diff --git a/gen/adexchangebuyer1d3-cli/Cargo.toml b/gen/adexchangebuyer1d3-cli/Cargo.toml index f803de55b9..cb8cb05697 100644 --- a/gen/adexchangebuyer1d3-cli/Cargo.toml +++ b/gen/adexchangebuyer1d3-cli/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-adexchangebuyer1d3-cli" -version = "0.3.2+20150720" +version = "0.3.2+20150909" 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-cli" diff --git a/gen/adexchangebuyer1d3-cli/README.md b/gen/adexchangebuyer1d3-cli/README.md index d4b552f271..96800d2b41 100644 --- a/gen/adexchangebuyer1d3-cli/README.md +++ b/gen/adexchangebuyer1d3-cli/README.md @@ -24,7 +24,7 @@ Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/ma # Usage -This documentation was generated from the *Ad Exchange Buyer* API at revision *20150720*. The CLI is at version *0.3.2*. +This documentation was generated from the *Ad Exchange Buyer* API at revision *20150909*. The CLI is at version *0.3.2*. ```bash adexchangebuyer1d3 [options] diff --git a/gen/adexchangebuyer1d3-cli/mkdocs.yml b/gen/adexchangebuyer1d3-cli/mkdocs.yml index dc16b34fd5..832cc1a10d 100644 --- a/gen/adexchangebuyer1d3-cli/mkdocs.yml +++ b/gen/adexchangebuyer1d3-cli/mkdocs.yml @@ -1,4 +1,4 @@ -site_name: Ad Exchange Buyer v0.3.2+20150720 +site_name: Ad Exchange Buyer v0.3.2+20150909 site_url: http://byron.github.io/google-apis-rs/google-adexchangebuyer1d3-cli site_description: Write integrating applications with bcore diff --git a/gen/adexchangebuyer1d3-cli/src/main.rs b/gen/adexchangebuyer1d3-cli/src/main.rs index 584d93b3b3..71d07a5966 100644 --- a/gen/adexchangebuyer1d3-cli/src/main.rs +++ b/gen/adexchangebuyer1d3-cli/src/main.rs @@ -747,26 +747,47 @@ impl<'n, 'a> Engine<'n, 'a> { let type_info: Option<(&'static str, JsonTypeInfo)> = match &temp_cursor.to_string()[..] { - "product-categories" => Some(("productCategories", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Vec })), - "status" => Some(("status", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), - "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), - "video-url" => Some(("videoURL", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), - "agency-id" => Some(("agencyId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), - "width" => Some(("width", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "api-upload-timestamp" => Some(("api_upload_timestamp", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "attribute" => Some(("attribute", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Vec })), - "restricted-categories" => Some(("restrictedCategories", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Vec })), "height" => Some(("height", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), "advertiser-name" => Some(("advertiserName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "html-snippet" => Some(("HTMLSnippet", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), - "advertiser-id" => Some(("advertiserId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), "buyer-creative-id" => Some(("buyerCreativeId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), - "click-through-url" => Some(("clickThroughUrl", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), - "vendor-type" => Some(("vendorType", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Vec })), - "filtering-reasons.date" => Some(("filteringReasons.date", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), - "sensitive-categories" => Some(("sensitiveCategories", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Vec })), + "impression-tracking-url" => Some(("impressionTrackingUrl", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "video-url" => Some(("videoURL", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "click-through-url" => Some(("clickThroughUrl", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "width" => Some(("width", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "native-ad.body" => Some(("nativeAd.body", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "native-ad.advertiser" => Some(("nativeAd.advertiser", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "native-ad.store" => Some(("nativeAd.store", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "native-ad.headline" => Some(("nativeAd.headline", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "native-ad.image.url" => Some(("nativeAd.image.url", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "native-ad.image.width" => Some(("nativeAd.image.width", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "native-ad.image.height" => Some(("nativeAd.image.height", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "native-ad.star-rating" => Some(("nativeAd.starRating", JsonTypeInfo { jtype: JsonType::Float, ctype: ComplexType::Pod })), + "native-ad.call-to-action" => Some(("nativeAd.callToAction", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "native-ad.logo.url" => Some(("nativeAd.logo.url", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "native-ad.logo.width" => Some(("nativeAd.logo.width", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "native-ad.logo.height" => Some(("nativeAd.logo.height", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "native-ad.app-icon.url" => Some(("nativeAd.appIcon.url", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "native-ad.app-icon.width" => Some(("nativeAd.appIcon.width", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "native-ad.app-icon.height" => Some(("nativeAd.appIcon.height", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "native-ad.impression-tracking-url" => Some(("nativeAd.impressionTrackingUrl", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "native-ad.price" => Some(("nativeAd.price", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "native-ad.click-tracking-url" => Some(("nativeAd.clickTrackingUrl", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "version" => Some(("version", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "vendor-type" => Some(("vendorType", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Vec })), + "sensitive-categories" => Some(("sensitiveCategories", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Vec })), + "product-categories" => Some(("productCategories", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Vec })), + "agency-id" => Some(("agencyId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id" => Some(("advertiserId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "status" => Some(("status", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "restricted-categories" => Some(("restrictedCategories", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Vec })), + "filtering-reasons.date" => Some(("filteringReasons.date", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), _ => { - let suggestion = FieldCursor::did_you_mean(key, &vec!["html-snippet", "account-id", "advertiser-id", "advertiser-name", "agency-id", "attribute", "buyer-creative-id", "click-through-url", "date", "filtering-reasons", "height", "kind", "product-categories", "restricted-categories", "sensitive-categories", "status", "vendor-type", "video-url", "width"]); + let suggestion = FieldCursor::did_you_mean(key, &vec!["html-snippet", "account-id", "advertiser", "advertiser-id", "advertiser-name", "agency-id", "api-upload-timestamp", "app-icon", "attribute", "body", "buyer-creative-id", "call-to-action", "click-through-url", "click-tracking-url", "date", "filtering-reasons", "headline", "height", "image", "impression-tracking-url", "kind", "logo", "native-ad", "price", "product-categories", "restricted-categories", "sensitive-categories", "star-rating", "status", "store", "url", "vendor-type", "version", "video-url", "width"]); err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); None } @@ -2282,7 +2303,7 @@ fn main() { let mut app = App::new("adexchangebuyer1d3") .author("Sebastian Thiel ") - .version("0.3.2+20150720") + .version("0.3.2+20150909") .about("Accesses your bidding-account information, submits creatives for validation, finds available direct deals, and retrieves performance reports.") .after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_adexchangebuyer1d3_cli") .arg(Arg::with_name("url") diff --git a/gen/adexchangebuyer1d3/Cargo.toml b/gen/adexchangebuyer1d3/Cargo.toml index aaa92d10f2..31b443eda0 100644 --- a/gen/adexchangebuyer1d3/Cargo.toml +++ b/gen/adexchangebuyer1d3/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-adexchangebuyer1d3" -version = "0.1.9+20150720" +version = "0.1.9+20150909" 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" diff --git a/gen/adexchangebuyer1d3/README.md b/gen/adexchangebuyer1d3/README.md index f26ec11d2d..bbe60cacfa 100644 --- a/gen/adexchangebuyer1d3/README.md +++ b/gen/adexchangebuyer1d3/README.md @@ -5,7 +5,7 @@ DO NOT EDIT ! --> 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.9+20150720*, where *20150720* is the exact revision of the *adexchangebuyer:v1.3* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +This documentation was generated from *Ad Exchange Buyer* crate version *0.1.9+20150909*, where *20150909* is the exact revision of the *adexchangebuyer:v1.3* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. 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). diff --git a/gen/adexchangebuyer1d3/src/lib.rs b/gen/adexchangebuyer1d3/src/lib.rs index bae774ae81..899c4a753e 100644 --- a/gen/adexchangebuyer1d3/src/lib.rs +++ b/gen/adexchangebuyer1d3/src/lib.rs @@ -2,7 +2,7 @@ // This file was generated automatically from 'src/mako/api/lib.rs.mako' // DO NOT EDIT ! -//! This documentation was generated from *Ad Exchange Buyer* crate version *0.1.9+20150720*, where *20150720* is the exact revision of the *adexchangebuyer:v1.3* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +//! This documentation was generated from *Ad Exchange Buyer* crate version *0.1.9+20150909*, where *20150909* is the exact revision of the *adexchangebuyer:v1.3* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. //! //! 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). diff --git a/gen/adexchangebuyer1d3/src/lib.rs.in b/gen/adexchangebuyer1d3/src/lib.rs.in index 88b6f047ad..f9edc29a4f 100644 --- a/gen/adexchangebuyer1d3/src/lib.rs.in +++ b/gen/adexchangebuyer1d3/src/lib.rs.in @@ -173,12 +173,30 @@ impl<'a, C, A> AdExchangeBuyer // ############ // SCHEMAS ### // ########## -/// Requests containing any of these placements will not match. +/// A large 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 PretargetingConfigExcludedPlacements { +pub struct CreativeNativeAdImage { + /// no description provided + pub url: Option, + /// no description provided + pub width: Option, + /// no description provided + pub height: Option, +} + +impl NestedType for CreativeNativeAdImage {} +impl Part for CreativeNativeAdImage {} + + +/// 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: Option, /// The type of the placement. @@ -186,8 +204,126 @@ pub struct PretargetingConfigExcludedPlacements { pub type_: Option, } -impl NestedType for PretargetingConfigExcludedPlacements {} -impl Part for PretargetingConfigExcludedPlacements {} +impl NestedType for PretargetingConfigPlacements {} +impl Part for PretargetingConfigPlacements {} + + +/// 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(rename="productCategories")] + pub product_categories: Option>, + /// The last upload timestamp of this creative if it was uploaded via API. Read-only. The value of this field is generated, and will be ignored for uploads. (formatted RFC 3339 timestamp). + pub api_upload_timestamp: Option, + /// The agency id for this creative. + #[serde(rename="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(rename="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(rename="HTMLSnippet")] + pub html_snippet: Option, + /// A buyer-specific id identifying the creative in this ad. + #[serde(rename="buyerCreativeId")] + pub buyer_creative_id: Option, + /// The set of urls to be called to record an impression. + #[serde(rename="impressionTrackingUrl")] + pub impression_tracking_url: Option>, + /// Account id. + #[serde(rename="accountId")] + pub account_id: Option, + /// Detected advertiser id, if any. Read-only. This field should not be set in requests. + #[serde(rename="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(rename="videoURL")] + pub video_url: Option, + /// The set of destination urls for the snippet. + #[serde(rename="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, + /// If nativeAd is set, HTMLSnippet and videoURL should not be set. + #[serde(rename="nativeAd")] + pub native_ad: Option, + /// The version for this creative. Read-only. This field should not be set in requests. + pub version: Option, + /// Creative serving status. Read-only. This field should not be set in requests. + pub status: Option, + /// All restricted categories for the ads that may be shown from this snippet. + #[serde(rename="restrictedCategories")] + pub restricted_categories: Option>, + /// All vendor types for the ads that may be shown from this snippet. + #[serde(rename="vendorType")] + pub vendor_type: Option>, + /// The filtering reasons for the creative. Read-only. This field should not be set in requests. + #[serde(rename="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(rename="disapprovalReasons")] + pub disapproval_reasons: Option>, + /// Detected sensitive categories, if any. Read-only. This field should not be set in requests. + #[serde(rename="sensitiveCategories")] + pub sensitive_categories: Option>, +} + +impl RequestValue for Creative {} +impl Resource for Creative {} +impl ResponseResult for Creative {} + + +/// The filtering reasons for the 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 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: Option, + /// The filtering reasons. + pub reasons: Option>, +} + +impl NestedType for CreativeFilteringReasons {} +impl Part for CreativeFilteringReasons {} + + +/// The app icon, for app download 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 CreativeNativeAdAppIcon { + /// no description provided + pub url: Option, + /// no description provided + pub width: Option, + /// no description provided + pub height: Option, +} + +impl NestedType for CreativeNativeAdAppIcon {} +impl Part for CreativeNativeAdAppIcon {} /// 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. @@ -206,6 +342,189 @@ impl NestedType for CreativeDisapprovalReasons {} impl Part for CreativeDisapprovalReasons {} +/// A smaller image, for the advertiser logo. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct CreativeNativeAdLogo { + /// no description provided + pub url: Option, + /// no description provided + pub width: Option, + /// no description provided + pub height: Option, +} + +impl NestedType for CreativeNativeAdLogo {} +impl Part for CreativeNativeAdLogo {} + + +/// 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, Serialize, Deserialize)] +pub struct DirectDealsList { + /// Resource type. + pub kind: Option, + /// A list of direct deals relevant for your account. + #[serde(rename="directDeals")] + pub direct_deals: Option>, +} + +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, Serialize, Deserialize)] +pub struct AccountsList { + /// A list of accounts. + pub items: Option>, + /// Resource type. + pub kind: Option, +} + +impl ResponseResult for AccountsList {} + + +/// 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: Option, + /// Additional details about the correction. + pub details: Option>, +} + +impl NestedType for CreativeCorrections {} +impl Part for CreativeCorrections {} + + +/// 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(rename="filteringCount")] + pub filtering_count: Option, + /// The filtering status code. Please refer to the creative-status-codes.txt file for different statuses. + #[serde(rename="filteringStatus")] + pub filtering_status: Option, +} + +impl NestedType for CreativeFilteringReasonsReasons {} +impl Part for CreativeFilteringReasonsReasons {} + + +/// 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, Serialize, Deserialize)] +pub struct DirectDeal { + /// The name of the advertiser this deal is for. + pub advertiser: Option, + /// Resource type. + pub kind: Option, + /// Deal name. + pub name: Option, + /// The currency code that applies to the fixed_cpm value. If not set then assumed to be USD. + #[serde(rename="currencyCode")] + pub currency_code: Option, + /// The account id of the buyer this deal is for. + #[serde(rename="accountId")] + pub account_id: Option, + /// 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(rename="fixedCpm")] + pub fixed_cpm: Option, + /// 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(rename="startTime")] + pub start_time: Option, + /// If true, the publisher has opted to have their blocks ignored when a creative is bid with for this deal. + #[serde(rename="publisherBlocksOverriden")] + pub publisher_blocks_overriden: Option, + /// 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(rename="endTime")] + pub end_time: Option, + /// The name of the publisher offering this direct deal. + #[serde(rename="sellerNetwork")] + pub seller_network: Option, + /// Deal id. + pub id: Option, + /// 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(rename="privateExchangeMinCpm")] + pub private_exchange_min_cpm: Option, +} + +impl Resource for DirectDeal {} +impl ResponseResult for DirectDeal {} + + +/// 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: Option, + /// 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: Option, + /// The maximum queries per second the Ad Exchange will send. + #[serde(rename="maximumQps")] + pub maximum_qps: Option, +} + +impl NestedType for AccountBidderLocation {} +impl Part for AccountBidderLocation {} + + +/// 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: Option, + /// The type of the placement. + #[serde(rename="type")] + pub type_: Option, +} + +impl NestedType for PretargetingConfigExcludedPlacements {} +impl Part for PretargetingConfigExcludedPlacements {} + + /// Configuration data for an Ad Exchange buyer account. /// /// # Activities @@ -269,22 +588,6 @@ pub struct PretargetingConfigList { impl ResponseResult for PretargetingConfigList {} -/// The filtering reasons for the 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 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: Option, - /// The filtering reasons. - pub reasons: Option>, -} - -impl NestedType for CreativeFilteringReasons {} -impl Part for CreativeFilteringReasons {} - - /// The configuration data for an Ad Exchange billing info. /// /// # Activities @@ -312,70 +615,6 @@ pub struct BillingInfo { 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, Serialize, Deserialize)] -pub struct DirectDealsList { - /// Resource type. - pub kind: Option, - /// A list of direct deals relevant for your account. - #[serde(rename="directDeals")] - pub direct_deals: Option>, -} - -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, Serialize, Deserialize)] -pub struct AccountsList { - /// A list of accounts. - pub items: Option>, - /// Resource type. - pub kind: Option, -} - -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, Serialize, 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(rename="nextPageToken")] - pub next_page_token: Option, - /// A list of creatives. - pub items: Option>, - /// Resource type. - pub kind: Option, -} - -impl ResponseResult for CreativesList {} - - /// The configuration data for Ad Exchange RTB - Budget API. /// /// # Activities @@ -411,152 +650,6 @@ 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(rename="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(rename="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(rename="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(rename="HTMLSnippet")] - pub html_snippet: Option, - /// A buyer-specific id identifying the creative in this ad. - #[serde(rename="buyerCreativeId")] - pub buyer_creative_id: Option, - /// Account id. - #[serde(rename="accountId")] - pub account_id: Option, - /// Detected advertiser id, if any. Read-only. This field should not be set in requests. - #[serde(rename="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(rename="videoURL")] - pub video_url: Option, - /// The set of destination urls for the snippet. - #[serde(rename="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(rename="restrictedCategories")] - pub restricted_categories: Option>, - /// All vendor types for the ads that may be shown from this snippet. - #[serde(rename="vendorType")] - pub vendor_type: Option>, - /// The filtering reasons for the creative. Read-only. This field should not be set in requests. - #[serde(rename="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(rename="disapprovalReasons")] - pub disapproval_reasons: Option>, - /// Detected sensitive categories, if any. Read-only. This field should not be set in requests. - #[serde(rename="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, Serialize, Deserialize)] -pub struct PerformanceReportList { - /// Resource type. - pub kind: Option, - /// A list of performance reports relevant for the account. - #[serde(rename="performanceReport")] - pub performance_report: Option>, -} - -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(rename="filteringCount")] - pub filtering_count: Option, - /// The filtering status code. Please refer to the creative-status-codes.txt file for different statuses. - #[serde(rename="filteringStatus")] - pub filtering_status: Option, -} - -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: Option, - /// The type of the placement. - #[serde(rename="type")] - pub type_: Option, -} - -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: Option, - /// Height in pixels. - pub height: Option, -} - -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. @@ -631,20 +724,25 @@ pub struct PerformanceReport { impl Part for PerformanceReport {} -/// Shows any corrections that were applied to this creative. Read-only. This field should not be set in requests. +/// 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 /// -/// This type is not used in any activity, and only used as *part* of another schema. +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where 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, Serialize, Deserialize)] -pub struct CreativeCorrections { - /// The type of correction that was applied to the creative. - pub reason: Option, - /// Additional details about the correction. - pub details: Option>, +pub struct PerformanceReportList { + /// Resource type. + pub kind: Option, + /// A list of performance reports relevant for the account. + #[serde(rename="performanceReport")] + pub performance_report: Option>, } -impl NestedType for CreativeCorrections {} -impl Part for CreativeCorrections {} +impl ResponseResult for PerformanceReportList {} /// 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. @@ -667,56 +765,6 @@ pub struct BillingInfoList { 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, Serialize, Deserialize)] -pub struct DirectDeal { - /// The name of the advertiser this deal is for. - pub advertiser: Option, - /// Resource type. - pub kind: Option, - /// Deal name. - pub name: Option, - /// The currency code that applies to the fixed_cpm value. If not set then assumed to be USD. - #[serde(rename="currencyCode")] - pub currency_code: Option, - /// The account id of the buyer this deal is for. - #[serde(rename="accountId")] - pub account_id: Option, - /// 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(rename="fixedCpm")] - pub fixed_cpm: Option, - /// 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(rename="startTime")] - pub start_time: Option, - /// If true, the publisher has opted to have their blocks ignored when a creative is bid with for this deal. - #[serde(rename="publisherBlocksOverriden")] - pub publisher_blocks_overriden: Option, - /// 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(rename="endTime")] - pub end_time: Option, - /// The name of the publisher offering this direct deal. - #[serde(rename="sellerNetwork")] - pub seller_network: Option, - /// Deal id. - pub id: Option, - /// 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(rename="privateExchangeMinCpm")] - pub private_exchange_min_cpm: Option, -} - -impl Resource for DirectDeal {} -impl ResponseResult for DirectDeal {} - - /// There is no detailed description. /// /// # Activities @@ -800,27 +848,84 @@ impl RequestValue for PretargetingConfig {} impl ResponseResult for PretargetingConfig {} -/// Your bidder locations that have distinct URLs. +/// 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 AccountBidderLocation { - /// The URL to which the Ad Exchange will send bid requests. - pub url: Option, - /// 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: Option, - /// The maximum queries per second the Ad Exchange will send. - #[serde(rename="maximumQps")] - pub maximum_qps: Option, +pub struct PretargetingConfigDimensions { + /// Width in pixels. + pub width: Option, + /// Height in pixels. + pub height: Option, } -impl NestedType for AccountBidderLocation {} -impl Part for AccountBidderLocation {} +impl NestedType for PretargetingConfigDimensions {} +impl Part for PretargetingConfigDimensions {} + + +/// 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, Serialize, 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(rename="nextPageToken")] + pub next_page_token: Option, + /// A list of creatives. + pub items: Option>, + /// Resource type. + pub kind: Option, +} + +impl ResponseResult for CreativesList {} + + +/// If nativeAd is set, HTMLSnippet and videoURL should not be 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 CreativeNativeAd { + /// A long description of the ad. + pub body: Option, + /// no description provided + pub advertiser: Option, + /// A short title for the ad. + pub headline: Option, + /// A large image. + pub image: Option, + /// The app rating in the app store. Must be in the range [0-5]. + #[serde(rename="starRating")] + pub star_rating: Option, + /// The URL to use for click tracking. + #[serde(rename="clickTrackingUrl")] + pub click_tracking_url: Option, + /// A label for the button that the user is supposed to click. + #[serde(rename="callToAction")] + pub call_to_action: Option, + /// The app icon, for app download ads. + #[serde(rename="appIcon")] + pub app_icon: Option, + /// A smaller image, for the advertiser logo. + pub logo: Option, + /// The URLs are called when the impression is rendered. + #[serde(rename="impressionTrackingUrl")] + pub impression_tracking_url: Option>, + /// The price of the promoted app including the currency info. + pub price: Option, + /// The URL to the app store to purchase/download the promoted app. + pub store: Option, +} + +impl NestedType for CreativeNativeAd {} +impl Part for CreativeNativeAd {} diff --git a/gen/adexchangebuyer1d4-cli/Cargo.toml b/gen/adexchangebuyer1d4-cli/Cargo.toml new file mode 100644 index 0000000000..7d8c9b02b4 --- /dev/null +++ b/gen/adexchangebuyer1d4-cli/Cargo.toml @@ -0,0 +1,35 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-adexchangebuyer1d4-cli" +version = "0.3.2+20150909" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with Ad Exchange Buyer (protocol v1.4)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/adexchangebuyer1d4-cli" +homepage = "https://developers.google.com/ad-exchange/buyer-rest" +documentation = "http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4_cli" +license = "MIT" +keywords = ["adexchangebuyer", "google", "cli"] + +[[bin]] +name = "adexchangebuyer1d4" + +[dependencies] +hyper = ">= 0.6.8" +mime = "0.1.0" +serde = ">= 0.6.0" +serde_json = ">= 0.6.0" +yup-oauth2 = "*" +strsim = "*" +yup-hyper-mock = ">=1.0.0" +clap = ">= 1.0.3" + +[build-dependencies] +syntex = { version = "*" } +serde_codegen = { version = "*" } + + +[dependencies.google-adexchangebuyer1d4] +path = "../adexchangebuyer1d4" diff --git a/gen/adexchangebuyer1d4-cli/LICENSE.md b/gen/adexchangebuyer1d4-cli/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/adexchangebuyer1d4-cli/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/adexchangebuyer1d4-cli/README.md b/gen/adexchangebuyer1d4-cli/README.md new file mode 100644 index 0000000000..7496d56043 --- /dev/null +++ b/gen/adexchangebuyer1d4-cli/README.md @@ -0,0 +1,172 @@ + +The `adexchangebuyer1d4` command-line interface *(CLI)* allows to use most features of the *Google Ad Exchange Buyer* service from the comfort of your terminal. + +By default all output is printed to standard out, but flags can be set to direct it into a file independent of your shell's +capabilities. Errors will be printed to standard error, and cause the program's exit code to be non-zero. + +If data-structures are requested, these will be returned as pretty-printed JSON, to be useful as input to other tools. + +Everything else about the *Ad Exchange Buyer* API can be found at the +[official documentation site](https://developers.google.com/ad-exchange/buyer-rest). + +# Downloads + +You can download the pre-compiled 64bit binaries for the following platforms: + +* ![icon](http://megaicons.net/static/img/icons_sizes/6/140/16/ubuntu-icon.png) [ubuntu](http://dl.byronimo.de/google.rs/cli/0.3.2/ubuntu/adexchangebuyer1d4.tar.gz) +* ![icon](http://hydra-media.cursecdn.com/wow.gamepedia.com/a/a2/Apple-icon-16x16.png?version=25ddd67ac3dd3b634478e3978b76cb74) [osx](http://dl.byronimo.de/google.rs/cli/0.3.2/osx/adexchangebuyer1d4.tar.gz) + +Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/adexchangebuyer1d4-cli). + +# Usage + +This documentation was generated from the *Ad Exchange Buyer* API at revision *20150909*. The CLI is at version *0.3.2*. + +```bash +adexchangebuyer1d4 [options] + accounts + get [-p ]... [-o ] + list [-p ]... [-o ] + patch (-r )... [-p ]... [-o ] + update (-r )... [-p ]... [-o ] + billing-info + get [-p ]... [-o ] + list [-p ]... [-o ] + budget + get [-p ]... [-o ] + patch (-r )... [-p ]... [-o ] + update (-r )... [-p ]... [-o ] + clientaccess + delete [-p ]... + get [-p ]... [-o ] + insert (-r )... [-p ]... [-o ] + list (-r )... [-p ]... [-o ] + patch (-r )... [-p ]... [-o ] + update (-r )... [-p ]... [-o ] + creatives + get [-p ]... [-o ] + insert (-r )... [-p ]... [-o ] + list [-p ]... [-o ] + deals + get (-r )... [-p ]... [-o ] + marketplacedeals + delete (-r )... [-p ]... [-o ] + insert (-r )... [-p ]... [-o ] + list [-p ]... [-o ] + update (-r )... [-p ]... [-o ] + marketplacenotes + insert (-r )... [-p ]... [-o ] + list [-p ]... [-o ] + marketplaceoffers + get [-p ]... [-o ] + search [-p ]... [-o ] + marketplaceorders + get [-p ]... [-o ] + insert (-r )... [-p ]... [-o ] + patch (-r )... [-p ]... [-o ] + search [-p ]... [-o ] + update (-r )... [-p ]... [-o ] + negotiationrounds + insert (-r )... [-p ]... [-o ] + negotiations + get (-r )... [-p ]... [-o ] + insert (-r )... [-p ]... [-o ] + list (-r )... [-p ]... [-o ] + offers + get [-p ]... [-o ] + insert (-r )... [-p ]... [-o ] + list (-r )... [-p ]... [-o ] + performance-report + list [-p ]... [-o ] + pretargeting-config + delete [-p ]... + get [-p ]... [-o ] + insert (-r )... [-p ]... [-o ] + list [-p ]... [-o ] + patch (-r )... [-p ]... [-o ] + update (-r )... [-p ]... [-o ] + adexchangebuyer1d4 --help + +Configuration: + [--scope ]... + Specify the authentication a method should be executed in. Each scope + requires the user to grant this application permission to use it. + If unset, it defaults to the shortest scope url for a particular method. + --config-dir + A directory into which we will store our persistent data. Defaults to + a user-writable directory that we will create during the first invocation. + [default: ~/.google-service-cli] + --debug + Output all server communication to standard error. `tx` and `rx` are placed + into the same stream. + --debug-auth + Output all communication related to authentication to standard error. `tx` + and `rx` are placed into the same stream. + +``` + +# Configuration + +The program will store all persistent data in the `~/.google-service-cli` directory in *JSON* files prefixed with `adexchangebuyer1d4-`. You can change the directory used to store configuration with the `--config-dir` flag on a per-invocation basis. + +More information about the various kinds of persistent data are given in the following paragraphs. + +# Authentication + +Most APIs require a user to authenticate any request. If this is the case, the [scope][scopes] determines the +set of permissions granted. The granularity of these is usually no more than *read-only* or *full-access*. + +If not set, the system will automatically select the smallest feasible scope, e.g. when invoking a +method that is read-only, it will ask only for a read-only scope. +You may use the `--scope` flag to specify a scope directly. +All applicable scopes are documented in the respective method's CLI documentation. + +The first time a scope is used, the user is asked for permission. Follow the instructions given +by the CLI to grant permissions, or to decline. + +If a scope was authenticated by the user, the respective information will be stored as *JSON* in the configuration +directory, e.g. `~/.google-service-cli/adexchangebuyer1d4-token-.json`. No manual management of these tokens +is necessary. + +To revoke granted authentication, please refer to the [official documentation][revoke-access]. + +# Application Secrets + +In order to allow any application to use Google services, it will need to be registered using the +[Google Developer Console][google-dev-console]. APIs the application may use are then enabled for it +one by one. Most APIs can be used for free and have a daily quota. + +To allow more comfortable usage of the CLI without forcing anyone to register an own application, the CLI +comes with a default application secret that is configured accordingly. This also means that heavy usage +all around the world may deplete the daily quota. + +You can workaround this limitation by putting your own secrets file at this location: +`~/.google-service-cli/adexchangebuyer1d4-secret.json`, assuming that the required *adexchangebuyer* API +was enabled for it. Such a secret file can be downloaded in the *Google Developer Console* at +*APIs & auth -> Credentials -> Download JSON* and used as is. + +Learn more about how to setup Google projects and enable APIs using the [official documentation][google-project-new]. + + +# Debugging + +Even though the CLI does its best to provide usable error messages, sometimes it might be desirable to know +what exactly led to a particular issue. This is done by allowing all client-server communication to be +output to standard error *as-is*. + +The `--debug` flag will print all client-server communication to standard error, whereas the `--debug-auth` flag +will cause all communication related to authentication to standard error. +If the `--debug` flag is set, error-results will be debug-printed, possibly yielding more information about the +issue at hand. + +You may consider redirecting standard error into a file for ease of use, e.g. `adexchangebuyer1d4 --debug [options] 2>debug.txt`. + + +[scopes]: https://developers.google.com/+/api/oauth#scopes +[revoke-access]: http://webapps.stackexchange.com/a/30849 +[google-dev-console]: https://console.developers.google.com/ +[google-project-new]: https://developers.google.com/console/help/new/ \ No newline at end of file diff --git a/gen/adexchangebuyer1d4-cli/mkdocs.yml b/gen/adexchangebuyer1d4-cli/mkdocs.yml new file mode 100644 index 0000000000..89be06a785 --- /dev/null +++ b/gen/adexchangebuyer1d4-cli/mkdocs.yml @@ -0,0 +1,62 @@ +site_name: Ad Exchange Buyer v0.3.2+20150909 +site_url: http://byron.github.io/google-apis-rs/google-adexchangebuyer1d4-cli +site_description: Write integrating applications with bcore + +repo_url: https://github.com/Byron/google-apis-rs/tree/master/gen/adexchangebuyer1d4-cli + +docs_dir: docs +site_dir: build_html + +pages: +- ['index.md', 'Home'] +- ['accounts_get.md', 'Accounts', 'Get'] +- ['accounts_list.md', 'Accounts', 'List'] +- ['accounts_patch.md', 'Accounts', 'Patch'] +- ['accounts_update.md', 'Accounts', 'Update'] +- ['billing-info_get.md', 'Billing Info', 'Get'] +- ['billing-info_list.md', 'Billing Info', 'List'] +- ['budget_get.md', 'Budget', 'Get'] +- ['budget_patch.md', 'Budget', 'Patch'] +- ['budget_update.md', 'Budget', 'Update'] +- ['clientaccess_delete.md', 'Clientaccess', 'Delete'] +- ['clientaccess_get.md', 'Clientaccess', 'Get'] +- ['clientaccess_insert.md', 'Clientaccess', 'Insert'] +- ['clientaccess_list.md', 'Clientaccess', 'List'] +- ['clientaccess_patch.md', 'Clientaccess', 'Patch'] +- ['clientaccess_update.md', 'Clientaccess', 'Update'] +- ['creatives_get.md', 'Creatives', 'Get'] +- ['creatives_insert.md', 'Creatives', 'Insert'] +- ['creatives_list.md', 'Creatives', 'List'] +- ['deals_get.md', 'Deals', 'Get'] +- ['marketplacedeals_delete.md', 'Marketplacedeals', 'Delete'] +- ['marketplacedeals_insert.md', 'Marketplacedeals', 'Insert'] +- ['marketplacedeals_list.md', 'Marketplacedeals', 'List'] +- ['marketplacedeals_update.md', 'Marketplacedeals', 'Update'] +- ['marketplacenotes_insert.md', 'Marketplacenotes', 'Insert'] +- ['marketplacenotes_list.md', 'Marketplacenotes', 'List'] +- ['marketplaceoffers_get.md', 'Marketplaceoffers', 'Get'] +- ['marketplaceoffers_search.md', 'Marketplaceoffers', 'Search'] +- ['marketplaceorders_get.md', 'Marketplaceorders', 'Get'] +- ['marketplaceorders_insert.md', 'Marketplaceorders', 'Insert'] +- ['marketplaceorders_patch.md', 'Marketplaceorders', 'Patch'] +- ['marketplaceorders_search.md', 'Marketplaceorders', 'Search'] +- ['marketplaceorders_update.md', 'Marketplaceorders', 'Update'] +- ['negotiationrounds_insert.md', 'Negotiationrounds', 'Insert'] +- ['negotiations_get.md', 'Negotiations', 'Get'] +- ['negotiations_insert.md', 'Negotiations', 'Insert'] +- ['negotiations_list.md', 'Negotiations', 'List'] +- ['offers_get.md', 'Offers', 'Get'] +- ['offers_insert.md', 'Offers', 'Insert'] +- ['offers_list.md', 'Offers', 'List'] +- ['performance-report_list.md', 'Performance Report', 'List'] +- ['pretargeting-config_delete.md', 'Pretargeting Config', 'Delete'] +- ['pretargeting-config_get.md', 'Pretargeting Config', 'Get'] +- ['pretargeting-config_insert.md', 'Pretargeting Config', 'Insert'] +- ['pretargeting-config_list.md', 'Pretargeting Config', 'List'] +- ['pretargeting-config_patch.md', 'Pretargeting Config', 'Patch'] +- ['pretargeting-config_update.md', 'Pretargeting Config', 'Update'] + +theme: readthedocs + +copyright: Copyright © 2015, `Sebastian Thiel` + diff --git a/gen/adexchangebuyer1d4-cli/src/cmn.rs b/gen/adexchangebuyer1d4-cli/src/cmn.rs new file mode 100644 index 0000000000..8358f156fa --- /dev/null +++ b/gen/adexchangebuyer1d4-cli/src/cmn.rs @@ -0,0 +1,721 @@ +// COPY OF 'src/rust/cli/cmn.rs' +// DO NOT EDIT +use oauth2::{ApplicationSecret, ConsoleApplicationSecret, TokenStorage, Token}; +use serde_json as json; +use serde_json::value::Value; +use mime::Mime; +use clap::{App, SubCommand}; +use strsim; + +use std::fs; +use std::env; +use std::io; +use std::fmt; +use std::path::{Path, PathBuf}; +use std::str::FromStr; +use std::string::ToString; +use std::io::{Write, Read, stdout}; + +use std::default::Default; + +const FIELD_SEP: char = '.'; + + +pub enum ComplexType { + Pod, + Vec, + Map, +} + + // Null, + // Bool(bool), + // I64(i64), + // U64(u64), + // F64(f64), + // String(String), + +pub enum JsonType { + Boolean, + Int, + Uint, + Float, + String, +} + +pub struct JsonTypeInfo { + pub jtype: JsonType, + pub ctype: ComplexType, +} + +// Based on @erickt user comment. Thanks for the idea ! +// Remove all keys whose values are null from given value (changed in place) +pub fn remove_json_null_values(value: &mut Value) { + match *value { + Value::Object(ref mut map) => { + let mut for_removal = Vec::new(); + + for (key, mut value) in map.iter_mut() { + if value.is_null() { + for_removal.push(key.clone()); + } else { + remove_json_null_values(&mut value); + } + } + + for key in &for_removal { + map.remove(key); + } + } + _ => {} + } +} + +fn did_you_mean<'a>(v: &str, possible_values: &[&'a str]) -> Option<&'a str> { + + let mut candidate: Option<(f64, &str)> = None; + for pv in possible_values { + let confidence = strsim::jaro_winkler(v, pv); + if confidence > 0.8 && (candidate.is_none() || (candidate.as_ref().unwrap().0 < confidence)) { + candidate = Some((confidence, pv)); + } + } + match candidate { + None => None, + Some((_, candidate)) => Some(candidate), + } +} + +pub enum CallType { + Upload(UploadProtocol), + Standard, +} + +arg_enum!{ + pub enum UploadProtocol { + Simple, + Resumable + } +} + +impl AsRef for UploadProtocol { + fn as_ref(&self) -> &str { + match *self { + UploadProtocol::Simple => "simple", + UploadProtocol::Resumable => "resumable" + } + } +} + +impl AsRef for CallType { + fn as_ref(&self) -> &str { + match *self { + CallType::Upload(ref proto) => proto.as_ref(), + CallType::Standard => "standard-request" + } + } +} + +#[derive(Clone, Default)] +pub struct FieldCursor(Vec); + +impl ToString for FieldCursor { + fn to_string(&self) -> String { + self.0.join(".") + } +} + +impl From<&'static str> for FieldCursor { + fn from(value: &'static str) -> FieldCursor { + let mut res = FieldCursor::default(); + res.set(value).unwrap(); + res + } +} + +impl FieldCursor { + pub fn set(&mut self, value: &str) -> Result<(), CLIError> { + if value.len() == 0 { + return Err(CLIError::Field(FieldError::Empty)) + } + + let mut first_is_field_sep = false; + let mut char_count: usize = 0; + let mut last_c = FIELD_SEP; + let mut num_conscutive_field_seps = 0; + + let mut field = String::new(); + let mut fields = self.0.clone(); + + let push_field = |fs: &mut Vec, f: &mut String| { + if f.len() > 0 { + fs.push(f.clone()); + f.truncate(0); + } + }; + + for (cid, c) in value.chars().enumerate() { + char_count += 1; + + if c == FIELD_SEP { + if cid == 0 { + first_is_field_sep = true; + } + num_conscutive_field_seps += 1; + if cid > 0 && last_c == FIELD_SEP { + if fields.pop().is_none() { + return Err(CLIError::Field(FieldError::PopOnEmpty(value.to_string()))) + } + } else { + push_field(&mut fields, &mut field); + } + } else { + num_conscutive_field_seps = 0; + if cid == 1 { + if first_is_field_sep { + fields.truncate(0); + } + } + field.push(c); + } + + last_c = c; + } + + push_field(&mut fields, &mut field); + + if char_count == 1 && first_is_field_sep { + fields.truncate(0); + } + if char_count > 1 && num_conscutive_field_seps == 1 { + return Err(CLIError::Field(FieldError::TrailingFieldSep(value.to_string()))) + } + + self.0 = fields; + Ok(()) + } + + pub fn did_you_mean(value: &str, possible_values: &[&str]) -> Option { + if value.len() == 0 { + return None + } + + let mut last_c = FIELD_SEP; + + let mut field = String::new(); + let mut output = String::new(); + + let push_field = |fs: &mut String, f: &mut String| { + if f.len() > 0 { + fs.push_str( + match did_you_mean(&f, possible_values) { + Some(candidate) => candidate, + None => &f, + }); + f.truncate(0); + } + }; + + for (cid, c) in value.chars().enumerate() { + if c == FIELD_SEP { + if last_c != FIELD_SEP { + push_field(&mut output, &mut field); + } + output.push(c); + } else { + field.push(c); + } + + last_c = c; + } + + push_field(&mut output, &mut field); + + if &output == value { + None + } else { + Some(output) + } + } + + pub fn set_json_value(&self, mut object: &mut Value, + value: &str, type_info: JsonTypeInfo, + err: &mut InvalidOptionsError, + orig_cursor: &FieldCursor) { + assert!(self.0.len() > 0); + + for field in &self.0[..self.0.len()-1] { + let tmp = object; + object = + match *tmp { + Value::Object(ref mut mapping) => { + mapping.entry(field.to_owned()).or_insert( + Value::Object(Default::default()) + ) + }, + _ => panic!("We don't expect non-object Values here ...") + }; + } + + match *object { + Value::Object(ref mut mapping) => { + let field = &self.0[self.0.len()-1]; + let to_jval = + |value: &str, jtype: JsonType, err: &mut InvalidOptionsError| + -> Value { + match jtype { + JsonType::Boolean => + Value::Bool(arg_from_str(value, err, &field, "boolean")), + JsonType::Int => + Value::I64(arg_from_str(value, err, &field, "int")), + JsonType::Uint => + Value::U64(arg_from_str(value, err, &field, "uint")), + JsonType::Float => + Value::F64(arg_from_str(value, err, &field, "float")), + JsonType::String => + Value::String(value.to_owned()), + } + }; + + match type_info.ctype { + ComplexType::Pod => { + if mapping.insert(field.to_owned(), to_jval(value, type_info.jtype, err)).is_some() { + err.issues.push(CLIError::Field(FieldError::Duplicate(orig_cursor.to_string()))); + } + }, + ComplexType::Vec => { + match *mapping.entry(field.to_owned()) + .or_insert(Value::Array(Default::default())) { + Value::Array(ref mut values) => values.push(to_jval(value, type_info.jtype, err)), + _ => unreachable!() + } + }, + ComplexType::Map => { + let (key, value) = parse_kv_arg(value, err, true); + let jval = to_jval(value.unwrap_or(""), type_info.jtype, err); + + match *mapping.entry(field.to_owned()) + .or_insert(Value::Object(Default::default())) { + Value::Object(ref mut value_map) => { + if value_map.insert(key.to_owned(), jval).is_some() { + err.issues.push(CLIError::Field(FieldError::Duplicate(orig_cursor.to_string()))); + } + } + _ => unreachable!() + } + } + } + }, + _ => unreachable!() + } + } + + pub fn num_fields(&self) -> usize { + self.0.len() + } +} + +pub fn parse_kv_arg<'a>(kv: &'a str, err: &mut InvalidOptionsError, for_hashmap: bool) + -> (&'a str, Option<&'a str>) { + let mut add_err = || err.issues.push(CLIError::InvalidKeyValueSyntax(kv.to_string(),for_hashmap)); + match kv.find('=') { + None => { + add_err(); + return (kv, None) + }, + Some(pos) => { + let key = &kv[..pos]; + if kv.len() <= pos + 1 { + add_err(); + return (key, Some("")) + } + (key, Some(&kv[pos+1..])) + } + } +} + +pub fn calltype_from_str(name: &str, valid_protocols: Vec, err: &mut InvalidOptionsError) -> CallType { + CallType::Upload( + match UploadProtocol::from_str(name) { + Ok(up) => up, + Err(msg) => { + err.issues.push(CLIError::InvalidUploadProtocol(name.to_string(), valid_protocols)); + UploadProtocol::Simple + } + }) +} + +pub fn input_file_from_opts(file_path: &str, err: &mut InvalidOptionsError) -> Option { + match fs::File::open(file_path) { + Ok(f) => Some(f), + Err(io_err) => { + err.issues.push(CLIError::Input(InputError::IOError((file_path.to_string(), io_err)))); + None + } + } +} + +pub fn input_mime_from_opts(mime: &str, err: &mut InvalidOptionsError) -> Option { + match mime.parse() { + Ok(m) => Some(m), + Err(_) => { + err.issues.push(CLIError::Input(InputError::Mime(mime.to_string()))); + None + } + } +} + +pub fn writer_from_opts(arg: Option<&str>) -> Result, io::Error> { + let f = arg.unwrap_or("-"); + match f { + "-" => Ok(Box::new(stdout())), + _ => match fs::OpenOptions::new().create(true).write(true).open(f) { + Ok(f) => Ok(Box::new(f)), + Err(io_err) => Err(io_err), + } + } +} + + +pub fn arg_from_str<'a, T>(arg: &str, err: &mut InvalidOptionsError, + arg_name: &'a str, + arg_type: &'a str) -> T + where T: FromStr + Default, + ::Err: fmt::Display { + match FromStr::from_str(arg) { + Err(perr) => { + err.issues.push( + CLIError::ParseError(arg_name.to_owned(), arg_type.to_owned(), arg.to_string(), format!("{}", perr)) + ); + Default::default() + }, + Ok(v) => v, + } +} + +pub struct JsonTokenStorage { + pub program_name: &'static str, + pub db_dir: String, +} + +impl JsonTokenStorage { + fn path(&self, scope_hash: u64) -> PathBuf { + Path::new(&self.db_dir).join(&format!("{}-token-{}.json", self.program_name, scope_hash)) + } +} + +impl TokenStorage for JsonTokenStorage { + type Error = json::Error; + + // NOTE: logging might be interesting, currently we swallow all errors + fn set(&mut self, scope_hash: u64, _: &Vec<&str>, token: Option) -> Result<(), json::Error> { + match token { + None => { + match fs::remove_file(self.path(scope_hash)) { + Err(err) => + match err.kind() { + io::ErrorKind::NotFound => Ok(()), + _ => Err(json::Error::IoError(err)) + }, + Ok(_) => Ok(()), + } + } + Some(token) => { + match fs::OpenOptions::new().create(true).write(true).open(&self.path(scope_hash)) { + Ok(mut f) => { + match json::to_writer_pretty(&mut f, &token) { + Ok(_) => Ok(()), + Err(serde_err) => Err(serde_err), + } + }, + Err(io_err) => Err(json::Error::IoError(io_err)) + } + } + } + } + + fn get(&self, scope_hash: u64, _: &Vec<&str>) -> Result, json::Error> { + match fs::File::open(&self.path(scope_hash)) { + Ok(mut f) => { + match json::de::from_reader(f) { + Ok(token) => Ok(Some(token)), + Err(err) => Err(err), + } + }, + Err(io_err) => { + match io_err.kind() { + io::ErrorKind::NotFound => Ok(None), + _ => Err(json::Error::IoError(io_err)) + } + } + } + } +} + + +#[derive(Debug)] +pub enum ApplicationSecretError { + DecoderError((String, json::Error)), + FormatError(String), +} + +impl fmt::Display for ApplicationSecretError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + ApplicationSecretError::DecoderError((ref path, ref err)) + => writeln!(f, "Could not decode file at '{}' with error: {}.", + path, err), + ApplicationSecretError::FormatError(ref path) + => writeln!(f, "'installed' field is unset in secret file at '{}'.", + path), + } + } +} + +#[derive(Debug)] +pub enum ConfigurationError { + DirectoryCreationFailed((String, io::Error)), + DirectoryUnset, + HomeExpansionFailed(String), + Secret(ApplicationSecretError), + IOError((String, io::Error)), +} + +impl fmt::Display for ConfigurationError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + ConfigurationError::DirectoryCreationFailed((ref dir, ref err)) + => writeln!(f, "Directory '{}' could not be created with error: {}.", dir, err), + ConfigurationError::DirectoryUnset + => writeln!(f, "--config-dir was unset or empty."), + ConfigurationError::HomeExpansionFailed(ref dir) + => writeln!(f, "Couldn't find HOME directory of current user, failed to expand '{}'.", dir), + ConfigurationError::Secret(ref err) + => writeln!(f, "Secret -> {}", err), + ConfigurationError::IOError((ref path, ref err)) + => writeln!(f, "IO operation failed on path '{}' with error: {}.", path, err), + } + } +} + +#[derive(Debug)] +pub enum InputError { + IOError((String, io::Error)), + Mime(String), +} + +impl fmt::Display for InputError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + InputError::IOError((ref file_path, ref io_err)) + => writeln!(f, "Failed to open '{}' for reading with error: {}.", file_path, io_err), + InputError::Mime(ref mime) + => writeln!(f, "'{}' is not a known mime-type.", mime), + } + } +} + +#[derive(Debug)] +pub enum FieldError { + PopOnEmpty(String), + TrailingFieldSep(String), + Unknown(String, Option, Option), + Duplicate(String), + Empty, +} + + +impl fmt::Display for FieldError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + FieldError::PopOnEmpty(ref field) + => writeln!(f, "'{}': Cannot move up on empty field cursor.", field), + FieldError::TrailingFieldSep(ref field) + => writeln!(f, "'{}': Single field separator may not be last character.", field), + FieldError::Unknown(ref field, ref suggestion, ref value) => { + let suffix = + match *suggestion { + Some(ref s) => { + let kv = + match *value { + Some(ref v) => format!("{}={}", s, v), + None => s.clone(), + }; + format!(" Did you mean '{}' ?", kv) + }, + None => String::new(), + }; + writeln!(f, "Field '{}' does not exist.{}", field, suffix) + }, + FieldError::Duplicate(ref cursor) + => writeln!(f, "Value at '{}' was already set", cursor), + FieldError::Empty + => writeln!(f, "Field names must not be empty."), + } + } +} + + +#[derive(Debug)] +pub enum CLIError { + Configuration(ConfigurationError), + ParseError(String, String, String, String), + UnknownParameter(String, Vec<&'static str>), + InvalidUploadProtocol(String, Vec), + InvalidKeyValueSyntax(String, bool), + Input(InputError), + Field(FieldError), + MissingCommandError, + MissingMethodError(String), +} + +impl fmt::Display for CLIError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + CLIError::Configuration(ref err) => write!(f, "Configuration -> {}", err), + CLIError::Input(ref err) => write!(f, "Input -> {}", err), + CLIError::Field(ref err) => write!(f, "Field -> {}", err), + CLIError::InvalidUploadProtocol(ref proto_name, ref valid_names) + => writeln!(f, "'{}' is not a valid upload protocol. Choose from one of {}.", proto_name, valid_names.join(", ")), + CLIError::ParseError(ref arg_name, ref type_name, ref value, ref err_desc) + => writeln!(f, "Failed to parse argument '{}' with value '{}' as {} with error: {}.", + arg_name, value, type_name, err_desc), + CLIError::UnknownParameter(ref param_name, ref possible_values) => { + let mut suffix = + match did_you_mean(param_name, &possible_values) { + Some(v) => format!(" Did you mean '{}' ?", v), + None => String::new(), + }; + write!(f, "Parameter '{}' is unknown.{}\n", param_name, suffix) + }, + CLIError::InvalidKeyValueSyntax(ref kv, is_hashmap) => { + let hashmap_info = if is_hashmap { "hashmap " } else { "" }; + writeln!(f, "'{}' does not match {}pattern =.", kv, hashmap_info) + }, + CLIError::MissingCommandError => writeln!(f, "Please specify the main sub-command."), + CLIError::MissingMethodError(ref cmd) => writeln!(f, "Please specify the method to call on the '{}' command.", cmd), + } + } +} + +#[derive(Debug)] +pub struct InvalidOptionsError { + pub issues: Vec, + pub exit_code: i32, +} + +impl fmt::Display for InvalidOptionsError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + for issue in &self.issues { + try!(issue.fmt(f)); + } + Ok(()) + } +} + +impl InvalidOptionsError { + pub fn single(err: CLIError, exit_code: i32) -> InvalidOptionsError { + InvalidOptionsError { + issues: vec![err], + exit_code: exit_code, + } + } + + pub fn new() -> InvalidOptionsError { + InvalidOptionsError { + issues: Vec::new(), + exit_code: 1, + } + } +} + +pub fn assure_config_dir_exists(dir: &str) -> Result { + let trdir = dir.trim(); + if trdir.len() == 0 { + return Err(CLIError::Configuration(ConfigurationError::DirectoryUnset)) + } + + let expanded_config_dir = + if trdir.as_bytes()[0] == b'~' { + match env::var("HOME").ok().or(env::var("UserProfile").ok()) { + None => return Err(CLIError::Configuration(ConfigurationError::HomeExpansionFailed(trdir.to_string()))), + Some(mut user) => { + user.push_str(&trdir[1..]); + user + } + } + } else { + trdir.to_string() + }; + + if let Err(err) = fs::create_dir(&expanded_config_dir) { + if err.kind() != io::ErrorKind::AlreadyExists { + return Err(CLIError::Configuration( + ConfigurationError::DirectoryCreationFailed((expanded_config_dir, err)))) + } + } + + Ok(expanded_config_dir) +} + +pub fn application_secret_from_directory(dir: &str, + secret_basename: &str, + json_console_secret: &str) + -> Result { + let secret_path = Path::new(dir).join(secret_basename); + let secret_str = || secret_path.as_path().to_str().unwrap().to_string(); + let secret_io_error = |io_err: io::Error| { + Err(CLIError::Configuration(ConfigurationError::IOError( + (secret_str(), io_err) + ))) + }; + + for _ in 0..2 { + match fs::File::open(&secret_path) { + Err(mut err) => { + if err.kind() == io::ErrorKind::NotFound { + // Write our built-in one - user may adjust the written file at will + + err = match fs::OpenOptions::new().create(true).write(true).open(&secret_path) { + Err(cfe) => cfe, + Ok(mut f) => { + // Assure we convert 'ugly' json string into pretty one + let console_secret: ConsoleApplicationSecret + = json::from_str(json_console_secret).unwrap(); + match json::to_writer_pretty(&mut f, &console_secret) { + Err(serde_err) => match serde_err { + json::Error::IoError(err) => err, + _ => panic!("Unexpected serde error: {:#?}", serde_err) + }, + Ok(_) => continue, + } + } + }; + // fall through to IO error handling + } + return secret_io_error(err) + }, + Ok(mut f) => { + match json::de::from_reader::<_, ConsoleApplicationSecret>(f) { + Err(json::Error::IoError(err)) => + return secret_io_error(err), + Err(json_err) => + return Err(CLIError::Configuration( + ConfigurationError::Secret( + ApplicationSecretError::DecoderError( + (secret_str(), json_err) + )))), + Ok(console_secret) => + match console_secret.installed { + Some(secret) => return Ok(secret), + None => return Err( + CLIError::Configuration( + ConfigurationError::Secret( + ApplicationSecretError::FormatError(secret_str()) + ))) + }, + } + } + } + } + unreachable!(); +} diff --git a/gen/adexchangebuyer1d4-cli/src/main.rs b/gen/adexchangebuyer1d4-cli/src/main.rs new file mode 100644 index 0000000000..7a7784f1ea --- /dev/null +++ b/gen/adexchangebuyer1d4-cli/src/main.rs @@ -0,0 +1,5454 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/cli/main.rs.mako' +// DO NOT EDIT ! +#![allow(unused_variables, unused_imports, dead_code, unused_mut)] + +#[macro_use] +extern crate clap; +extern crate yup_oauth2 as oauth2; +extern crate yup_hyper_mock as mock; +extern crate serde; +extern crate serde_json; +extern crate hyper; +extern crate mime; +extern crate strsim; +extern crate google_adexchangebuyer1d4 as api; + +use std::env; +use std::io::{self, Write}; +use clap::{App, SubCommand, Arg}; + +mod cmn; + +use cmn::{InvalidOptionsError, CLIError, JsonTokenStorage, arg_from_str, writer_from_opts, parse_kv_arg, + input_file_from_opts, input_mime_from_opts, FieldCursor, FieldError, CallType, UploadProtocol, + calltype_from_str, remove_json_null_values, ComplexType, JsonType, JsonTypeInfo}; + +use std::default::Default; +use std::str::FromStr; + +use oauth2::{Authenticator, DefaultAuthenticatorDelegate}; +use serde_json as json; +use clap::ArgMatches; + +enum DoitError { + IoError(String, io::Error), + ApiError(api::Error), +} + +struct Engine<'n, 'a> { + opt: ArgMatches<'n, 'a>, + hub: api::AdExchangeBuyer>, + gp: Vec<&'static str>, + gpm: Vec<(&'static str, &'static str)>, +} + + +impl<'n, 'a> Engine<'n, 'a> { + fn _accounts_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let id: i32 = arg_from_str(&opt.value_of("id").unwrap_or(""), err, "", "integer"); + let mut call = self.hub.accounts().get(id); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _accounts_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.accounts().list(); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _accounts_patch(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "maximum-total-qps" => Some(("maximumTotalQps", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "maximum-active-creatives" => Some(("maximumActiveCreatives", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "cookie-matching-nid" => Some(("cookieMatchingNid", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "number-active-creatives" => Some(("numberActiveCreatives", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "cookie-matching-url" => Some(("cookieMatchingUrl", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["cookie-matching-nid", "cookie-matching-url", "id", "kind", "maximum-active-creatives", "maximum-total-qps", "number-active-creatives"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::Account = json::value::from_value(object).unwrap(); + let id: i32 = arg_from_str(&opt.value_of("id").unwrap_or(""), err, "", "integer"); + let mut call = self.hub.accounts().patch(request, id); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _accounts_update(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "maximum-total-qps" => Some(("maximumTotalQps", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "maximum-active-creatives" => Some(("maximumActiveCreatives", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "cookie-matching-nid" => Some(("cookieMatchingNid", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "number-active-creatives" => Some(("numberActiveCreatives", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "cookie-matching-url" => Some(("cookieMatchingUrl", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["cookie-matching-nid", "cookie-matching-url", "id", "kind", "maximum-active-creatives", "maximum-total-qps", "number-active-creatives"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::Account = json::value::from_value(object).unwrap(); + let id: i32 = arg_from_str(&opt.value_of("id").unwrap_or(""), err, "", "integer"); + let mut call = self.hub.accounts().update(request, id); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _billing_info_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let account_id: i32 = arg_from_str(&opt.value_of("account-id").unwrap_or(""), err, "", "integer"); + let mut call = self.hub.billing_info().get(account_id); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _billing_info_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.billing_info().list(); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _budget_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.budget().get(opt.value_of("account-id").unwrap_or(""), opt.value_of("billing-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _budget_patch(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "budget-amount" => Some(("budgetAmount", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "currency-code" => Some(("currencyCode", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "billing-id" => Some(("billingId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "billing-id", "budget-amount", "currency-code", "id", "kind"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::Budget = json::value::from_value(object).unwrap(); + let mut call = self.hub.budget().patch(request, opt.value_of("account-id").unwrap_or(""), opt.value_of("billing-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _budget_update(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "budget-amount" => Some(("budgetAmount", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "currency-code" => Some(("currencyCode", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "billing-id" => Some(("billingId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "billing-id", "budget-amount", "currency-code", "id", "kind"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::Budget = json::value::from_value(object).unwrap(); + let mut call = self.hub.budget().update(request, opt.value_of("account-id").unwrap_or(""), opt.value_of("billing-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _clientaccess_delete(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let sponsor_account_id: i32 = arg_from_str(&opt.value_of("sponsor-account-id").unwrap_or(""), err, "", "integer"); + let mut call = self.hub.clientaccess().delete(opt.value_of("client-account-id").unwrap_or(""), sponsor_account_id); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok(mut response) => { + Ok(()) + } + } + } + } + + fn _clientaccess_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let sponsor_account_id: i32 = arg_from_str(&opt.value_of("sponsor-account-id").unwrap_or(""), err, "", "integer"); + let mut call = self.hub.clientaccess().get(opt.value_of("client-account-id").unwrap_or(""), sponsor_account_id); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _clientaccess_insert(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "client-account-id" => Some(("clientAccountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "capabilities" => Some(("capabilities", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Vec })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["capabilities", "client-account-id"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::ClientAccessCapabilities = json::value::from_value(object).unwrap(); + let mut call = self.hub.clientaccess().insert(request); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "sponsor-account-id" => { + call = call.sponsor_account_id(arg_from_str(value.unwrap_or("-0"), err, "sponsor-account-id", "integer")); + }, + "client-account-id" => { + call = call.client_account_id(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["client-account-id", "sponsor-account-id"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _clientaccess_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "sponsor-account-id" => Some(("sponsorAccountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["sponsor-account-id"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::ListClientAccessCapabilitiesRequest = json::value::from_value(object).unwrap(); + let mut call = self.hub.clientaccess().list(request); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _clientaccess_patch(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "client-account-id" => Some(("clientAccountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "capabilities" => Some(("capabilities", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Vec })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["capabilities", "client-account-id"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::ClientAccessCapabilities = json::value::from_value(object).unwrap(); + let sponsor_account_id: i32 = arg_from_str(&opt.value_of("sponsor-account-id").unwrap_or(""), err, "", "integer"); + let mut call = self.hub.clientaccess().patch(request, opt.value_of("client-account-id").unwrap_or(""), sponsor_account_id); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _clientaccess_update(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "client-account-id" => Some(("clientAccountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "capabilities" => Some(("capabilities", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Vec })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["capabilities", "client-account-id"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::ClientAccessCapabilities = json::value::from_value(object).unwrap(); + let sponsor_account_id: i32 = arg_from_str(&opt.value_of("sponsor-account-id").unwrap_or(""), err, "", "integer"); + let mut call = self.hub.clientaccess().update(request, opt.value_of("client-account-id").unwrap_or(""), sponsor_account_id); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _creatives_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let account_id: i32 = arg_from_str(&opt.value_of("account-id").unwrap_or(""), err, "", "integer"); + let mut call = self.hub.creatives().get(account_id, opt.value_of("buyer-creative-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _creatives_insert(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "api-upload-timestamp" => Some(("api_upload_timestamp", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "attribute" => Some(("attribute", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Vec })), + "height" => Some(("height", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "advertiser-name" => Some(("advertiserName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "html-snippet" => Some(("HTMLSnippet", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "open-auction-status" => Some(("openAuctionStatus", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "buyer-creative-id" => Some(("buyerCreativeId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "impression-tracking-url" => Some(("impressionTrackingUrl", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "video-url" => Some(("videoURL", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "click-through-url" => Some(("clickThroughUrl", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "width" => Some(("width", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "native-ad.body" => Some(("nativeAd.body", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "native-ad.advertiser" => Some(("nativeAd.advertiser", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "native-ad.store" => Some(("nativeAd.store", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "native-ad.headline" => Some(("nativeAd.headline", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "native-ad.image.url" => Some(("nativeAd.image.url", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "native-ad.image.width" => Some(("nativeAd.image.width", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "native-ad.image.height" => Some(("nativeAd.image.height", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "native-ad.star-rating" => Some(("nativeAd.starRating", JsonTypeInfo { jtype: JsonType::Float, ctype: ComplexType::Pod })), + "native-ad.call-to-action" => Some(("nativeAd.callToAction", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "native-ad.logo.url" => Some(("nativeAd.logo.url", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "native-ad.logo.width" => Some(("nativeAd.logo.width", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "native-ad.logo.height" => Some(("nativeAd.logo.height", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "native-ad.app-icon.url" => Some(("nativeAd.appIcon.url", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "native-ad.app-icon.width" => Some(("nativeAd.appIcon.width", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "native-ad.app-icon.height" => Some(("nativeAd.appIcon.height", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "native-ad.impression-tracking-url" => Some(("nativeAd.impressionTrackingUrl", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "native-ad.price" => Some(("nativeAd.price", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "native-ad.click-tracking-url" => Some(("nativeAd.clickTrackingUrl", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "version" => Some(("version", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "vendor-type" => Some(("vendorType", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Vec })), + "sensitive-categories" => Some(("sensitiveCategories", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Vec })), + "product-categories" => Some(("productCategories", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Vec })), + "agency-id" => Some(("agencyId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "deals-status" => Some(("dealsStatus", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id" => Some(("advertiserId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "restricted-categories" => Some(("restrictedCategories", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Vec })), + "filtering-reasons.date" => Some(("filteringReasons.date", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["html-snippet", "account-id", "advertiser", "advertiser-id", "advertiser-name", "agency-id", "api-upload-timestamp", "app-icon", "attribute", "body", "buyer-creative-id", "call-to-action", "click-through-url", "click-tracking-url", "date", "deals-status", "filtering-reasons", "headline", "height", "image", "impression-tracking-url", "kind", "logo", "native-ad", "open-auction-status", "price", "product-categories", "restricted-categories", "sensitive-categories", "star-rating", "store", "url", "vendor-type", "version", "video-url", "width"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::Creative = json::value::from_value(object).unwrap(); + let mut call = self.hub.creatives().insert(request); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _creatives_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.creatives().list(); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "open-auction-status-filter" => { + call = call.open_auction_status_filter(value.unwrap_or("")); + }, + "max-results" => { + call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer")); + }, + "deals-status-filter" => { + call = call.deals_status_filter(value.unwrap_or("")); + }, + "buyer-creative-id" => { + call = call.add_buyer_creative_id(value.unwrap_or("")); + }, + "account-id" => { + call = call.add_account_id(arg_from_str(value.unwrap_or("-0"), err, "account-id", "integer")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["open-auction-status-filter", "max-results", "page-token", "buyer-creative-id", "deals-status-filter", "account-id"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _deals_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "include-private-auctions" => Some(("includePrivateAuctions", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["include-private-auctions"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::GetFinalizedNegotiationByExternalDealIdRequest = json::value::from_value(object).unwrap(); + let mut call = self.hub.deals().get(request, opt.value_of("deal-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _marketplacedeals_delete(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "order-revision-number" => Some(("orderRevisionNumber", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "update-action" => Some(("updateAction", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "deal-ids" => Some(("dealIds", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["deal-ids", "order-revision-number", "update-action"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::DeleteOrderDealsRequest = json::value::from_value(object).unwrap(); + let mut call = self.hub.marketplacedeals().delete(request, opt.value_of("order-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _marketplacedeals_insert(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "order-revision-number" => Some(("orderRevisionNumber", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "update-action" => Some(("updateAction", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["order-revision-number", "update-action"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::AddOrderDealsRequest = json::value::from_value(object).unwrap(); + let mut call = self.hub.marketplacedeals().insert(request, opt.value_of("order-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _marketplacedeals_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.marketplacedeals().list(opt.value_of("order-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _marketplacedeals_update(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "order-revision-number" => Some(("orderRevisionNumber", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "order.order-id" => Some(("order.orderId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "order.kind" => Some(("order.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "order.name" => Some(("order.name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "order.revision-time-ms" => Some(("order.revisionTimeMs", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "order.buyer-private-data.reference-id" => Some(("order.buyerPrivateData.referenceId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "order.buyer-private-data.reference-payload" => Some(("order.buyerPrivateData.referencePayload", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "order.billed-buyer.account-id" => Some(("order.billedBuyer.accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "order.originator-role" => Some(("order.originatorRole", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "order.seller.sub-account-id" => Some(("order.seller.subAccountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "order.seller.account-id" => Some(("order.seller.accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "order.last-updater-role" => Some(("order.lastUpdaterRole", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "order.order-state" => Some(("order.orderState", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "order.has-seller-signed-off" => Some(("order.hasSellerSignedOff", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "order.is-renegotiating" => Some(("order.isRenegotiating", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "order.buyer.account-id" => Some(("order.buyer.accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "order.has-buyer-signed-off" => Some(("order.hasBuyerSignedOff", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "order.is-setup-complete" => Some(("order.isSetupComplete", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "order.revision-number" => Some(("order.revisionNumber", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "order.last-updater-or-commentor-role" => Some(("order.lastUpdaterOrCommentorRole", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "update-action" => Some(("updateAction", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "billed-buyer", "buyer", "buyer-private-data", "has-buyer-signed-off", "has-seller-signed-off", "is-renegotiating", "is-setup-complete", "kind", "last-updater-or-commentor-role", "last-updater-role", "name", "order", "order-id", "order-revision-number", "order-state", "originator-role", "reference-id", "reference-payload", "revision-number", "revision-time-ms", "seller", "sub-account-id", "update-action"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::EditAllOrderDealsRequest = json::value::from_value(object).unwrap(); + let mut call = self.hub.marketplacedeals().update(request, opt.value_of("order-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _marketplacenotes_insert(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec![]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::AddOrderNotesRequest = json::value::from_value(object).unwrap(); + let mut call = self.hub.marketplacenotes().insert(request, opt.value_of("order-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _marketplacenotes_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.marketplacenotes().list(opt.value_of("order-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _marketplaceoffers_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.marketplaceoffers().get(opt.value_of("offer-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _marketplaceoffers_search(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.marketplaceoffers().search(); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "pql-query" => { + call = call.pql_query(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["pql-query"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _marketplaceorders_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.marketplaceorders().get(opt.value_of("order-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _marketplaceorders_insert(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "web-property-code" => Some(("webPropertyCode", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["web-property-code"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::CreateOrdersRequest = json::value::from_value(object).unwrap(); + let mut call = self.hub.marketplaceorders().insert(request); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _marketplaceorders_patch(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "order-id" => Some(("orderId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "revision-time-ms" => Some(("revisionTimeMs", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "buyer-private-data.reference-id" => Some(("buyerPrivateData.referenceId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "buyer-private-data.reference-payload" => Some(("buyerPrivateData.referencePayload", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "billed-buyer.account-id" => Some(("billedBuyer.accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "originator-role" => Some(("originatorRole", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "seller.sub-account-id" => Some(("seller.subAccountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "seller.account-id" => Some(("seller.accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "last-updater-role" => Some(("lastUpdaterRole", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "order-state" => Some(("orderState", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "has-seller-signed-off" => Some(("hasSellerSignedOff", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "is-renegotiating" => Some(("isRenegotiating", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "buyer.account-id" => Some(("buyer.accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "has-buyer-signed-off" => Some(("hasBuyerSignedOff", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "is-setup-complete" => Some(("isSetupComplete", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "revision-number" => Some(("revisionNumber", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "last-updater-or-commentor-role" => Some(("lastUpdaterOrCommentorRole", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "billed-buyer", "buyer", "buyer-private-data", "has-buyer-signed-off", "has-seller-signed-off", "is-renegotiating", "is-setup-complete", "kind", "last-updater-or-commentor-role", "last-updater-role", "name", "order-id", "order-state", "originator-role", "reference-id", "reference-payload", "revision-number", "revision-time-ms", "seller", "sub-account-id"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::MarketplaceOrder = json::value::from_value(object).unwrap(); + let mut call = self.hub.marketplaceorders().patch(request, opt.value_of("order-id").unwrap_or(""), opt.value_of("revision-number").unwrap_or(""), opt.value_of("update-action").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _marketplaceorders_search(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.marketplaceorders().search(); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "pql-query" => { + call = call.pql_query(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["pql-query"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _marketplaceorders_update(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "order-id" => Some(("orderId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "revision-time-ms" => Some(("revisionTimeMs", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "buyer-private-data.reference-id" => Some(("buyerPrivateData.referenceId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "buyer-private-data.reference-payload" => Some(("buyerPrivateData.referencePayload", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "billed-buyer.account-id" => Some(("billedBuyer.accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "originator-role" => Some(("originatorRole", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "seller.sub-account-id" => Some(("seller.subAccountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "seller.account-id" => Some(("seller.accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "last-updater-role" => Some(("lastUpdaterRole", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "order-state" => Some(("orderState", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "has-seller-signed-off" => Some(("hasSellerSignedOff", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "is-renegotiating" => Some(("isRenegotiating", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "buyer.account-id" => Some(("buyer.accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "has-buyer-signed-off" => Some(("hasBuyerSignedOff", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "is-setup-complete" => Some(("isSetupComplete", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "revision-number" => Some(("revisionNumber", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "last-updater-or-commentor-role" => Some(("lastUpdaterOrCommentorRole", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "billed-buyer", "buyer", "buyer-private-data", "has-buyer-signed-off", "has-seller-signed-off", "is-renegotiating", "is-setup-complete", "kind", "last-updater-or-commentor-role", "last-updater-role", "name", "order-id", "order-state", "originator-role", "reference-id", "reference-payload", "revision-number", "revision-time-ms", "seller", "sub-account-id"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::MarketplaceOrder = json::value::from_value(object).unwrap(); + let mut call = self.hub.marketplaceorders().update(request, opt.value_of("order-id").unwrap_or(""), opt.value_of("revision-number").unwrap_or(""), opt.value_of("update-action").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _negotiationrounds_insert(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "terms.finalize-automatically" => Some(("terms.finalizeAutomatically", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "terms.inventory-segment-targeting.positive-icm-interests" => Some(("terms.inventorySegmentTargeting.positiveIcmInterests", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "terms.inventory-segment-targeting.positive-inventory-slots" => Some(("terms.inventorySegmentTargeting.positiveInventorySlots", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "terms.inventory-segment-targeting.negative-site-urls" => Some(("terms.inventorySegmentTargeting.negativeSiteUrls", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "terms.inventory-segment-targeting.positive-icm-brands" => Some(("terms.inventorySegmentTargeting.positiveIcmBrands", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "terms.inventory-segment-targeting.negative-xfp-placements" => Some(("terms.inventorySegmentTargeting.negativeXfpPlacements", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "terms.inventory-segment-targeting.positive-video-ad-position-segments" => Some(("terms.inventorySegmentTargeting.positiveVideoAdPositionSegments", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "terms.inventory-segment-targeting.negative-icm-interests" => Some(("terms.inventorySegmentTargeting.negativeIcmInterests", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "terms.inventory-segment-targeting.negative-audience-segments" => Some(("terms.inventorySegmentTargeting.negativeAudienceSegments", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "terms.inventory-segment-targeting.positive-operating-systems" => Some(("terms.inventorySegmentTargeting.positiveOperatingSystems", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "terms.inventory-segment-targeting.negative-operating-systems" => Some(("terms.inventorySegmentTargeting.negativeOperatingSystems", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "terms.inventory-segment-targeting.negative-icm-brands" => Some(("terms.inventorySegmentTargeting.negativeIcmBrands", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "terms.inventory-segment-targeting.positive-locations" => Some(("terms.inventorySegmentTargeting.positiveLocations", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "terms.inventory-segment-targeting.negative-mobile-apps" => Some(("terms.inventorySegmentTargeting.negativeMobileApps", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "terms.inventory-segment-targeting.positive-device-categories" => Some(("terms.inventorySegmentTargeting.positiveDeviceCategories", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "terms.inventory-segment-targeting.negative-inventory-slots" => Some(("terms.inventorySegmentTargeting.negativeInventorySlots", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "terms.inventory-segment-targeting.negative-video-ad-position-segments" => Some(("terms.inventorySegmentTargeting.negativeVideoAdPositionSegments", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "terms.inventory-segment-targeting.negative-video-duration-segments" => Some(("terms.inventorySegmentTargeting.negativeVideoDurationSegments", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "terms.inventory-segment-targeting.positive-sizes" => Some(("terms.inventorySegmentTargeting.positiveSizes", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "terms.inventory-segment-targeting.positive-xfp-ad-slots" => Some(("terms.inventorySegmentTargeting.positiveXfpAdSlots", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "terms.inventory-segment-targeting.positive-site-urls" => Some(("terms.inventorySegmentTargeting.positiveSiteUrls", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "terms.inventory-segment-targeting.positive-mobile-apps" => Some(("terms.inventorySegmentTargeting.positiveMobileApps", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "terms.inventory-segment-targeting.negative-sizes" => Some(("terms.inventorySegmentTargeting.negativeSizes", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "terms.inventory-segment-targeting.positive-operating-system-versions" => Some(("terms.inventorySegmentTargeting.positiveOperatingSystemVersions", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "terms.inventory-segment-targeting.negative-locations" => Some(("terms.inventorySegmentTargeting.negativeLocations", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "terms.inventory-segment-targeting.negative-operating-system-versions" => Some(("terms.inventorySegmentTargeting.negativeOperatingSystemVersions", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "terms.inventory-segment-targeting.positive-xfp-placements" => Some(("terms.inventorySegmentTargeting.positiveXfpPlacements", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "terms.inventory-segment-targeting.negative-xfp-ad-slots" => Some(("terms.inventorySegmentTargeting.negativeXfpAdSlots", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "terms.inventory-segment-targeting.positive-video-duration-segments" => Some(("terms.inventorySegmentTargeting.positiveVideoDurationSegments", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "terms.inventory-segment-targeting.positive-audience-segments" => Some(("terms.inventorySegmentTargeting.positiveAudienceSegments", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "terms.inventory-segment-targeting.negative-device-categories" => Some(("terms.inventorySegmentTargeting.negativeDeviceCategories", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "terms.inventory-segment-targeting.positive-ad-type-segments" => Some(("terms.inventorySegmentTargeting.positiveAdTypeSegments", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "terms.inventory-segment-targeting.negative-ad-type-segments" => Some(("terms.inventorySegmentTargeting.negativeAdTypeSegments", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "terms.end-date.time-zone-id" => Some(("terms.endDate.timeZoneId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "terms.end-date.hour" => Some(("terms.endDate.hour", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "terms.end-date.month" => Some(("terms.endDate.month", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "terms.end-date.second" => Some(("terms.endDate.second", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "terms.end-date.year" => Some(("terms.endDate.year", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "terms.end-date.day" => Some(("terms.endDate.day", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "terms.end-date.minute" => Some(("terms.endDate.minute", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "terms.terms-attributes" => Some(("terms.termsAttributes", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "terms.start-date.time-zone-id" => Some(("terms.startDate.timeZoneId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "terms.start-date.hour" => Some(("terms.startDate.hour", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "terms.start-date.month" => Some(("terms.startDate.month", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "terms.start-date.second" => Some(("terms.startDate.second", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "terms.start-date.year" => Some(("terms.startDate.year", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "terms.start-date.day" => Some(("terms.startDate.day", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "terms.start-date.minute" => Some(("terms.startDate.minute", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "terms.buyer-billing-type" => Some(("terms.buyerBillingType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "terms.estimated-impressions-per-day" => Some(("terms.estimatedImpressionsPerDay", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "terms.monetizer-type" => Some(("terms.monetizerType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "terms.target-by-deal-id" => Some(("terms.targetByDealId", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "terms.minimum-spend-micros" => Some(("terms.minimumSpendMicros", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "terms.targeting-all-ad-slots" => Some(("terms.targetingAllAdSlots", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "terms.creative-review-policy" => Some(("terms.creativeReviewPolicy", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "terms.audience-segment-description" => Some(("terms.audienceSegmentDescription", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "terms.deal-premium.micros" => Some(("terms.dealPremium.micros", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "terms.deal-premium.currency-code" => Some(("terms.dealPremium.currencyCode", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "terms.creative-blocking-level" => Some(("terms.creativeBlockingLevel", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "terms.audience-segment.num-cookies" => Some(("terms.audienceSegment.numCookies", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "terms.audience-segment.description" => Some(("terms.audienceSegment.description", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "terms.audience-segment.name" => Some(("terms.audienceSegment.name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "terms.audience-segment.id" => Some(("terms.audienceSegment.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "terms.description" => Some(("terms.description", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "terms.billing-terms" => Some(("terms.billingTerms", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "terms.is-reservation" => Some(("terms.isReservation", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "terms.semi-transparent" => Some(("terms.semiTransparent", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "terms.minimum-true-looks" => Some(("terms.minimumTrueLooks", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "terms.cpm.micros" => Some(("terms.cpm.micros", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "terms.cpm.currency-code" => Some(("terms.cpm.currencyCode", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "terms.descriptive-name" => Some(("terms.descriptiveName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "terms.urls" => Some(("terms.urls", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "terms.estimated-spend.micros" => Some(("terms.estimatedSpend.micros", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "terms.estimated-spend.currency-code" => Some(("terms.estimatedSpend.currencyCode", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "round-number" => Some(("roundNumber", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "notes" => Some(("notes", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "originator-role" => Some(("originatorRole", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "negotiation-id" => Some(("negotiationId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "edit-history.created-time-stamp" => Some(("editHistory.createdTimeStamp", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "edit-history.created-by-login-name" => Some(("editHistory.createdByLoginName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "edit-history.last-updated-by-login-name" => Some(("editHistory.lastUpdatedByLoginName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "edit-history.last-update-time-stamp" => Some(("editHistory.lastUpdateTimeStamp", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "dbm-partner-id" => Some(("dbmPartnerId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "action" => Some(("action", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["action", "audience-segment", "audience-segment-description", "billing-terms", "buyer-billing-type", "cpm", "created-by-login-name", "created-time-stamp", "creative-blocking-level", "creative-review-policy", "currency-code", "day", "dbm-partner-id", "deal-premium", "description", "descriptive-name", "edit-history", "end-date", "estimated-impressions-per-day", "estimated-spend", "finalize-automatically", "hour", "id", "inventory-segment-targeting", "is-reservation", "kind", "last-update-time-stamp", "last-updated-by-login-name", "micros", "minimum-spend-micros", "minimum-true-looks", "minute", "monetizer-type", "month", "name", "negative-ad-type-segments", "negative-audience-segments", "negative-device-categories", "negative-icm-brands", "negative-icm-interests", "negative-inventory-slots", "negative-locations", "negative-mobile-apps", "negative-operating-system-versions", "negative-operating-systems", "negative-site-urls", "negative-sizes", "negative-video-ad-position-segments", "negative-video-duration-segments", "negative-xfp-ad-slots", "negative-xfp-placements", "negotiation-id", "notes", "num-cookies", "originator-role", "positive-ad-type-segments", "positive-audience-segments", "positive-device-categories", "positive-icm-brands", "positive-icm-interests", "positive-inventory-slots", "positive-locations", "positive-mobile-apps", "positive-operating-system-versions", "positive-operating-systems", "positive-site-urls", "positive-sizes", "positive-video-ad-position-segments", "positive-video-duration-segments", "positive-xfp-ad-slots", "positive-xfp-placements", "round-number", "second", "semi-transparent", "start-date", "target-by-deal-id", "targeting-all-ad-slots", "terms", "terms-attributes", "time-zone-id", "urls", "year"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::NegotiationRoundDto = json::value::from_value(object).unwrap(); + let mut call = self.hub.negotiationrounds().insert(request, opt.value_of("negotiation-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _negotiations_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "include-private-auctions" => Some(("includePrivateAuctions", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["include-private-auctions"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::GetNegotiationByIdRequest = json::value::from_value(object).unwrap(); + let mut call = self.hub.negotiations().get(request, opt.value_of("negotiation-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _negotiations_insert(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "status" => Some(("status", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "buyer-email-contacts" => Some(("buyerEmailContacts", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "label-names" => Some(("labelNames", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "billed-buyer.buyer.enabled-for-preferred-deals" => Some(("billedBuyer.buyer.enabledForPreferredDeals", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "billed-buyer.buyer.display-name" => Some(("billedBuyer.buyer.displayName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "billed-buyer.buyer.customer-id" => Some(("billedBuyer.buyer.customerId", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "billed-buyer.buyer.enabled-for-interest-targeting-deals" => Some(("billedBuyer.buyer.enabledForInterestTargetingDeals", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "billed-buyer.buyer.sponsor-account-id" => Some(("billedBuyer.buyer.sponsorAccountId", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "billed-buyer.buyer.id" => Some(("billedBuyer.buyer.id", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "billed-buyer.buyer.account-id" => Some(("billedBuyer.buyer.accountId", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "billed-buyer.web-property.enabled-for-preferred-deals" => Some(("billedBuyer.webProperty.enabledForPreferredDeals", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "billed-buyer.web-property.name" => Some(("billedBuyer.webProperty.name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "billed-buyer.web-property.syndication-product" => Some(("billedBuyer.webProperty.syndicationProduct", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "billed-buyer.web-property.allow-interest-targeted-ads" => Some(("billedBuyer.webProperty.allowInterestTargetedAds", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "billed-buyer.web-property.site-urls" => Some(("billedBuyer.webProperty.siteUrls", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "billed-buyer.web-property.property-code" => Some(("billedBuyer.webProperty.propertyCode", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "billed-buyer.web-property.id" => Some(("billedBuyer.webProperty.id", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "billed-buyer.customer-id" => Some(("billedBuyer.customerId", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "billed-buyer.name" => Some(("billedBuyer.name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "billed-buyer.buyer-seller-role" => Some(("billedBuyer.buyerSellerRole", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "offer-id" => Some(("offerId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "seller.buyer.enabled-for-preferred-deals" => Some(("seller.buyer.enabledForPreferredDeals", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "seller.buyer.display-name" => Some(("seller.buyer.displayName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "seller.buyer.customer-id" => Some(("seller.buyer.customerId", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "seller.buyer.enabled-for-interest-targeting-deals" => Some(("seller.buyer.enabledForInterestTargetingDeals", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "seller.buyer.sponsor-account-id" => Some(("seller.buyer.sponsorAccountId", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "seller.buyer.id" => Some(("seller.buyer.id", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "seller.buyer.account-id" => Some(("seller.buyer.accountId", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "seller.web-property.enabled-for-preferred-deals" => Some(("seller.webProperty.enabledForPreferredDeals", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "seller.web-property.name" => Some(("seller.webProperty.name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "seller.web-property.syndication-product" => Some(("seller.webProperty.syndicationProduct", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "seller.web-property.allow-interest-targeted-ads" => Some(("seller.webProperty.allowInterestTargetedAds", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "seller.web-property.site-urls" => Some(("seller.webProperty.siteUrls", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "seller.web-property.property-code" => Some(("seller.webProperty.propertyCode", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "seller.web-property.id" => Some(("seller.webProperty.id", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "seller.customer-id" => Some(("seller.customerId", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "seller.name" => Some(("seller.name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "seller.buyer-seller-role" => Some(("seller.buyerSellerRole", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "negotiation-id" => Some(("negotiationId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "negotiation-state" => Some(("negotiationState", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "buyer.buyer.enabled-for-preferred-deals" => Some(("buyer.buyer.enabledForPreferredDeals", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "buyer.buyer.display-name" => Some(("buyer.buyer.displayName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "buyer.buyer.customer-id" => Some(("buyer.buyer.customerId", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "buyer.buyer.enabled-for-interest-targeting-deals" => Some(("buyer.buyer.enabledForInterestTargetingDeals", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "buyer.buyer.sponsor-account-id" => Some(("buyer.buyer.sponsorAccountId", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "buyer.buyer.id" => Some(("buyer.buyer.id", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "buyer.buyer.account-id" => Some(("buyer.buyer.accountId", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "buyer.web-property.enabled-for-preferred-deals" => Some(("buyer.webProperty.enabledForPreferredDeals", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "buyer.web-property.name" => Some(("buyer.webProperty.name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "buyer.web-property.syndication-product" => Some(("buyer.webProperty.syndicationProduct", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "buyer.web-property.allow-interest-targeted-ads" => Some(("buyer.webProperty.allowInterestTargetedAds", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "buyer.web-property.site-urls" => Some(("buyer.webProperty.siteUrls", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "buyer.web-property.property-code" => Some(("buyer.webProperty.propertyCode", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "buyer.web-property.id" => Some(("buyer.webProperty.id", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "buyer.customer-id" => Some(("buyer.customerId", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "buyer.name" => Some(("buyer.name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "buyer.buyer-seller-role" => Some(("buyer.buyerSellerRole", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "stats.revenue.micros" => Some(("stats.revenue.micros", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "stats.revenue.currency-code" => Some(("stats.revenue.currencyCode", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "stats.bids" => Some(("stats.bids", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "stats.impressions" => Some(("stats.impressions", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "stats.requests" => Some(("stats.requests", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "stats.good-bids" => Some(("stats.goodBids", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "stats.spend.micros" => Some(("stats.spend.micros", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "stats.spend.currency-code" => Some(("stats.spend.currencyCode", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "external-deal-id" => Some(("externalDealId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "seller-email-contacts" => Some(("sellerEmailContacts", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "deal-type" => Some(("dealType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "allow-interest-targeted-ads", "bids", "billed-buyer", "buyer", "buyer-email-contacts", "buyer-seller-role", "currency-code", "customer-id", "deal-type", "display-name", "enabled-for-interest-targeting-deals", "enabled-for-preferred-deals", "external-deal-id", "good-bids", "id", "impressions", "kind", "label-names", "micros", "name", "negotiation-id", "negotiation-state", "offer-id", "property-code", "requests", "revenue", "seller", "seller-email-contacts", "site-urls", "spend", "sponsor-account-id", "stats", "status", "syndication-product", "web-property"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::NegotiationDto = json::value::from_value(object).unwrap(); + let mut call = self.hub.negotiations().insert(request); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _negotiations_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "since-timestamp-millis" => Some(("sinceTimestampMillis", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "include-private-auctions" => Some(("includePrivateAuctions", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "finalized" => Some(("finalized", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["finalized", "include-private-auctions", "since-timestamp-millis"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::GetNegotiationsRequest = json::value::from_value(object).unwrap(); + let mut call = self.hub.negotiations().list(request); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _offers_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.offers().get(opt.value_of("offer-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _offers_insert(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "status" => Some(("status", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "label-names" => Some(("labelNames", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "point-of-contact" => Some(("pointOfContact", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "is-open" => Some(("isOpen", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "creator.buyer.enabled-for-preferred-deals" => Some(("creator.buyer.enabledForPreferredDeals", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "creator.buyer.display-name" => Some(("creator.buyer.displayName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "creator.buyer.customer-id" => Some(("creator.buyer.customerId", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "creator.buyer.enabled-for-interest-targeting-deals" => Some(("creator.buyer.enabledForInterestTargetingDeals", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "creator.buyer.sponsor-account-id" => Some(("creator.buyer.sponsorAccountId", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "creator.buyer.id" => Some(("creator.buyer.id", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "creator.buyer.account-id" => Some(("creator.buyer.accountId", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "creator.web-property.enabled-for-preferred-deals" => Some(("creator.webProperty.enabledForPreferredDeals", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "creator.web-property.name" => Some(("creator.webProperty.name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "creator.web-property.syndication-product" => Some(("creator.webProperty.syndicationProduct", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "creator.web-property.allow-interest-targeted-ads" => Some(("creator.webProperty.allowInterestTargetedAds", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "creator.web-property.site-urls" => Some(("creator.webProperty.siteUrls", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "creator.web-property.property-code" => Some(("creator.webProperty.propertyCode", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "creator.web-property.id" => Some(("creator.webProperty.id", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "creator.customer-id" => Some(("creator.customerId", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "creator.name" => Some(("creator.name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "creator.buyer-seller-role" => Some(("creator.buyerSellerRole", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "billed-buyer.buyer.enabled-for-preferred-deals" => Some(("billedBuyer.buyer.enabledForPreferredDeals", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "billed-buyer.buyer.display-name" => Some(("billedBuyer.buyer.displayName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "billed-buyer.buyer.customer-id" => Some(("billedBuyer.buyer.customerId", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "billed-buyer.buyer.enabled-for-interest-targeting-deals" => Some(("billedBuyer.buyer.enabledForInterestTargetingDeals", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "billed-buyer.buyer.sponsor-account-id" => Some(("billedBuyer.buyer.sponsorAccountId", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "billed-buyer.buyer.id" => Some(("billedBuyer.buyer.id", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "billed-buyer.buyer.account-id" => Some(("billedBuyer.buyer.accountId", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "billed-buyer.web-property.enabled-for-preferred-deals" => Some(("billedBuyer.webProperty.enabledForPreferredDeals", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "billed-buyer.web-property.name" => Some(("billedBuyer.webProperty.name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "billed-buyer.web-property.syndication-product" => Some(("billedBuyer.webProperty.syndicationProduct", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "billed-buyer.web-property.allow-interest-targeted-ads" => Some(("billedBuyer.webProperty.allowInterestTargetedAds", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "billed-buyer.web-property.site-urls" => Some(("billedBuyer.webProperty.siteUrls", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "billed-buyer.web-property.property-code" => Some(("billedBuyer.webProperty.propertyCode", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "billed-buyer.web-property.id" => Some(("billedBuyer.webProperty.id", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "billed-buyer.customer-id" => Some(("billedBuyer.customerId", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "billed-buyer.name" => Some(("billedBuyer.name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "billed-buyer.buyer-seller-role" => Some(("billedBuyer.buyerSellerRole", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "offer-id" => Some(("offerId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "offer-state" => Some(("offerState", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "anonymous" => Some(("anonymous", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "terms.finalize-automatically" => Some(("terms.finalizeAutomatically", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "terms.inventory-segment-targeting.positive-icm-interests" => Some(("terms.inventorySegmentTargeting.positiveIcmInterests", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "terms.inventory-segment-targeting.positive-inventory-slots" => Some(("terms.inventorySegmentTargeting.positiveInventorySlots", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "terms.inventory-segment-targeting.negative-site-urls" => Some(("terms.inventorySegmentTargeting.negativeSiteUrls", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "terms.inventory-segment-targeting.positive-icm-brands" => Some(("terms.inventorySegmentTargeting.positiveIcmBrands", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "terms.inventory-segment-targeting.negative-xfp-placements" => Some(("terms.inventorySegmentTargeting.negativeXfpPlacements", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "terms.inventory-segment-targeting.positive-video-ad-position-segments" => Some(("terms.inventorySegmentTargeting.positiveVideoAdPositionSegments", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "terms.inventory-segment-targeting.negative-icm-interests" => Some(("terms.inventorySegmentTargeting.negativeIcmInterests", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "terms.inventory-segment-targeting.negative-audience-segments" => Some(("terms.inventorySegmentTargeting.negativeAudienceSegments", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "terms.inventory-segment-targeting.positive-operating-systems" => Some(("terms.inventorySegmentTargeting.positiveOperatingSystems", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "terms.inventory-segment-targeting.negative-operating-systems" => Some(("terms.inventorySegmentTargeting.negativeOperatingSystems", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "terms.inventory-segment-targeting.negative-icm-brands" => Some(("terms.inventorySegmentTargeting.negativeIcmBrands", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "terms.inventory-segment-targeting.positive-locations" => Some(("terms.inventorySegmentTargeting.positiveLocations", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "terms.inventory-segment-targeting.negative-mobile-apps" => Some(("terms.inventorySegmentTargeting.negativeMobileApps", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "terms.inventory-segment-targeting.positive-device-categories" => Some(("terms.inventorySegmentTargeting.positiveDeviceCategories", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "terms.inventory-segment-targeting.negative-inventory-slots" => Some(("terms.inventorySegmentTargeting.negativeInventorySlots", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "terms.inventory-segment-targeting.negative-video-ad-position-segments" => Some(("terms.inventorySegmentTargeting.negativeVideoAdPositionSegments", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "terms.inventory-segment-targeting.negative-video-duration-segments" => Some(("terms.inventorySegmentTargeting.negativeVideoDurationSegments", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "terms.inventory-segment-targeting.positive-sizes" => Some(("terms.inventorySegmentTargeting.positiveSizes", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "terms.inventory-segment-targeting.positive-xfp-ad-slots" => Some(("terms.inventorySegmentTargeting.positiveXfpAdSlots", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "terms.inventory-segment-targeting.positive-site-urls" => Some(("terms.inventorySegmentTargeting.positiveSiteUrls", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "terms.inventory-segment-targeting.positive-mobile-apps" => Some(("terms.inventorySegmentTargeting.positiveMobileApps", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "terms.inventory-segment-targeting.negative-sizes" => Some(("terms.inventorySegmentTargeting.negativeSizes", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "terms.inventory-segment-targeting.positive-operating-system-versions" => Some(("terms.inventorySegmentTargeting.positiveOperatingSystemVersions", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "terms.inventory-segment-targeting.negative-locations" => Some(("terms.inventorySegmentTargeting.negativeLocations", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "terms.inventory-segment-targeting.negative-operating-system-versions" => Some(("terms.inventorySegmentTargeting.negativeOperatingSystemVersions", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "terms.inventory-segment-targeting.positive-xfp-placements" => Some(("terms.inventorySegmentTargeting.positiveXfpPlacements", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "terms.inventory-segment-targeting.negative-xfp-ad-slots" => Some(("terms.inventorySegmentTargeting.negativeXfpAdSlots", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "terms.inventory-segment-targeting.positive-video-duration-segments" => Some(("terms.inventorySegmentTargeting.positiveVideoDurationSegments", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "terms.inventory-segment-targeting.positive-audience-segments" => Some(("terms.inventorySegmentTargeting.positiveAudienceSegments", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "terms.inventory-segment-targeting.negative-device-categories" => Some(("terms.inventorySegmentTargeting.negativeDeviceCategories", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "terms.inventory-segment-targeting.positive-ad-type-segments" => Some(("terms.inventorySegmentTargeting.positiveAdTypeSegments", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "terms.inventory-segment-targeting.negative-ad-type-segments" => Some(("terms.inventorySegmentTargeting.negativeAdTypeSegments", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "terms.end-date.time-zone-id" => Some(("terms.endDate.timeZoneId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "terms.end-date.hour" => Some(("terms.endDate.hour", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "terms.end-date.month" => Some(("terms.endDate.month", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "terms.end-date.second" => Some(("terms.endDate.second", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "terms.end-date.year" => Some(("terms.endDate.year", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "terms.end-date.day" => Some(("terms.endDate.day", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "terms.end-date.minute" => Some(("terms.endDate.minute", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "terms.terms-attributes" => Some(("terms.termsAttributes", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "terms.start-date.time-zone-id" => Some(("terms.startDate.timeZoneId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "terms.start-date.hour" => Some(("terms.startDate.hour", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "terms.start-date.month" => Some(("terms.startDate.month", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "terms.start-date.second" => Some(("terms.startDate.second", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "terms.start-date.year" => Some(("terms.startDate.year", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "terms.start-date.day" => Some(("terms.startDate.day", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "terms.start-date.minute" => Some(("terms.startDate.minute", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "terms.buyer-billing-type" => Some(("terms.buyerBillingType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "terms.estimated-impressions-per-day" => Some(("terms.estimatedImpressionsPerDay", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "terms.monetizer-type" => Some(("terms.monetizerType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "terms.target-by-deal-id" => Some(("terms.targetByDealId", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "terms.minimum-spend-micros" => Some(("terms.minimumSpendMicros", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "terms.targeting-all-ad-slots" => Some(("terms.targetingAllAdSlots", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "terms.creative-review-policy" => Some(("terms.creativeReviewPolicy", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "terms.audience-segment-description" => Some(("terms.audienceSegmentDescription", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "terms.deal-premium.micros" => Some(("terms.dealPremium.micros", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "terms.deal-premium.currency-code" => Some(("terms.dealPremium.currencyCode", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "terms.creative-blocking-level" => Some(("terms.creativeBlockingLevel", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "terms.audience-segment.num-cookies" => Some(("terms.audienceSegment.numCookies", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "terms.audience-segment.description" => Some(("terms.audienceSegment.description", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "terms.audience-segment.name" => Some(("terms.audienceSegment.name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "terms.audience-segment.id" => Some(("terms.audienceSegment.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "terms.description" => Some(("terms.description", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "terms.billing-terms" => Some(("terms.billingTerms", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "terms.is-reservation" => Some(("terms.isReservation", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "terms.semi-transparent" => Some(("terms.semiTransparent", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "terms.minimum-true-looks" => Some(("terms.minimumTrueLooks", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "terms.cpm.micros" => Some(("terms.cpm.micros", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "terms.cpm.currency-code" => Some(("terms.cpm.currencyCode", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "terms.descriptive-name" => Some(("terms.descriptiveName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "terms.urls" => Some(("terms.urls", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "terms.estimated-spend.micros" => Some(("terms.estimatedSpend.micros", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "terms.estimated-spend.currency-code" => Some(("terms.estimatedSpend.currencyCode", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "email-contacts" => Some(("emailContacts", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "allow-interest-targeted-ads", "anonymous", "audience-segment", "audience-segment-description", "billed-buyer", "billing-terms", "buyer", "buyer-billing-type", "buyer-seller-role", "cpm", "creative-blocking-level", "creative-review-policy", "creator", "currency-code", "customer-id", "day", "deal-premium", "description", "descriptive-name", "display-name", "email-contacts", "enabled-for-interest-targeting-deals", "enabled-for-preferred-deals", "end-date", "estimated-impressions-per-day", "estimated-spend", "finalize-automatically", "hour", "id", "inventory-segment-targeting", "is-open", "is-reservation", "kind", "label-names", "micros", "minimum-spend-micros", "minimum-true-looks", "minute", "monetizer-type", "month", "name", "negative-ad-type-segments", "negative-audience-segments", "negative-device-categories", "negative-icm-brands", "negative-icm-interests", "negative-inventory-slots", "negative-locations", "negative-mobile-apps", "negative-operating-system-versions", "negative-operating-systems", "negative-site-urls", "negative-sizes", "negative-video-ad-position-segments", "negative-video-duration-segments", "negative-xfp-ad-slots", "negative-xfp-placements", "num-cookies", "offer-id", "offer-state", "point-of-contact", "positive-ad-type-segments", "positive-audience-segments", "positive-device-categories", "positive-icm-brands", "positive-icm-interests", "positive-inventory-slots", "positive-locations", "positive-mobile-apps", "positive-operating-system-versions", "positive-operating-systems", "positive-site-urls", "positive-sizes", "positive-video-ad-position-segments", "positive-video-duration-segments", "positive-xfp-ad-slots", "positive-xfp-placements", "property-code", "second", "semi-transparent", "site-urls", "sponsor-account-id", "start-date", "status", "syndication-product", "target-by-deal-id", "targeting-all-ad-slots", "terms", "terms-attributes", "time-zone-id", "urls", "web-property", "year"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::OfferDto = json::value::from_value(object).unwrap(); + let mut call = self.hub.offers().insert(request); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _offers_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "since-timestamp-millis" => Some(("sinceTimestampMillis", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["since-timestamp-millis"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::ListOffersRequest = json::value::from_value(object).unwrap(); + let mut call = self.hub.offers().list(request); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _performance_report_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.performance_report().list(opt.value_of("account-id").unwrap_or(""), opt.value_of("end-date-time").unwrap_or(""), opt.value_of("start-date-time").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "max-results" => { + call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["page-token", "max-results"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _pretargeting_config_delete(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.pretargeting_config().delete(opt.value_of("account-id").unwrap_or(""), opt.value_of("config-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok(mut response) => { + Ok(()) + } + } + } + } + + fn _pretargeting_config_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.pretargeting_config().get(opt.value_of("account-id").unwrap_or(""), opt.value_of("config-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _pretargeting_config_insert(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "billing-id" => Some(("billingId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "languages" => Some(("languages", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "config-name" => Some(("configName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "excluded-geo-criteria-ids" => Some(("excludedGeoCriteriaIds", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "user-lists" => Some(("userLists", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "excluded-verticals" => Some(("excludedVerticals", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "vendor-types" => Some(("vendorTypes", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "excluded-content-labels" => Some(("excludedContentLabels", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "verticals" => Some(("verticals", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "platforms" => Some(("platforms", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "mobile-devices" => Some(("mobileDevices", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "creative-type" => Some(("creativeType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "geo-criteria-ids" => Some(("geoCriteriaIds", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "mobile-operating-system-versions" => Some(("mobileOperatingSystemVersions", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "mobile-carriers" => Some(("mobileCarriers", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "config-id" => Some(("configId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "excluded-user-lists" => Some(("excludedUserLists", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "is-active" => Some(("isActive", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "supported-creative-attributes" => Some(("supportedCreativeAttributes", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["billing-id", "config-id", "config-name", "creative-type", "excluded-content-labels", "excluded-geo-criteria-ids", "excluded-user-lists", "excluded-verticals", "geo-criteria-ids", "is-active", "kind", "languages", "mobile-carriers", "mobile-devices", "mobile-operating-system-versions", "platforms", "supported-creative-attributes", "user-lists", "vendor-types", "verticals"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::PretargetingConfig = json::value::from_value(object).unwrap(); + let mut call = self.hub.pretargeting_config().insert(request, opt.value_of("account-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _pretargeting_config_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.pretargeting_config().list(opt.value_of("account-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _pretargeting_config_patch(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "billing-id" => Some(("billingId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "languages" => Some(("languages", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "config-name" => Some(("configName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "excluded-geo-criteria-ids" => Some(("excludedGeoCriteriaIds", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "user-lists" => Some(("userLists", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "excluded-verticals" => Some(("excludedVerticals", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "vendor-types" => Some(("vendorTypes", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "excluded-content-labels" => Some(("excludedContentLabels", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "verticals" => Some(("verticals", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "platforms" => Some(("platforms", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "mobile-devices" => Some(("mobileDevices", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "creative-type" => Some(("creativeType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "geo-criteria-ids" => Some(("geoCriteriaIds", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "mobile-operating-system-versions" => Some(("mobileOperatingSystemVersions", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "mobile-carriers" => Some(("mobileCarriers", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "config-id" => Some(("configId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "excluded-user-lists" => Some(("excludedUserLists", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "is-active" => Some(("isActive", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "supported-creative-attributes" => Some(("supportedCreativeAttributes", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["billing-id", "config-id", "config-name", "creative-type", "excluded-content-labels", "excluded-geo-criteria-ids", "excluded-user-lists", "excluded-verticals", "geo-criteria-ids", "is-active", "kind", "languages", "mobile-carriers", "mobile-devices", "mobile-operating-system-versions", "platforms", "supported-creative-attributes", "user-lists", "vendor-types", "verticals"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::PretargetingConfig = json::value::from_value(object).unwrap(); + let mut call = self.hub.pretargeting_config().patch(request, opt.value_of("account-id").unwrap_or(""), opt.value_of("config-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _pretargeting_config_update(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "billing-id" => Some(("billingId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "languages" => Some(("languages", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "config-name" => Some(("configName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "excluded-geo-criteria-ids" => Some(("excludedGeoCriteriaIds", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "user-lists" => Some(("userLists", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "excluded-verticals" => Some(("excludedVerticals", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "vendor-types" => Some(("vendorTypes", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "excluded-content-labels" => Some(("excludedContentLabels", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "verticals" => Some(("verticals", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "platforms" => Some(("platforms", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "mobile-devices" => Some(("mobileDevices", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "creative-type" => Some(("creativeType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "geo-criteria-ids" => Some(("geoCriteriaIds", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "mobile-operating-system-versions" => Some(("mobileOperatingSystemVersions", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "mobile-carriers" => Some(("mobileCarriers", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "config-id" => Some(("configId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "excluded-user-lists" => Some(("excludedUserLists", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "is-active" => Some(("isActive", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "supported-creative-attributes" => Some(("supportedCreativeAttributes", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["billing-id", "config-id", "config-name", "creative-type", "excluded-content-labels", "excluded-geo-criteria-ids", "excluded-user-lists", "excluded-verticals", "geo-criteria-ids", "is-active", "kind", "languages", "mobile-carriers", "mobile-devices", "mobile-operating-system-versions", "platforms", "supported-creative-attributes", "user-lists", "vendor-types", "verticals"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::PretargetingConfig = json::value::from_value(object).unwrap(); + let mut call = self.hub.pretargeting_config().update(request, opt.value_of("account-id").unwrap_or(""), opt.value_of("config-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _doit(&self, dry_run: bool) -> Result, Option> { + let mut err = InvalidOptionsError::new(); + let mut call_result: Result<(), DoitError> = Ok(()); + let mut err_opt: Option = None; + match self.opt.subcommand() { + ("accounts", Some(opt)) => { + match opt.subcommand() { + ("get", Some(opt)) => { + call_result = self._accounts_get(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._accounts_list(opt, dry_run, &mut err); + }, + ("patch", Some(opt)) => { + call_result = self._accounts_patch(opt, dry_run, &mut err); + }, + ("update", Some(opt)) => { + call_result = self._accounts_update(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("accounts".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("billing-info", Some(opt)) => { + match opt.subcommand() { + ("get", Some(opt)) => { + call_result = self._billing_info_get(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._billing_info_list(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("billing-info".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("budget", Some(opt)) => { + match opt.subcommand() { + ("get", Some(opt)) => { + call_result = self._budget_get(opt, dry_run, &mut err); + }, + ("patch", Some(opt)) => { + call_result = self._budget_patch(opt, dry_run, &mut err); + }, + ("update", Some(opt)) => { + call_result = self._budget_update(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("budget".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("clientaccess", Some(opt)) => { + match opt.subcommand() { + ("delete", Some(opt)) => { + call_result = self._clientaccess_delete(opt, dry_run, &mut err); + }, + ("get", Some(opt)) => { + call_result = self._clientaccess_get(opt, dry_run, &mut err); + }, + ("insert", Some(opt)) => { + call_result = self._clientaccess_insert(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._clientaccess_list(opt, dry_run, &mut err); + }, + ("patch", Some(opt)) => { + call_result = self._clientaccess_patch(opt, dry_run, &mut err); + }, + ("update", Some(opt)) => { + call_result = self._clientaccess_update(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("clientaccess".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("creatives", Some(opt)) => { + match opt.subcommand() { + ("get", Some(opt)) => { + call_result = self._creatives_get(opt, dry_run, &mut err); + }, + ("insert", Some(opt)) => { + call_result = self._creatives_insert(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._creatives_list(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("creatives".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("deals", Some(opt)) => { + match opt.subcommand() { + ("get", Some(opt)) => { + call_result = self._deals_get(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("deals".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("marketplacedeals", Some(opt)) => { + match opt.subcommand() { + ("delete", Some(opt)) => { + call_result = self._marketplacedeals_delete(opt, dry_run, &mut err); + }, + ("insert", Some(opt)) => { + call_result = self._marketplacedeals_insert(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._marketplacedeals_list(opt, dry_run, &mut err); + }, + ("update", Some(opt)) => { + call_result = self._marketplacedeals_update(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("marketplacedeals".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("marketplacenotes", Some(opt)) => { + match opt.subcommand() { + ("insert", Some(opt)) => { + call_result = self._marketplacenotes_insert(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._marketplacenotes_list(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("marketplacenotes".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("marketplaceoffers", Some(opt)) => { + match opt.subcommand() { + ("get", Some(opt)) => { + call_result = self._marketplaceoffers_get(opt, dry_run, &mut err); + }, + ("search", Some(opt)) => { + call_result = self._marketplaceoffers_search(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("marketplaceoffers".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("marketplaceorders", Some(opt)) => { + match opt.subcommand() { + ("get", Some(opt)) => { + call_result = self._marketplaceorders_get(opt, dry_run, &mut err); + }, + ("insert", Some(opt)) => { + call_result = self._marketplaceorders_insert(opt, dry_run, &mut err); + }, + ("patch", Some(opt)) => { + call_result = self._marketplaceorders_patch(opt, dry_run, &mut err); + }, + ("search", Some(opt)) => { + call_result = self._marketplaceorders_search(opt, dry_run, &mut err); + }, + ("update", Some(opt)) => { + call_result = self._marketplaceorders_update(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("marketplaceorders".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("negotiationrounds", Some(opt)) => { + match opt.subcommand() { + ("insert", Some(opt)) => { + call_result = self._negotiationrounds_insert(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("negotiationrounds".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("negotiations", Some(opt)) => { + match opt.subcommand() { + ("get", Some(opt)) => { + call_result = self._negotiations_get(opt, dry_run, &mut err); + }, + ("insert", Some(opt)) => { + call_result = self._negotiations_insert(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._negotiations_list(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("negotiations".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("offers", Some(opt)) => { + match opt.subcommand() { + ("get", Some(opt)) => { + call_result = self._offers_get(opt, dry_run, &mut err); + }, + ("insert", Some(opt)) => { + call_result = self._offers_insert(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._offers_list(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("offers".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("performance-report", Some(opt)) => { + match opt.subcommand() { + ("list", Some(opt)) => { + call_result = self._performance_report_list(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("performance-report".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("pretargeting-config", Some(opt)) => { + match opt.subcommand() { + ("delete", Some(opt)) => { + call_result = self._pretargeting_config_delete(opt, dry_run, &mut err); + }, + ("get", Some(opt)) => { + call_result = self._pretargeting_config_get(opt, dry_run, &mut err); + }, + ("insert", Some(opt)) => { + call_result = self._pretargeting_config_insert(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._pretargeting_config_list(opt, dry_run, &mut err); + }, + ("patch", Some(opt)) => { + call_result = self._pretargeting_config_patch(opt, dry_run, &mut err); + }, + ("update", Some(opt)) => { + call_result = self._pretargeting_config_update(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("pretargeting-config".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + _ => { + err.issues.push(CLIError::MissingCommandError); + writeln!(io::stderr(), "{}\n", self.opt.usage()).ok(); + } + } + + if dry_run { + if err.issues.len() > 0 { + err_opt = Some(err); + } + Err(err_opt) + } else { + Ok(call_result) + } + } + + // Please note that this call will fail if any part of the opt can't be handled + fn new(opt: ArgMatches<'a, 'n>) -> Result, InvalidOptionsError> { + let (config_dir, secret) = { + let config_dir = match cmn::assure_config_dir_exists(opt.value_of("folder").unwrap_or("~/.google-service-cli")) { + Err(e) => return Err(InvalidOptionsError::single(e, 3)), + Ok(p) => p, + }; + + match cmn::application_secret_from_directory(&config_dir, "adexchangebuyer1d4-secret.json", + "{\"installed\":{\"auth_uri\":\"https://accounts.google.com/o/oauth2/auth\",\"client_secret\":\"hCsslbCUyfehWMmbkG8vTYxG\",\"token_uri\":\"https://accounts.google.com/o/oauth2/token\",\"client_email\":\"\",\"redirect_uris\":[\"urn:ietf:wg:oauth:2.0:oob\",\"oob\"],\"client_x509_cert_url\":\"\",\"client_id\":\"620010449518-9ngf7o4dhs0dka470npqvor6dc5lqb9b.apps.googleusercontent.com\",\"auth_provider_x509_cert_url\":\"https://www.googleapis.com/oauth2/v1/certs\"}}") { + Ok(secret) => (config_dir, secret), + Err(e) => return Err(InvalidOptionsError::single(e, 4)) + } + }; + + let auth = Authenticator::new( &secret, DefaultAuthenticatorDelegate, + if opt.is_present("debug-auth") { + hyper::Client::with_connector(mock::TeeConnector { + connector: hyper::net::HttpsConnector::::default() + }) + } else { + hyper::Client::new() + }, + JsonTokenStorage { + program_name: "adexchangebuyer1d4", + db_dir: config_dir.clone(), + }, None); + + let client = + if opt.is_present("debug") { + hyper::Client::with_connector(mock::TeeConnector { + connector: hyper::net::HttpsConnector::::default() + }) + } else { + hyper::Client::new() + }; + let engine = Engine { + opt: opt, + hub: api::AdExchangeBuyer::new(client, auth), + gp: vec!["alt", "fields", "key", "oauth-token", "pretty-print", "quota-user", "user-ip"], + gpm: vec![ + ("oauth-token", "oauth_token"), + ("pretty-print", "prettyPrint"), + ("quota-user", "quotaUser"), + ("user-ip", "userIp"), + ] + }; + + match engine._doit(true) { + Err(Some(err)) => Err(err), + Err(None) => Ok(engine), + Ok(_) => unreachable!(), + } + } + + fn doit(&self) -> Result<(), DoitError> { + match self._doit(false) { + Ok(res) => res, + Err(_) => unreachable!(), + } + } +} + +fn main() { + let mut exit_status = 0i32; + let arg_data = [ + ("accounts", "methods: 'get', 'list', 'patch' and 'update'", vec![ + ("get", + Some(r##"Gets one account by ID."##), + "Details at http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4_cli/accounts_get", + vec![ + (Some(r##"id"##), + None, + Some(r##"The account id"##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Retrieves the authenticated user's list of accounts."##), + "Details at http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4_cli/accounts_list", + vec![ + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("patch", + Some(r##"Updates an existing account. This method supports patch semantics."##), + "Details at http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4_cli/accounts_patch", + vec![ + (Some(r##"id"##), + None, + Some(r##"The account id"##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("update", + Some(r##"Updates an existing account."##), + "Details at http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4_cli/accounts_update", + vec![ + (Some(r##"id"##), + None, + Some(r##"The account id"##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("billing-info", "methods: 'get' and 'list'", vec![ + ("get", + Some(r##"Returns the billing information for one account specified by account ID."##), + "Details at http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4_cli/billing-info_get", + vec![ + (Some(r##"account-id"##), + None, + Some(r##"The account id."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Retrieves a list of billing information for all accounts of the authenticated user."##), + "Details at http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4_cli/billing-info_list", + vec![ + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("budget", "methods: 'get', 'patch' and 'update'", vec![ + ("get", + Some(r##"Returns the budget information for the adgroup specified by the accountId and billingId."##), + "Details at http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4_cli/budget_get", + vec![ + (Some(r##"account-id"##), + None, + Some(r##"The account id to get the budget information for."##), + Some(true), + Some(false)), + + (Some(r##"billing-id"##), + None, + Some(r##"The billing id to get the budget information for."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("patch", + Some(r##"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."##), + "Details at http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4_cli/budget_patch", + vec![ + (Some(r##"account-id"##), + None, + Some(r##"The account id associated with the budget being updated."##), + Some(true), + Some(false)), + + (Some(r##"billing-id"##), + None, + Some(r##"The billing id associated with the budget being updated."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("update", + Some(r##"Updates the budget amount for the budget of the adgroup specified by the accountId and billingId, with the budget amount in the request."##), + "Details at http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4_cli/budget_update", + vec![ + (Some(r##"account-id"##), + None, + Some(r##"The account id associated with the budget being updated."##), + Some(true), + Some(false)), + + (Some(r##"billing-id"##), + None, + Some(r##"The billing id associated with the budget being updated."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("clientaccess", "methods: 'delete', 'get', 'insert', 'list', 'patch' and 'update'", vec![ + ("delete", + None, + "Details at http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4_cli/clientaccess_delete", + vec![ + (Some(r##"client-account-id"##), + None, + None, + Some(true), + Some(false)), + + (Some(r##"sponsor-account-id"##), + None, + None, + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + ]), + ("get", + None, + "Details at http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4_cli/clientaccess_get", + vec![ + (Some(r##"client-account-id"##), + None, + None, + Some(true), + Some(false)), + + (Some(r##"sponsor-account-id"##), + None, + None, + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("insert", + None, + "Details at http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4_cli/clientaccess_insert", + vec![ + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + None, + "Details at http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4_cli/clientaccess_list", + vec![ + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("patch", + None, + "Details at http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4_cli/clientaccess_patch", + vec![ + (Some(r##"client-account-id"##), + None, + None, + Some(true), + Some(false)), + + (Some(r##"sponsor-account-id"##), + None, + None, + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("update", + None, + "Details at http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4_cli/clientaccess_update", + vec![ + (Some(r##"client-account-id"##), + None, + None, + Some(true), + Some(false)), + + (Some(r##"sponsor-account-id"##), + None, + None, + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("creatives", "methods: 'get', 'insert' and 'list'", vec![ + ("get", + Some(r##"Gets the status for a single creative. A creative will be available 30-40 minutes after submission."##), + "Details at http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4_cli/creatives_get", + vec![ + (Some(r##"account-id"##), + None, + Some(r##"The id for the account that will serve this creative."##), + Some(true), + Some(false)), + + (Some(r##"buyer-creative-id"##), + None, + Some(r##"The buyer-specific id for this creative."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("insert", + Some(r##"Submit a new creative."##), + "Details at http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4_cli/creatives_insert", + vec![ + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Retrieves a list of the authenticated user's active creatives. A creative will be available 30-40 minutes after submission."##), + "Details at http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4_cli/creatives_list", + vec![ + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("deals", "methods: 'get'", vec![ + ("get", + Some(r##"Gets the requested deal."##), + "Details at http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4_cli/deals_get", + vec![ + (Some(r##"deal-id"##), + None, + None, + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("marketplacedeals", "methods: 'delete', 'insert', 'list' and 'update'", vec![ + ("delete", + Some(r##"Delete the specified deals from the order"##), + "Details at http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4_cli/marketplacedeals_delete", + vec![ + (Some(r##"order-id"##), + None, + Some(r##"The orderId to delete deals from."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("insert", + Some(r##"Add new deals for the specified order"##), + "Details at http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4_cli/marketplacedeals_insert", + vec![ + (Some(r##"order-id"##), + None, + Some(r##"OrderId for which deals need to be added."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"List all the deals for a given order"##), + "Details at http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4_cli/marketplacedeals_list", + vec![ + (Some(r##"order-id"##), + None, + Some(r##"The orderId to get deals for."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("update", + Some(r##"Replaces all the deals in the order with the passed in deals"##), + "Details at http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4_cli/marketplacedeals_update", + vec![ + (Some(r##"order-id"##), + None, + Some(r##"The orderId to edit deals on."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("marketplacenotes", "methods: 'insert' and 'list'", vec![ + ("insert", + Some(r##"Add notes to the order"##), + "Details at http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4_cli/marketplacenotes_insert", + vec![ + (Some(r##"order-id"##), + None, + Some(r##"The orderId to add notes for."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Get all the notes associated with an order"##), + "Details at http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4_cli/marketplacenotes_list", + vec![ + (Some(r##"order-id"##), + None, + Some(r##"The orderId to get notes for."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("marketplaceoffers", "methods: 'get' and 'search'", vec![ + ("get", + Some(r##"Gets the requested negotiation."##), + "Details at http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4_cli/marketplaceoffers_get", + vec![ + (Some(r##"offer-id"##), + None, + Some(r##"The offerId for the offer to get the head revision for."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("search", + Some(r##"Gets the requested negotiation."##), + "Details at http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4_cli/marketplaceoffers_search", + vec![ + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("marketplaceorders", "methods: 'get', 'insert', 'patch', 'search' and 'update'", vec![ + ("get", + Some(r##"Get an order given its id"##), + "Details at http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4_cli/marketplaceorders_get", + vec![ + (Some(r##"order-id"##), + None, + Some(r##"Id of the order to retrieve."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("insert", + Some(r##"Create the given list of orders"##), + "Details at http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4_cli/marketplaceorders_insert", + vec![ + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("patch", + Some(r##"Update the given order. This method supports patch semantics."##), + "Details at http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4_cli/marketplaceorders_patch", + vec![ + (Some(r##"order-id"##), + None, + Some(r##"The order id to update."##), + Some(true), + Some(false)), + + (Some(r##"revision-number"##), + None, + Some(r##"The last known revision number to update. If the head revision in the marketplace database has since changed, an error will be thrown. The caller should then fetch the lastest order at head revision and retry the update at that revision."##), + Some(true), + Some(false)), + + (Some(r##"update-action"##), + None, + Some(r##"The proposed action to take on the order."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("search", + Some(r##"Search for orders using pql query"##), + "Details at http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4_cli/marketplaceorders_search", + vec![ + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("update", + Some(r##"Update the given order"##), + "Details at http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4_cli/marketplaceorders_update", + vec![ + (Some(r##"order-id"##), + None, + Some(r##"The order id to update."##), + Some(true), + Some(false)), + + (Some(r##"revision-number"##), + None, + Some(r##"The last known revision number to update. If the head revision in the marketplace database has since changed, an error will be thrown. The caller should then fetch the lastest order at head revision and retry the update at that revision."##), + Some(true), + Some(false)), + + (Some(r##"update-action"##), + None, + Some(r##"The proposed action to take on the order."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("negotiationrounds", "methods: 'insert'", vec![ + ("insert", + Some(r##"Adds the requested negotiationRound to the requested negotiation."##), + "Details at http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4_cli/negotiationrounds_insert", + vec![ + (Some(r##"negotiation-id"##), + None, + None, + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("negotiations", "methods: 'get', 'insert' and 'list'", vec![ + ("get", + Some(r##"Gets the requested negotiation."##), + "Details at http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4_cli/negotiations_get", + vec![ + (Some(r##"negotiation-id"##), + None, + None, + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("insert", + Some(r##"Creates or updates the requested negotiation."##), + "Details at http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4_cli/negotiations_insert", + vec![ + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Lists all negotiations the authenticated user has access to."##), + "Details at http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4_cli/negotiations_list", + vec![ + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("offers", "methods: 'get', 'insert' and 'list'", vec![ + ("get", + Some(r##"Gets the requested offer."##), + "Details at http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4_cli/offers_get", + vec![ + (Some(r##"offer-id"##), + None, + None, + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("insert", + Some(r##"Creates or updates the requested offer."##), + "Details at http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4_cli/offers_insert", + vec![ + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Lists all offers the authenticated user has access to."##), + "Details at http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4_cli/offers_list", + vec![ + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("performance-report", "methods: 'list'", vec![ + ("list", + Some(r##"Retrieves the authenticated user's list of performance metrics."##), + "Details at http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4_cli/performance-report_list", + vec![ + (Some(r##"account-id"##), + None, + Some(r##"The account id to get the reports."##), + Some(true), + Some(false)), + + (Some(r##"end-date-time"##), + None, + Some(r##"The end time of the report in ISO 8601 timestamp format using UTC."##), + Some(true), + Some(false)), + + (Some(r##"start-date-time"##), + None, + Some(r##"The start time of the report in ISO 8601 timestamp format using UTC."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("pretargeting-config", "methods: 'delete', 'get', 'insert', 'list', 'patch' and 'update'", vec![ + ("delete", + Some(r##"Deletes an existing pretargeting config."##), + "Details at http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4_cli/pretargeting-config_delete", + vec![ + (Some(r##"account-id"##), + None, + Some(r##"The account id to delete the pretargeting config for."##), + Some(true), + Some(false)), + + (Some(r##"config-id"##), + None, + Some(r##"The specific id of the configuration to delete."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + ]), + ("get", + Some(r##"Gets a specific pretargeting configuration"##), + "Details at http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4_cli/pretargeting-config_get", + vec![ + (Some(r##"account-id"##), + None, + Some(r##"The account id to get the pretargeting config for."##), + Some(true), + Some(false)), + + (Some(r##"config-id"##), + None, + Some(r##"The specific id of the configuration to retrieve."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("insert", + Some(r##"Inserts a new pretargeting configuration."##), + "Details at http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4_cli/pretargeting-config_insert", + vec![ + (Some(r##"account-id"##), + None, + Some(r##"The account id to insert the pretargeting config for."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Retrieves a list of the authenticated user's pretargeting configurations."##), + "Details at http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4_cli/pretargeting-config_list", + vec![ + (Some(r##"account-id"##), + None, + Some(r##"The account id to get the pretargeting configs for."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("patch", + Some(r##"Updates an existing pretargeting config. This method supports patch semantics."##), + "Details at http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4_cli/pretargeting-config_patch", + vec![ + (Some(r##"account-id"##), + None, + Some(r##"The account id to update the pretargeting config for."##), + Some(true), + Some(false)), + + (Some(r##"config-id"##), + None, + Some(r##"The specific id of the configuration to update."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("update", + Some(r##"Updates an existing pretargeting config."##), + "Details at http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4_cli/pretargeting-config_update", + vec![ + (Some(r##"account-id"##), + None, + Some(r##"The account id to update the pretargeting config for."##), + Some(true), + Some(false)), + + (Some(r##"config-id"##), + None, + Some(r##"The specific id of the configuration to update."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ]; + + let mut app = App::new("adexchangebuyer1d4") + .author("Sebastian Thiel ") + .version("0.3.2+20150909") + .about("Accesses your bidding-account information, submits creatives for validation, finds available direct deals, and retrieves performance reports.") + .after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4_cli") + .arg(Arg::with_name("url") + .long("scope") + .help("Specify the authentication a method should be executed in. Each scope requires the user to grant this application permission to use it.If unset, it defaults to the shortest scope url for a particular method.") + .multiple(true) + .takes_value(true)) + .arg(Arg::with_name("folder") + .long("config-dir") + .help("A directory into which we will store our persistent data. Defaults to a user-writable directory that we will create during the first invocation.[default: ~/.google-service-cli") + .multiple(false) + .takes_value(true)) + .arg(Arg::with_name("debug") + .long("debug") + .help("Output all server communication to standard error. `tx` and `rx` are placed into the same stream.") + .multiple(false) + .takes_value(false)) + .arg(Arg::with_name("debug-auth") + .long("debug-auth") + .help("Output all communication related to authentication to standard error. `tx` and `rx` are placed into the same stream.") + .multiple(false) + .takes_value(false)); + + for &(main_command_name, ref about, ref subcommands) in arg_data.iter() { + let mut mcmd = SubCommand::with_name(main_command_name).about(about); + + for &(sub_command_name, ref desc, url_info, ref args) in subcommands { + let mut scmd = SubCommand::with_name(sub_command_name); + if let &Some(desc) = desc { + scmd = scmd.about(desc); + } + scmd = scmd.after_help(url_info); + + for &(ref arg_name, ref flag, ref desc, ref required, ref multi) in args { + let arg_name_str = + match (arg_name, flag) { + (&Some(an), _ ) => an, + (_ , &Some(f)) => f, + _ => unreachable!(), + }; + let mut arg = Arg::with_name(arg_name_str) + .empty_values(false); + if let &Some(short_flag) = flag { + arg = arg.short(short_flag); + } + if let &Some(desc) = desc { + arg = arg.help(desc); + } + if arg_name.is_some() && flag.is_some() { + arg = arg.takes_value(true); + } + if let &Some(required) = required { + arg = arg.required(required); + } + if let &Some(multi) = multi { + arg = arg.multiple(multi); + } + scmd = scmd.arg(arg); + } + mcmd = mcmd.subcommand(scmd); + } + app = app.subcommand(mcmd); + } + + let matches = app.get_matches(); + + let debug = matches.is_present("debug"); + match Engine::new(matches) { + Err(err) => { + exit_status = err.exit_code; + writeln!(io::stderr(), "{}", err).ok(); + }, + Ok(engine) => { + if let Err(doit_err) = engine.doit() { + exit_status = 1; + match doit_err { + DoitError::IoError(path, err) => { + writeln!(io::stderr(), "Failed to open output file '{}': {}", path, err).ok(); + }, + DoitError::ApiError(err) => { + if debug { + writeln!(io::stderr(), "{:#?}", err).ok(); + } else { + writeln!(io::stderr(), "{}", err).ok(); + } + } + } + } + } + } + + std::process::exit(exit_status); +} \ No newline at end of file diff --git a/gen/adexchangebuyer1d4/Cargo.toml b/gen/adexchangebuyer1d4/Cargo.toml new file mode 100644 index 0000000000..2754beb33e --- /dev/null +++ b/gen/adexchangebuyer1d4/Cargo.toml @@ -0,0 +1,29 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-adexchangebuyer1d4" +version = "0.1.9+20150909" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with Ad Exchange Buyer (protocol v1.4)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/adexchangebuyer1d4" +homepage = "https://developers.google.com/ad-exchange/buyer-rest" +documentation = "http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4" +license = "MIT" +keywords = ["adexchangebuyer", "google", "protocol", "web", "api"] +build = "src/build.rs" + + +[dependencies] +hyper = ">= 0.6.8" +mime = "0.1.0" +serde = ">= 0.6.0" +serde_json = ">= 0.6.0" +yup-oauth2 = "*" +url = "*" + +[build-dependencies] +syntex = { version = "*" } +serde_codegen = { version = "*" } + diff --git a/gen/adexchangebuyer1d4/LICENSE.md b/gen/adexchangebuyer1d4/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/adexchangebuyer1d4/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/adexchangebuyer1d4/README.md b/gen/adexchangebuyer1d4/README.md new file mode 100644 index 0000000000..ea143464bb --- /dev/null +++ b/gen/adexchangebuyer1d4/README.md @@ -0,0 +1,210 @@ + +The `google-adexchangebuyer1d4` 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.9+20150909*, where *20150909* is the exact revision of the *adexchangebuyer:v1.4* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. + +Everything else about the *Ad Exchange Buyer* *v1d4* 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_adexchangebuyer1d4/struct.AdExchangeBuyer.html) ... + +* [accounts](http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4/struct.Account.html) + * [*get*](http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4/struct.AccountGetCall.html), [*list*](http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4/struct.AccountListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4/struct.AccountPatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4/struct.AccountUpdateCall.html) +* [billing info](http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4/struct.BillingInfo.html) + * [*get*](http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4/struct.BillingInfoGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4/struct.BillingInfoListCall.html) +* [budget](http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4/struct.Budget.html) + * [*get*](http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4/struct.BudgetGetCall.html), [*patch*](http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4/struct.BudgetPatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4/struct.BudgetUpdateCall.html) +* clientaccess + * [*delete*](http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4/struct.ClientaccesDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4/struct.ClientaccesGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4/struct.ClientaccesInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4/struct.ClientaccesListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4/struct.ClientaccesPatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4/struct.ClientaccesUpdateCall.html) +* [creatives](http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4/struct.Creative.html) + * [*get*](http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4/struct.CreativeGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4/struct.CreativeInsertCall.html) and [*list*](http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4/struct.CreativeListCall.html) +* deals + * [*get*](http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4/struct.DealGetCall.html) +* marketplacedeals + * [*delete*](http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4/struct.MarketplacedealDeleteCall.html), [*insert*](http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4/struct.MarketplacedealInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4/struct.MarketplacedealListCall.html) and [*update*](http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4/struct.MarketplacedealUpdateCall.html) +* marketplacenotes + * [*insert*](http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4/struct.MarketplacenoteInsertCall.html) and [*list*](http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4/struct.MarketplacenoteListCall.html) +* marketplaceoffers + * [*get*](http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4/struct.MarketplaceofferGetCall.html) and [*search*](http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4/struct.MarketplaceofferSearchCall.html) +* marketplaceorders + * [*get*](http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4/struct.MarketplaceorderGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4/struct.MarketplaceorderInsertCall.html), [*patch*](http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4/struct.MarketplaceorderPatchCall.html), [*search*](http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4/struct.MarketplaceorderSearchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4/struct.MarketplaceorderUpdateCall.html) +* negotiationrounds + * [*insert*](http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4/struct.NegotiationroundInsertCall.html) +* negotiations + * [*get*](http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4/struct.NegotiationGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4/struct.NegotiationInsertCall.html) and [*list*](http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4/struct.NegotiationListCall.html) +* offers + * [*get*](http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4/struct.OfferGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4/struct.OfferInsertCall.html) and [*list*](http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4/struct.OfferListCall.html) +* [performance report](http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4/struct.PerformanceReport.html) + * [*list*](http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4/struct.PerformanceReportListCall.html) +* [pretargeting config](http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4/struct.PretargetingConfig.html) + * [*delete*](http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4/struct.PretargetingConfigDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4/struct.PretargetingConfigGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4/struct.PretargetingConfigInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4/struct.PretargetingConfigListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4/struct.PretargetingConfigPatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4/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_adexchangebuyer1d4/struct.AdExchangeBuyer.html)** + * a central object to maintain state and allow accessing all *Activities* + * creates [*Method Builders*](http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4/trait.MethodsBuilder.html) which in turn + allow access to individual [*Call Builders*](http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4/trait.CallBuilder.html) +* **[Resources](http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4/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_adexchangebuyer1d4/trait.Part.html)** + * a collection of properties + * never directly used in *Activities* +* **[Activities](http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4/trait.CallBuilder.html)** + * operations to apply to *Resources* + +All *structures* are marked with applicable traits to further categorize them and ease browsing. + +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-adexchangebuyer1d4 = "*" +``` + +## A complete example + +```Rust +extern crate hyper; +extern crate yup_oauth2 as oauth2; +extern crate google_adexchangebuyer1d4 as adexchangebuyer1d4; +use adexchangebuyer1d4::PretargetingConfig; +use adexchangebuyer1d4::{Result, Error}; +use std::default::Default; +use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +use adexchangebuyer1d4::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(); + +// You can configure optional parameters by calling 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 { + Err(e) => match e { + // The Error enum provides details about what exactly happened. + // You can also just use its `Debug`, `Display` or `Error` traits + Error::HttpError(_) + |Error::MissingAPIKey + |Error::MissingToken(_) + |Error::Cancelled + |Error::UploadSizeLimitExceeded(_, _) + |Error::Failure(_) + |Error::BadRequest(_) + |Error::FieldClash(_) + |Error::JsonDecodeError(_, _) => println!("{}", e), + }, + Ok(res) => println!("Success: {:?}", res), +} + +``` +## Handling Errors + +All errors produced by the system are provided either as [Result](http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4/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_adexchangebuyer1d4/trait.Delegate.html), or the [Authenticator Delegate](http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4/../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 Downloads +If a method supports downloads, the response body, which is part of the [Result](http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4/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_adexchangebuyer1d4/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_adexchangebuyer1d4/trait.Delegate.html) to the +[Method Builder](http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4/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_adexchangebuyer1d4/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_adexchangebuyer1d4/trait.RequestValue.html) and +[decodable](http://byron.github.io/google-apis-rs/google_adexchangebuyer1d4/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_adexchangebuyer1d4/trait.Part.html) which are identifiable 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_adexchangebuyer1d4/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_adexchangebuyer1d4/trait.RequestValue.html) are moved + +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 **adexchangebuyer1d4** 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/adexchangebuyer1d4/src/build.rs b/gen/adexchangebuyer1d4/src/build.rs new file mode 100644 index 0000000000..fa7bd38c87 --- /dev/null +++ b/gen/adexchangebuyer1d4/src/build.rs @@ -0,0 +1,16 @@ +extern crate syntex; +extern crate serde_codegen; + +use std::env; +use std::path::Path; + +pub fn main() { + let out_dir = env::var_os("OUT_DIR").unwrap(); + + let src = Path::new("src/lib.rs.in"); + let dst = Path::new(&out_dir).join("lib.rs"); + + let mut registry = syntex::Registry::new(); + serde_codegen::register(&mut registry); + registry.expand("google-adexchangebuyer1d4", &src, &dst).unwrap(); +} diff --git a/gen/adexchangebuyer1d4/src/cmn.rs b/gen/adexchangebuyer1d4/src/cmn.rs new file mode 100644 index 0000000000..0e31353ba3 --- /dev/null +++ b/gen/adexchangebuyer1d4/src/cmn.rs @@ -0,0 +1,762 @@ +// COPY OF 'src/rust/api/cmn.rs' +// DO NOT EDIT +use std::io::{self, Read, Seek, Cursor, Write, SeekFrom}; +use std; +use std::fmt::{self, Display}; +use std::str::FromStr; +use std::error; +use std::thread::sleep_ms; + +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::h1::LINE_ENDING; +use hyper::method::Method; +use hyper::status::StatusCode; + +use serde_json as json; + +/// 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 {} + +/// Identifies types for building methods of a particular resource type +pub trait MethodsBuilder {} + +/// Identifies types which represent builders for a particular resource method +pub trait CallBuilder {} + +/// Identifies types which can be inserted and deleted. +/// Types with this trait are most commonly used by clients of this API. +pub trait Resource {} + +/// Identifies types which are used in API responses. +pub trait ResponseResult {} + +/// Identifies types which are used in API requests. +pub trait RequestValue {} + +/// Identifies types which are not actually used by the API +/// This might be a bug within the google API schema. +pub trait UnusedType {} + +/// Identifies types which are only used as part of other types, which +/// usually are carrying the `Resource` trait. +pub trait Part {} + +/// 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 {} + +/// 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 +} + +/// A utility to represent detailed errors we might see in case there are BadRequests. +/// The latter happen if the sent parameters or request structures are unsound +#[derive(Deserialize, Serialize, Debug)] +pub struct ErrorResponse { + error: ServerError, +} + +#[derive(Deserialize, Serialize, Debug)] +pub struct ServerError { + errors: Vec, + code: u16, + message: String, +} + +#[derive(Deserialize, Serialize, Debug)] +pub struct ServerMessage { + domain: String, + reason: String, + message: String, + #[serde(rename="locationType")] + location_type: Option, + location: 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 successful. That way, the delegate 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. + /// + /// If you choose to retry after a duration, the duration should be chosen using the + /// [exponential backoff algorithm](http://en.wikipedia.org/wiki/Exponential_backoff). + /// + /// Return retry information. + fn http_error(&mut self, &hyper::Error) -> 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 it as a general information about the + /// impending failure. + /// The given Error provides information about why the token couldn't be acquired in the + /// first place + fn token(&mut self, err: &error::Error) -> Option { + let _ = err; + 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/canceled, 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()`. + /// It will also be called with None after a successful upload, which allows the delegate + /// to forget the URL. That way, we will not attempt to resume an upload that has already + /// finished. + fn store_upload_url(&mut self, url: Option<&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: &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. + /// + /// If you choose to retry after a duration, the duration should be chosen using the + /// [exponential backoff algorithm](http://en.wikipedia.org/wiki/Exponential_backoff). + fn http_failure(&mut self, _: &hyper::client::Response, Option, _: 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 {} + + +#[derive(Debug)] +pub enum Error { + /// The http connection failed + HttpError(hyper::Error), + + /// 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), + + /// Represents information about a request that was not understood by the server. + /// Details are included. + BadRequest(ErrorResponse), + + /// 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(Box), + + /// 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(String, json::Error), + + /// Indicates an HTTP repsonse with a non-success status code + Failure(hyper::client::Response), +} + + +impl Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + Error::HttpError(ref err) => err.fmt(f), + Error::UploadSizeLimitExceeded(ref resource_size, ref max_size) => + writeln!(f, "The media size {} exceeds the maximum allowed upload size of {}" + , resource_size, max_size), + Error::MissingAPIKey => { + (writeln!(f, "The application's API key was not found in the configuration")).ok(); + writeln!(f, "It is used as there are no Scopes defined for this method.") + }, + Error::BadRequest(ref err) => { + try!(writeln!(f, "Bad Requst ({}): {}", err.error.code, err.error.message)); + for err in err.error.errors.iter() { + try!(writeln!(f, " {}: {}, {}{}", + err.domain, + err.message, + err.reason, + match &err.location { + &Some(ref loc) => format!("@{}", loc), + &None => String::new(), + })); + } + Ok(()) + }, + Error::MissingToken(ref err) => + writeln!(f, "Token retrieval failed with error: {}", err), + Error::Cancelled => + writeln!(f, "Operation cancelled by delegate"), + Error::FieldClash(field) => + writeln!(f, "The custom parameter '{}' is already provided natively by the CallBuilder.", field), + Error::JsonDecodeError(ref json_str, ref err) + => writeln!(f, "{}: {}", err, json_str), + Error::Failure(ref response) => + writeln!(f, "Http status indicates failure: {:?}", response), + } + } +} + +impl error::Error for Error { + fn description(&self) -> &str { + match *self { + Error::HttpError(ref err) => err.description(), + Error::JsonDecodeError(_, ref err) => err.description(), + _ => "NO DESCRIPTION POSSIBLE - use `Display.fmt()` instead" + } + } + + fn cause(&self) -> Option<&error::Error> { + match *self { + Error::HttpError(ref err) => err.cause(), + Error::JsonDecodeError(_, ref err) => err.cause(), + _ => None + } + } +} + +/// A universal result type used as return for all calls. +pub type Result = std::result::Result; + +/// 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 + 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 following macro invocation needs to be expanded, as `include!` +// doens't support external macros +// header!{ +// #[doc="The `X-Upload-Content-Type` header."] +// (XUploadContentType, "X-Upload-Content-Type") => [Mime] + +// xupload_content_type { +// test_header!( +// test1, +// vec![b"text/plain"], +// Some(HeaderField( +// vec![Mime(TopLevel::Text, SubLevel::Plain, Vec::new())] +// ))); + +// } +// } + +/// The `X-Upload-Content-Type` header. +/// +/// Generated via rustc --pretty expanded -Z unstable-options, and manually +/// processed to be more readable. +#[derive(PartialEq, Debug, Clone)] +pub struct XUploadContentType(pub Mime); + +impl ::std::ops::Deref for XUploadContentType { + type Target = Mime; + fn deref<'a>(&'a self) -> &'a Mime { &self.0 } +} +impl ::std::ops::DerefMut for XUploadContentType { + fn deref_mut<'a>(&'a mut self) -> &'a mut Mime { &mut self.0 } +} +impl Header for XUploadContentType { + fn header_name() -> &'static str { "X-Upload-Content-Type" } + fn parse_header(raw: &[Vec]) -> hyper::error::Result { + hyper::header::parsing::from_one_raw_str(raw).map(XUploadContentType) + } +} +impl HeaderFormat for XUploadContentType { + fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { + Display::fmt(&**self, f) + } +} +impl Display for XUploadContentType { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Display::fmt(&**self, f) + } +} + +#[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]) -> hyper::error::Result { + Err(hyper::error::Error::Method) + } +} + + +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]) -> hyper::error::Result { + if raw.len() > 0 { + let v = &raw[0]; + if let Ok(s) = std::str::from_utf8(v) { + const PREFIX: &'static str = "bytes "; + if s.starts_with(PREFIX) { + if let Ok(c) = ::from_str(&s[PREFIX.len()..]) { + return Ok(RangeResponseHeader(c)) + } + } + } + } + Err(hyper::error::Error::Method) + } +} + +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, 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, A> ResumableUploadHelper<'a, A> + where A: oauth2::GetToken { + + fn query_transfer_status(&mut self) -> std::result::Result> { + 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, None) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + return Err(Ok(r)) + } + }; + return Ok(h.0.last) + } + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + return Err(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() { + Ok(s) => s, + Err(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 + }; + + self.reader.seek(SeekFrom::Start(start)).unwrap(); + loop { + let request_size = match self.content_length - start { + rs if rs > chunk_size => chunk_size, + rs => rs + }; + + 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 + } + // workaround https://github.com/rust-lang/rust/issues/22252 + let res = 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(); + match res { + 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, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + } + return Some(Ok(res)) + }, + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + return Some(Err(err)) + } + } + } + } +} + +// Copy of src/rust/cli/cmn.rs +// TODO(ST): Allow sharing common code between program types +pub fn remove_json_null_values(value: &mut json::value::Value) { + match *value { + json::value::Value::Object(ref mut map) => { + let mut for_removal = Vec::new(); + + for (key, mut value) in map.iter_mut() { + if value.is_null() { + for_removal.push(key.clone()); + } else { + remove_json_null_values(&mut value); + } + } + + for key in &for_removal { + map.remove(key); + } + } + _ => {} + } +} diff --git a/gen/adexchangebuyer1d4/src/lib.rs b/gen/adexchangebuyer1d4/src/lib.rs new file mode 100644 index 0000000000..5b0acd52c0 --- /dev/null +++ b/gen/adexchangebuyer1d4/src/lib.rs @@ -0,0 +1,214 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/api/lib.rs.mako' +// DO NOT EDIT ! + +//! This documentation was generated from *Ad Exchange Buyer* crate version *0.1.9+20150909*, where *20150909* is the exact revision of the *adexchangebuyer:v1.4* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +//! +//! Everything else about the *Ad Exchange Buyer* *v1d4* 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/adexchangebuyer1d4). +//! # 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) +//! * clientaccess +//! * [*delete*](struct.ClientaccesDeleteCall.html), [*get*](struct.ClientaccesGetCall.html), [*insert*](struct.ClientaccesInsertCall.html), [*list*](struct.ClientaccesListCall.html), [*patch*](struct.ClientaccesPatchCall.html) and [*update*](struct.ClientaccesUpdateCall.html) +//! * [creatives](struct.Creative.html) +//! * [*get*](struct.CreativeGetCall.html), [*insert*](struct.CreativeInsertCall.html) and [*list*](struct.CreativeListCall.html) +//! * deals +//! * [*get*](struct.DealGetCall.html) +//! * marketplacedeals +//! * [*delete*](struct.MarketplacedealDeleteCall.html), [*insert*](struct.MarketplacedealInsertCall.html), [*list*](struct.MarketplacedealListCall.html) and [*update*](struct.MarketplacedealUpdateCall.html) +//! * marketplacenotes +//! * [*insert*](struct.MarketplacenoteInsertCall.html) and [*list*](struct.MarketplacenoteListCall.html) +//! * marketplaceoffers +//! * [*get*](struct.MarketplaceofferGetCall.html) and [*search*](struct.MarketplaceofferSearchCall.html) +//! * marketplaceorders +//! * [*get*](struct.MarketplaceorderGetCall.html), [*insert*](struct.MarketplaceorderInsertCall.html), [*patch*](struct.MarketplaceorderPatchCall.html), [*search*](struct.MarketplaceorderSearchCall.html) and [*update*](struct.MarketplaceorderUpdateCall.html) +//! * negotiationrounds +//! * [*insert*](struct.NegotiationroundInsertCall.html) +//! * negotiations +//! * [*get*](struct.NegotiationGetCall.html), [*insert*](struct.NegotiationInsertCall.html) and [*list*](struct.NegotiationListCall.html) +//! * offers +//! * [*get*](struct.OfferGetCall.html), [*insert*](struct.OfferInsertCall.html) and [*list*](struct.OfferListCall.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* +//! * creates [*Method Builders*](trait.MethodsBuilder.html) which in turn +//! allow access to individual [*Call Builders*](trait.CallBuilder.html) +//! * **[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* +//! +//! All *structures* are marked with applicable traits to further categorize them and ease browsing. +//! +//! 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-adexchangebuyer1d4 = "*" +//! ``` +//! +//! ## A complete example +//! +//! ```test_harness,no_run +//! extern crate hyper; +//! extern crate yup_oauth2 as oauth2; +//! extern crate google_adexchangebuyer1d4 as adexchangebuyer1d4; +//! use adexchangebuyer1d4::PretargetingConfig; +//! use adexchangebuyer1d4::{Result, Error}; +//! # #[test] fn egal() { +//! use std::default::Default; +//! use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +//! use adexchangebuyer1d4::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(); +//! +//! // You can configure optional parameters by calling 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 { +//! Err(e) => match e { +//! // The Error enum provides details about what exactly happened. +//! // You can also just use its `Debug`, `Display` or `Error` traits +//! Error::HttpError(_) +//! |Error::MissingAPIKey +//! |Error::MissingToken(_) +//! |Error::Cancelled +//! |Error::UploadSizeLimitExceeded(_, _) +//! |Error::Failure(_) +//! |Error::BadRequest(_) +//! |Error::FieldClash(_) +//! |Error::JsonDecodeError(_, _) => println!("{}", e), +//! }, +//! Ok(res) => println!("Success: {:?}", res), +//! } +//! # } +//! ``` +//! ## 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 Downloads +//! 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 identifiable 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 moved +//! +//! 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 +//! +//! + +// 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)] + +include!(concat!(env!("OUT_DIR"), "/lib.rs")); \ No newline at end of file diff --git a/gen/adexchangebuyer1d4/src/lib.rs.in b/gen/adexchangebuyer1d4/src/lib.rs.in new file mode 100644 index 0000000000..245355dde1 --- /dev/null +++ b/gen/adexchangebuyer1d4/src/lib.rs.in @@ -0,0 +1,15625 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/api/lib.rs.in.mako' +// DO NOT EDIT ! + +extern crate hyper; +extern crate serde; +extern crate serde_json; +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 serde_json as json; +use std::io; +use std::fs; +use std::thread::sleep_ms; + +pub use cmn::{MultiPartReader, ToParts, MethodInfo, Result, Error, CallBuilder, Hub, ReadSeek, Part, + ResponseResult, RequestValue, NestedType, Delegate, DefaultDelegate, MethodsBuilder, + Resource, ErrorResponse, remove_json_null_values}; + + +// ############## +// 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 AsRef for Scope { + fn as_ref(&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_adexchangebuyer1d4 as adexchangebuyer1d4; +/// use adexchangebuyer1d4::PretargetingConfig; +/// use adexchangebuyer1d4::{Result, Error}; +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use adexchangebuyer1d4::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(); +/// +/// // You can configure optional parameters by calling 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 { +/// Err(e) => match e { +/// // The Error enum provides details about what exactly happened. +/// // You can also just use its `Debug`, `Display` or `Error` traits +/// Error::HttpError(_) +/// |Error::MissingAPIKey +/// |Error::MissingToken(_) +/// |Error::Cancelled +/// |Error::UploadSizeLimitExceeded(_, _) +/// |Error::Failure(_) +/// |Error::BadRequest(_) +/// |Error::FieldClash(_) +/// |Error::JsonDecodeError(_, _) => println!("{}", e), +/// }, +/// Ok(res) => println!("Success: {:?}", res), +/// } +/// # } +/// ``` +pub struct AdExchangeBuyer { + client: RefCell, + auth: RefCell, + _user_agent: String, +} + +impl<'a, C, A> Hub for AdExchangeBuyer {} + +impl<'a, C, A> AdExchangeBuyer + where 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.9".to_string(), + } + } + + pub fn accounts(&'a self) -> AccountMethods<'a, C, A> { + AccountMethods { hub: &self } + } + pub fn billing_info(&'a self) -> BillingInfoMethods<'a, C, A> { + BillingInfoMethods { hub: &self } + } + pub fn budget(&'a self) -> BudgetMethods<'a, C, A> { + BudgetMethods { hub: &self } + } + pub fn clientaccess(&'a self) -> ClientaccesMethods<'a, C, A> { + ClientaccesMethods { hub: &self } + } + pub fn creatives(&'a self) -> CreativeMethods<'a, C, A> { + CreativeMethods { hub: &self } + } + pub fn deals(&'a self) -> DealMethods<'a, C, A> { + DealMethods { hub: &self } + } + pub fn marketplacedeals(&'a self) -> MarketplacedealMethods<'a, C, A> { + MarketplacedealMethods { hub: &self } + } + pub fn marketplacenotes(&'a self) -> MarketplacenoteMethods<'a, C, A> { + MarketplacenoteMethods { hub: &self } + } + pub fn marketplaceoffers(&'a self) -> MarketplaceofferMethods<'a, C, A> { + MarketplaceofferMethods { hub: &self } + } + pub fn marketplaceorders(&'a self) -> MarketplaceorderMethods<'a, C, A> { + MarketplaceorderMethods { hub: &self } + } + pub fn negotiationrounds(&'a self) -> NegotiationroundMethods<'a, C, A> { + NegotiationroundMethods { hub: &self } + } + pub fn negotiations(&'a self) -> NegotiationMethods<'a, C, A> { + NegotiationMethods { hub: &self } + } + pub fn offers(&'a self) -> OfferMethods<'a, C, A> { + OfferMethods { hub: &self } + } + pub fn performance_report(&'a self) -> PerformanceReportMethods<'a, C, A> { + PerformanceReportMethods { hub: &self } + } + pub fn pretargeting_config(&'a self) -> PretargetingConfigMethods<'a, C, 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.9`. + /// + /// 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 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(rename="productCategories")] + pub product_categories: Option>, + /// The last upload timestamp of this creative if it was uploaded via API. Read-only. The value of this field is generated, and will be ignored for uploads. (formatted RFC 3339 timestamp). + pub api_upload_timestamp: Option, + /// The agency id for this creative. + #[serde(rename="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(rename="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(rename="HTMLSnippet")] + pub html_snippet: Option, + /// Top-level open auction status. Read-only. This field should not be set in requests. If disapproved, an entry for auctionType=OPEN_AUCTION (or ALL) in servingRestrictions will also exist. Note that this may be nuanced with other contextual restrictions, in which case it may be preferable to read from ServingRestrictions directly. + #[serde(rename="openAuctionStatus")] + pub open_auction_status: Option, + /// A buyer-specific id identifying the creative in this ad. + #[serde(rename="buyerCreativeId")] + pub buyer_creative_id: Option, + /// Top-level deals status. Read-only. This field should not be set in requests. If disapproved, an entry for auctionType=DIRECT_DEALS (or ALL) in servingRestrictions will also exist. Note that this may be nuanced with other contextual restrictions, in which case it may be preferable to read from servingRestrictions directly. + #[serde(rename="dealsStatus")] + pub deals_status: Option, + /// The set of urls to be called to record an impression. + #[serde(rename="impressionTrackingUrl")] + pub impression_tracking_url: Option>, + /// Account id. + #[serde(rename="accountId")] + pub account_id: Option, + /// Detected advertiser id, if any. Read-only. This field should not be set in requests. + #[serde(rename="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(rename="videoURL")] + pub video_url: Option, + /// The set of destination urls for the snippet. + #[serde(rename="clickThroughUrl")] + pub click_through_url: Option>, + /// The granular status of this ad in specific contexts. A context here relates to where something ultimately serves (for example, a physical location, a platform, an HTTPS vs HTTP request, or the type of auction). Read-only. This field should not be set in requests. + #[serde(rename="servingRestrictions")] + pub serving_restrictions: 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, + /// If nativeAd is set, HTMLSnippet and videoURL should not be set. + #[serde(rename="nativeAd")] + pub native_ad: Option, + /// The version for this creative. Read-only. This field should not be set in requests. + pub version: Option, + /// All restricted categories for the ads that may be shown from this snippet. + #[serde(rename="restrictedCategories")] + pub restricted_categories: Option>, + /// All vendor types for the ads that may be shown from this snippet. + #[serde(rename="vendorType")] + pub vendor_type: Option>, + /// The filtering reasons for the creative. Read-only. This field should not be set in requests. + #[serde(rename="filteringReasons")] + pub filtering_reasons: Option, + /// Detected sensitive categories, if any. Read-only. This field should not be set in requests. + #[serde(rename="sensitiveCategories")] + pub sensitive_categories: Option>, +} + +impl RequestValue for Creative {} +impl Resource for Creative {} +impl ResponseResult for Creative {} + + +/// 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 marketplacedeals](struct.MarketplacedealDeleteCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct DeleteOrderDealsRequest { + /// The last known order revision number. + #[serde(rename="orderRevisionNumber")] + pub order_revision_number: Option, + /// no description provided + #[serde(rename="updateAction")] + pub update_action: Option, + /// List of deals to delete for a given order + #[serde(rename="dealIds")] + pub deal_ids: Option>, +} + +impl RequestValue for DeleteOrderDealsRequest {} + + +/// 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 TargetingValueSize { + /// The width of the creative. + pub width: Option, + /// The height of the creative. + pub height: Option, +} + +impl Part for TargetingValueSize {} + + +/// 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 TargetingValueDayPartTargetingDayPart { + /// no description provided + #[serde(rename="dayOfWeek")] + pub day_of_week: Option, + /// no description provided + #[serde(rename="endHour")] + pub end_hour: Option, + /// no description provided + #[serde(rename="startHour")] + pub start_hour: Option, + /// no description provided + #[serde(rename="endMinute")] + pub end_minute: Option, + /// no description provided + #[serde(rename="startMinute")] + pub start_minute: Option, +} + +impl Part for TargetingValueDayPartTargetingDayPart {} + + +/// The app icon, for app download 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 CreativeNativeAdAppIcon { + /// no description provided + pub url: Option, + /// no description provided + pub width: Option, + /// no description provided + pub height: Option, +} + +impl NestedType for CreativeNativeAdAppIcon {} +impl Part for CreativeNativeAdAppIcon {} + + +/// 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 BuyerDto { + /// no description provided + #[serde(rename="enabledForPreferredDeals")] + pub enabled_for_preferred_deals: Option, + /// no description provided + #[serde(rename="enabledForInterestTargetingDeals")] + pub enabled_for_interest_targeting_deals: Option, + /// no description provided + #[serde(rename="displayName")] + pub display_name: Option, + /// no description provided + #[serde(rename="sponsorAccountId")] + pub sponsor_account_id: Option, + /// no description provided + #[serde(rename="accountId")] + pub account_id: Option, + /// no description provided + pub id: Option, + /// no description provided + #[serde(rename="customerId")] + pub customer_id: Option, +} + +impl Part for BuyerDto {} + + +/// 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 marketplacenotes](struct.MarketplacenoteListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct GetOrderNotesResponse { + /// The list of matching notes. + pub notes: Option>, +} + +impl ResponseResult for GetOrderNotesResponse {} + + +/// A smaller image, for the advertiser logo. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct CreativeNativeAdLogo { + /// no description provided + pub url: Option, + /// no description provided + pub width: Option, + /// no description provided + pub height: Option, +} + +impl NestedType for CreativeNativeAdLogo {} +impl Part for CreativeNativeAdLogo {} + + +/// 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 DealPartyDto { + /// no description provided + pub buyer: Option, + /// no description provided + #[serde(rename="webProperty")] + pub web_property: Option, + /// no description provided + #[serde(rename="buyerSellerRole")] + pub buyer_seller_role: Option, + /// no description provided + #[serde(rename="customerId")] + pub customer_id: Option, + /// no description provided + pub name: Option, +} + +impl Part for DealPartyDto {} + + +/// 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 BrandDto { + /// no description provided + #[serde(rename="advertiserId")] + pub advertiser_id: Option, + /// no description provided + pub id: Option, + /// no description provided + pub name: Option, +} + +impl Part for BrandDto {} + + +/// All known contexts/restrictions. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct CreativeServingRestrictionsContexts { + /// Only set when contextType=PLATFORM. Represents the platforms this restriction applies to. + pub platform: Option>, + /// The type of context (e.g., location, platform, auction type, SSL-ness). + #[serde(rename="contextType")] + pub context_type: Option, + /// Only set when contextType=AUCTION_TYPE. Represents the auction types this restriction applies to. + #[serde(rename="auctionType")] + pub auction_type: Option>, + /// Only set when contextType=LOCATION. Represents the geo criterias this restriction applies to. + #[serde(rename="geoCriteriaId")] + pub geo_criteria_id: Option>, +} + +impl NestedType for CreativeServingRestrictionsContexts {} +impl Part for CreativeServingRestrictionsContexts {} + + +/// 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 marketplacedeals](struct.MarketplacedealUpdateCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct EditAllOrderDealsResponse { + /// List of all deals in the order after edit. + pub deals: Option>, +} + +impl ResponseResult for EditAllOrderDealsResponse {} + + +/// 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 DealTermsNonGuaranteedAuctionTerms { + /// Reserve price for the specified buyer. + #[serde(rename="reservePricePerBuyers")] + pub reserve_price_per_buyers: Option>, + /// Id of the corresponding private auction. + #[serde(rename="privateAuctionId")] + pub private_auction_id: Option, +} + +impl Part for DealTermsNonGuaranteedAuctionTerms {} + + +/// 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: Option, + /// Additional details about the correction. + pub details: Option>, +} + +impl NestedType for CreativeCorrections {} +impl Part for CreativeCorrections {} + + +/// 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 clientaccess](struct.ClientaccesListCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ListClientAccessCapabilitiesRequest { + /// no description provided + #[serde(rename="sponsorAccountId")] + pub sponsor_account_id: Option, +} + +impl RequestValue for ListClientAccessCapabilitiesRequest {} + + +/// A large 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 CreativeNativeAdImage { + /// no description provided + pub url: Option, + /// no description provided + pub width: Option, + /// no description provided + pub height: Option, +} + +impl NestedType for CreativeNativeAdImage {} +impl Part for CreativeNativeAdImage {} + + +/// 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 Buyer { + /// Adx account id of the buyer. + #[serde(rename="accountId")] + pub account_id: Option, +} + +impl Part for Buyer {} + + +/// 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 DealTermsNonGuaranteedFixedPriceTerms { + /// Fixed price for the specified buyer. + #[serde(rename="fixedPrices")] + pub fixed_prices: Option>, +} + +impl Part for DealTermsNonGuaranteedFixedPriceTerms {} + + +/// 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: Option, + /// 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: Option, + /// The maximum queries per second the Ad Exchange will send. + #[serde(rename="maximumQps")] + pub maximum_qps: Option, +} + +impl NestedType for AccountBidderLocation {} +impl Part for AccountBidderLocation {} + + +/// 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(rename="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(rename="maximumActiveCreatives")] + pub maximum_active_creatives: Option, + /// Your bidder locations that have distinct URLs. + #[serde(rename="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(rename="cookieMatchingNid")] + pub cookie_matching_nid: Option, + /// The number of creatives that this account inserted or bid with in the last 30 days. + #[serde(rename="numberActiveCreatives")] + pub number_active_creatives: Option, + /// Account id. + pub id: Option, + /// The base URL used in cookie match requests. + #[serde(rename="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*). +/// +/// * [insert marketplacedeals](struct.MarketplacedealInsertCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct AddOrderDealsResponse { + /// List of deals added (in the same order as passed in the request) + pub deals: Option>, + /// The updated revision number for the order. + #[serde(rename="orderRevisionNumber")] + pub order_revision_number: Option, +} + +impl ResponseResult for AddOrderDealsResponse {} + + +/// An order is associated with a bunch of notes which may optionally be associated with a deal and/or revision number. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct MarketplaceNote { + /// The order_id that a note is attached to. (readonly) + #[serde(rename="orderId")] + pub order_id: Option, + /// Identifies what kind of resource this is. Value: the fixed string "adexchangebuyer#marketplaceNote". + pub kind: Option, + /// The role of the person (buyer/seller) creating the note. (readonly) + #[serde(rename="creatorRole")] + pub creator_role: Option, + /// Notes can optionally be associated with a deal. (readonly, except on create) + #[serde(rename="dealId")] + pub deal_id: Option, + /// The actual note to attach. (readonly, except on create) + pub note: Option, + /// If the note is associated with an order revision number, then store that here. (readonly, except on create) + #[serde(rename="orderRevisionNumber")] + pub order_revision_number: Option, + /// The unique id for the note. (readonly) + #[serde(rename="noteId")] + pub note_id: Option, + /// The timestamp (ms since epoch) that this note was created. (readonly) + #[serde(rename="timestampMs")] + pub timestamp_ms: Option, +} + +impl Part for MarketplaceNote {} + + +/// 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 marketplacedeals](struct.MarketplacedealDeleteCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct DeleteOrderDealsResponse { + /// List of deals deleted (in the same order as passed in the request) + pub deals: Option>, + /// The updated revision number for the order. + #[serde(rename="orderRevisionNumber")] + pub order_revision_number: Option, +} + +impl ResponseResult for DeleteOrderDealsResponse {} + + +/// 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 marketplacenotes](struct.MarketplacenoteInsertCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct AddOrderNotesRequest { + /// The list of notes to add. + pub notes: Option>, +} + +impl RequestValue for AddOrderNotesRequest {} + + +/// 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, Serialize, Deserialize)] +pub struct PerformanceReport { + /// Average QPS for cookie matcher operations. + #[serde(rename="cookieMatcherStatusRate")] + pub cookie_matcher_status_rate: Option>, + /// Rate of various prefiltering statuses per match. Please refer to the callout-status-codes.txt file for different statuses. + #[serde(rename="calloutStatusRate")] + pub callout_status_rate: Option>, + /// Average QPS for hosted match operations. + #[serde(rename="hostedMatchStatusRate")] + pub hosted_match_status_rate: Option>, + /// The number of bid requests sent to your bidder. + #[serde(rename="bidRequestRate")] + pub bid_request_rate: Option, + /// The number of bid responses that were unsuccessful due to timeouts, incorrect formatting, etc. + #[serde(rename="unsuccessfulRequestRate")] + pub unsuccessful_request_rate: Option, + /// The 50th percentile round trip latency(ms) as perceived from Google servers for the duration period covered by the report. + #[serde(rename="latency50thPercentile")] + pub latency50th_percentile: Option, + /// The number of properly formed bid responses received by our servers within the deadline. + #[serde(rename="successfulRequestRate")] + pub successful_request_rate: Option, + /// The 85th percentile round trip latency(ms) as perceived from Google servers for the duration period covered by the report. + #[serde(rename="latency85thPercentile")] + pub latency85th_percentile: Option, + /// Average QPS for pixel match responses from clients. + #[serde(rename="pixelMatchResponses")] + pub pixel_match_responses: Option, + /// Rate of ads with a given status. Please refer to the creative-status-codes.txt file for different statuses. + #[serde(rename="creativeStatusRate")] + pub creative_status_rate: Option>, + /// The 95th percentile round trip latency(ms) as perceived from Google servers for the duration period covered by the report. + #[serde(rename="latency95thPercentile")] + pub latency95th_percentile: Option, + /// Rate of various quota account statuses per quota check. + #[serde(rename="noQuotaInRegion")] + pub no_quota_in_region: Option, + /// Resource type. + pub kind: Option, + /// The number of potential queries based on your pretargeting settings. + #[serde(rename="inventoryMatchRate")] + pub inventory_match_rate: Option, + /// The trading location of this data. + pub region: Option, + /// The number of bid responses with an ad. + #[serde(rename="bidRate")] + pub bid_rate: Option, + /// The configured quota limits for this account. + #[serde(rename="quotaConfiguredLimit")] + pub quota_configured_limit: Option, + /// Rate of various quota account statuses per quota check. + #[serde(rename="outOfQuota")] + pub out_of_quota: Option, + /// The unix timestamp of the starting time of this performance data. + pub timestamp: Option, + /// The throttled quota limits for this account. + #[serde(rename="quotaThrottledLimit")] + pub quota_throttled_limit: Option, + /// The number of bid responses that were filtered due to a policy violation or other errors. + #[serde(rename="filteredBidRate")] + pub filtered_bid_rate: Option, + /// Average QPS for pixel match requests from clients. + #[serde(rename="pixelMatchRequests")] + pub pixel_match_requests: Option, +} + +impl Part for PerformanceReport {} + + +/// 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, Serialize, Deserialize)] +pub struct PerformanceReportList { + /// Resource type. + pub kind: Option, + /// A list of performance reports relevant for the account. + #[serde(rename="performanceReport")] + pub performance_report: Option>, +} + +impl ResponseResult for PerformanceReportList {} + + +/// 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 AdvertiserDto { + /// no description provided + pub brands: Option>, + /// no description provided + pub status: Option, + /// no description provided + pub id: Option, + /// no description provided + pub name: Option, +} + +impl Part for AdvertiserDto {} + + +/// 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 marketplacedeals](struct.MarketplacedealListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct GetOrderDealsResponse { + /// List of deals for the order + pub deals: Option>, +} + +impl ResponseResult for GetOrderDealsResponse {} + + +/// 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 SharedTargeting { + /// The list of value to include as part of the targeting. + pub inclusions: Option>, + /// The list of values to exclude from targeting. + pub exclusions: Option>, + /// The key representing the shared targeting criterion. + pub key: Option, +} + +impl Part for SharedTargeting {} + + +/// 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, Serialize, Deserialize)] +pub struct BillingInfoList { + /// A list of billing info relevant for your account. + pub items: Option>, + /// Resource type. + pub kind: Option, +} + +impl ResponseResult for BillingInfoList {} + + +/// 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 DateTime { + /// no description provided + #[serde(rename="timeZoneId")] + pub time_zone_id: Option, + /// no description provided + pub second: Option, + /// no description provided + pub hour: Option, + /// no description provided + pub year: Option, + /// no description provided + pub day: Option, + /// no description provided + pub minute: Option, + /// no description provided + pub month: Option, +} + +impl Part for DateTime {} + + +/// 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 InventorySegmentTargeting { + /// no description provided + #[serde(rename="negativeXfpAdSlots")] + pub negative_xfp_ad_slots: Option>, + /// no description provided + #[serde(rename="positiveInventorySlots")] + pub positive_inventory_slots: Option>, + /// no description provided + #[serde(rename="negativeSiteUrls")] + pub negative_site_urls: Option>, + /// no description provided + #[serde(rename="positiveIcmBrands")] + pub positive_icm_brands: Option>, + /// no description provided + #[serde(rename="negativeXfpPlacements")] + pub negative_xfp_placements: Option>, + /// no description provided + #[serde(rename="positiveVideoAdPositionSegments")] + pub positive_video_ad_position_segments: Option>, + /// no description provided + #[serde(rename="negativeIcmInterests")] + pub negative_icm_interests: Option>, + /// no description provided + #[serde(rename="negativeAudienceSegments")] + pub negative_audience_segments: Option>, + /// no description provided + #[serde(rename="positiveOperatingSystems")] + pub positive_operating_systems: Option>, + /// no description provided + #[serde(rename="negativeOperatingSystems")] + pub negative_operating_systems: Option>, + /// no description provided + #[serde(rename="negativeIcmBrands")] + pub negative_icm_brands: Option>, + /// no description provided + #[serde(rename="positiveLocations")] + pub positive_locations: Option>, + /// no description provided + #[serde(rename="negativeVideoAdPositionSegments")] + pub negative_video_ad_position_segments: Option>, + /// no description provided + #[serde(rename="positiveDeviceCategories")] + pub positive_device_categories: Option>, + /// no description provided + #[serde(rename="negativeAdSizes")] + pub negative_ad_sizes: Option>, + /// no description provided + #[serde(rename="negativeInventorySlots")] + pub negative_inventory_slots: Option>, + /// no description provided + #[serde(rename="negativeMobileApps")] + pub negative_mobile_apps: Option>, + /// no description provided + #[serde(rename="negativeVideoDurationSegments")] + pub negative_video_duration_segments: Option>, + /// no description provided + #[serde(rename="positiveSizes")] + pub positive_sizes: Option>, + /// no description provided + #[serde(rename="positiveXfpAdSlots")] + pub positive_xfp_ad_slots: Option>, + /// no description provided + #[serde(rename="positiveKeyValues")] + pub positive_key_values: Option>, + /// no description provided + #[serde(rename="positiveSiteUrls")] + pub positive_site_urls: Option>, + /// no description provided + #[serde(rename="positiveMobileApps")] + pub positive_mobile_apps: Option>, + /// no description provided + #[serde(rename="negativeKeyValues")] + pub negative_key_values: Option>, + /// no description provided + #[serde(rename="negativeSizes")] + pub negative_sizes: Option>, + /// no description provided + #[serde(rename="positiveOperatingSystemVersions")] + pub positive_operating_system_versions: Option>, + /// no description provided + #[serde(rename="negativeLocations")] + pub negative_locations: Option>, + /// no description provided + #[serde(rename="positiveAdSizes")] + pub positive_ad_sizes: Option>, + /// no description provided + #[serde(rename="negativeOperatingSystemVersions")] + pub negative_operating_system_versions: Option>, + /// no description provided + #[serde(rename="positiveXfpPlacements")] + pub positive_xfp_placements: Option>, + /// no description provided + #[serde(rename="positiveIcmInterests")] + pub positive_icm_interests: Option>, + /// no description provided + #[serde(rename="positiveVideoDurationSegments")] + pub positive_video_duration_segments: Option>, + /// no description provided + #[serde(rename="positiveAudienceSegments")] + pub positive_audience_segments: Option>, + /// no description provided + #[serde(rename="negativeDeviceCategories")] + pub negative_device_categories: Option>, + /// no description provided + #[serde(rename="positiveAdTypeSegments")] + pub positive_ad_type_segments: Option>, + /// no description provided + #[serde(rename="negativeAdTypeSegments")] + pub negative_ad_type_segments: Option>, +} + +impl Part for InventorySegmentTargeting {} + + +/// 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 AudienceSegment { + /// no description provided + pub description: Option, + /// no description provided + pub id: Option, + /// no description provided + pub name: Option, + /// no description provided + #[serde(rename="numCookies")] + pub num_cookies: Option, +} + +impl Part for AudienceSegment {} + + +/// 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 negotiations](struct.NegotiationGetCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct GetNegotiationByIdRequest { + /// no description provided + #[serde(rename="includePrivateAuctions")] + pub include_private_auctions: Option, +} + +impl RequestValue for GetNegotiationByIdRequest {} + + +/// 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 marketplaceorders](struct.MarketplaceorderInsertCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct CreateOrdersResponse { + /// The list of orders successfully created. + pub orders: Option>, +} + +impl ResponseResult for CreateOrdersResponse {} + + +/// Represents an order in the marketplace. An order is the unit of negotiation between a seller and a buyer and contains deals which are served. Each field in an order can have one of the following setting: +/// +/// (readonly) - It is an error to try and set this field. (buyer-readonly) - Only the seller can set this field. (seller-readonly) - Only the buyer can set this field. (updatable) - The field is updatable at all times by either buyer or the seller. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where 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 marketplaceorders](struct.MarketplaceorderGetCall.html) (response) +/// * [patch marketplaceorders](struct.MarketplaceorderPatchCall.html) (request|response) +/// * [update marketplaceorders](struct.MarketplaceorderUpdateCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct MarketplaceOrder { + /// The unique id of the order. (readonly). + #[serde(rename="orderId")] + pub order_id: Option, + /// List of labels associated with the order. (readonly) + pub labels: Option>, + /// Indicates whether the buyer/seller created the offer.(readonly) + #[serde(rename="originatorRole")] + pub originator_role: Option, + /// Optional contact information for the seller (buyer-readonly). + #[serde(rename="sellerContacts")] + pub seller_contacts: Option>, + /// Reference to the buyer on the order. (readonly, except on create) + pub buyer: Option, + /// The current state of the order. (readonly) + #[serde(rename="orderState")] + pub order_state: Option, + /// When an order is in an accepted state, indicates whether the buyer has signed off Once both sides have signed off on a deal, the order can be finalized by the seller. (buyer-readonly) + #[serde(rename="hasSellerSignedOff")] + pub has_seller_signed_off: Option, + /// no description provided + #[serde(rename="lastUpdaterRole")] + pub last_updater_role: Option, + /// When an order is in an accepted state, indicates whether the buyer has signed off Once both sides have signed off on a deal, the order can be finalized by the seller. (seller-readonly) + #[serde(rename="hasBuyerSignedOff")] + pub has_buyer_signed_off: Option, + /// The revision number for the order (readonly). + #[serde(rename="revisionNumber")] + pub revision_number: Option, + /// Identifies what kind of resource this is. Value: the fixed string "adexchangebuyer#marketplaceOrder". + pub kind: Option, + /// The name for the order (updatable) + pub name: Option, + /// The time (ms since epoch) when the order was last revised (readonly). + #[serde(rename="revisionTimeMs")] + pub revision_time_ms: Option, + /// Private data for buyer. (hidden from seller). + #[serde(rename="buyerPrivateData")] + pub buyer_private_data: Option, + /// Reference to the buyer that will get billed for this order. (readonly) + #[serde(rename="billedBuyer")] + pub billed_buyer: Option, + /// Reference to the seller on the order. (readonly, except on create) + pub seller: Option, + /// True if the order is being renegotiated (readonly). + #[serde(rename="isRenegotiating")] + pub is_renegotiating: Option, + /// True, if the buyside inventory setup is complete for this order. (readonly) + #[serde(rename="isSetupComplete")] + pub is_setup_complete: Option, + /// The role of the last user that either updated the order or left a comment. (readonly) + #[serde(rename="lastUpdaterOrCommentorRole")] + pub last_updater_or_commentor_role: Option, + /// Optional contact information fort the buyer. (seller-readonly) + #[serde(rename="buyerContacts")] + pub buyer_contacts: Option>, +} + +impl RequestValue for MarketplaceOrder {} +impl Resource for MarketplaceOrder {} +impl ResponseResult for MarketplaceOrder {} + + +/// 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 TargetingValueCreativeSize { + /// The Creative size type. + #[serde(rename="creativeSizeType")] + pub creative_size_type: Option, + /// For video size type, the list of companion sizes. + #[serde(rename="companionSizes")] + pub companion_sizes: Option>, + /// For regular creative size type, specifies the size of the creative. + pub size: Option, +} + +impl Part for TargetingValueCreativeSize {} + + +/// 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 TargetingValue { + /// The daypart targeting to include / exclude. Filled in when the key is GOOG_DAYPART_TARGETING. + #[serde(rename="dayPartTargetingValue")] + pub day_part_targeting_value: Option, + /// The long value to exclude/include. + #[serde(rename="longValue")] + pub long_value: Option, + /// The creative size value to exclude/include. + #[serde(rename="creativeSizeValue")] + pub creative_size_value: Option, + /// The string value to exclude/include. + #[serde(rename="stringValue")] + pub string_value: Option, +} + +impl Part for TargetingValue {} + + +/// 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 DealTerms { + /// The terms for guaranteed fixed price deals. + #[serde(rename="guaranteedFixedPriceTerms")] + pub guaranteed_fixed_price_terms: Option, + /// Description for the proposed terms of the deal. + pub description: Option, + /// The terms for non-guaranteed auction deals. + #[serde(rename="nonGuaranteedAuctionTerms")] + pub non_guaranteed_auction_terms: Option, + /// The terms for non-guaranteed fixed price deals. + #[serde(rename="nonGuaranteedFixedPriceTerms")] + pub non_guaranteed_fixed_price_terms: Option, +} + +impl Part for DealTerms {} + + +/// 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: Option, + /// The type of the placement. + #[serde(rename="type")] + pub type_: Option, +} + +impl NestedType for PretargetingConfigExcludedPlacements {} +impl Part for PretargetingConfigExcludedPlacements {} + + +/// 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 negotiations](struct.NegotiationListCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct GetNegotiationsRequest { + /// no description provided + #[serde(rename="sinceTimestampMillis")] + pub since_timestamp_millis: Option, + /// no description provided + #[serde(rename="includePrivateAuctions")] + pub include_private_auctions: Option, + /// no description provided + pub finalized: Option, +} + +impl RequestValue for GetNegotiationsRequest {} + + +/// 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 TargetingValueDayPartTargeting { + /// no description provided + #[serde(rename="dayParts")] + pub day_parts: Option>, + /// no description provided + #[serde(rename="timeZoneType")] + pub time_zone_type: Option, +} + +impl Part for TargetingValueDayPartTargeting {} + + +/// 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 offers](struct.OfferListCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ListOffersRequest { + /// no description provided + #[serde(rename="sinceTimestampMillis")] + pub since_timestamp_millis: Option, +} + +impl RequestValue for ListOffersRequest {} + + +/// 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 PrivateData { + /// no description provided + #[serde(rename="referenceId")] + pub reference_id: Option, + /// no description provided + #[serde(rename="referencePayload")] + pub reference_payload: Option, +} + +impl Part for PrivateData {} + + +/// 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: Option, + /// The type of the placement. + #[serde(rename="type")] + pub type_: Option, +} + +impl NestedType for PretargetingConfigPlacements {} +impl Part for PretargetingConfigPlacements {} + + +/// 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 offers](struct.OfferListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ListOffersResponse { + /// no description provided + pub kind: Option, + /// no description provided + pub offers: Option>, +} + +impl ResponseResult for ListOffersResponse {} + + +/// The granular status of this ad in specific contexts. A context here relates to where something ultimately serves (for example, a physical location, a platform, an HTTPS vs HTTP request, or the type of auction). 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 CreativeServingRestrictions { + /// All known contexts/restrictions. + pub contexts: Option>, + /// The reasons for disapproval within this restriction, if any. Note that not all disapproval reasons may be categorized, so it is possible for the creative to have a status of DISAPPROVED or CONDITIONALLY_APPROVED with an empty list for disapproval_reasons. In this case, please reach out to your TAM to help debug the issue. + #[serde(rename="disapprovalReasons")] + pub disapproval_reasons: Option>, + /// Why the creative is ineligible to serve in this context (e.g., it has been explicitly disapproved or is pending review). + pub reason: Option, +} + +impl NestedType for CreativeServingRestrictions {} +impl Part for CreativeServingRestrictions {} + + +/// The filtering reasons for the 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 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: Option, + /// The filtering reasons. + pub reasons: Option>, +} + +impl NestedType for CreativeFilteringReasons {} +impl Part for CreativeFilteringReasons {} + + +/// 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 AdSlotDto { + /// no description provided + pub description: Option, + /// no description provided + pub name: Option, + /// no description provided + #[serde(rename="webPropertyId")] + pub web_property_id: Option, + /// no description provided + #[serde(rename="channelId")] + pub channel_id: Option, + /// no description provided + #[serde(rename="channelCode")] + pub channel_code: Option, + /// no description provided + pub size: Option, +} + +impl Part for AdSlotDto {} + + +/// 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, Serialize, Deserialize)] +pub struct PretargetingConfigList { + /// A list of pretargeting configs + pub items: Option>, + /// Resource type. + pub kind: Option, +} + +impl ResponseResult for PretargetingConfigList {} + + +/// 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 TermsDto { + /// If true, the offer will finalize automatically when accepted. + #[serde(rename="finalizeAutomatically")] + pub finalize_automatically: Option, + /// The inventory segment targeting for the offer. + #[serde(rename="inventorySegmentTargeting")] + pub inventory_segment_targeting: Option, + /// The audience segment for the offer. + #[serde(rename="audienceSegment")] + pub audience_segment: Option, + /// The end date for the offer. + #[serde(rename="endDate")] + pub end_date: Option, + /// A list of terms attributes. + #[serde(rename="termsAttributes")] + pub terms_attributes: Option>, + /// The start date for the offer. + #[serde(rename="startDate")] + pub start_date: Option, + /// The buyer billing type. + #[serde(rename="buyerBillingType")] + pub buyer_billing_type: Option, + /// The estimated daily impressions for the offer. + #[serde(rename="estimatedImpressionsPerDay")] + pub estimated_impressions_per_day: Option, + /// The monetizer type. + #[serde(rename="monetizerType")] + pub monetizer_type: Option, + /// The billing terms. + #[serde(rename="billingTerms")] + pub billing_terms: Option, + /// Whether to target by deal id. + #[serde(rename="targetByDealId")] + pub target_by_deal_id: Option, + /// The particular ad slots targeted by the offer. + #[serde(rename="adSlots")] + pub ad_slots: Option>, + /// A list of advertisers for this offer. + pub advertisers: Option>, + /// The minimum spend for the offer. + #[serde(rename="minimumSpendMicros")] + pub minimum_spend_micros: Option, + /// If true, the offer targets all ad slots. + #[serde(rename="targetingAllAdSlots")] + pub targeting_all_ad_slots: Option, + /// A description for these terms. + pub description: Option, + /// The minimum true looks for the offer. + #[serde(rename="minimumTrueLooks")] + pub minimum_true_looks: Option, + /// The cpm terms. + pub cpm: Option, + /// Whether the offer is a reservation. + #[serde(rename="isReservation")] + pub is_reservation: Option, + /// The urls applicable to the offer. + pub urls: Option>, + /// Whether to use or ignore publisher blocking rules. + #[serde(rename="creativeBlockingLevel")] + pub creative_blocking_level: Option, + /// Whether to use publisher review policy or AdX review policy. + #[serde(rename="creativeReviewPolicy")] + pub creative_review_policy: Option, + /// A description of the audience segment for the offer. + #[serde(rename="audienceSegmentDescription")] + pub audience_segment_description: Option, + /// A descriptive name for these terms. + #[serde(rename="descriptiveName")] + pub descriptive_name: Option, + /// Whether this offer is semi-transparent. + #[serde(rename="semiTransparent")] + pub semi_transparent: Option, + /// The estimated spend for the offer. + #[serde(rename="estimatedSpend")] + pub estimated_spend: Option, + /// The premium terms. + #[serde(rename="dealPremium")] + pub deal_premium: Option, +} + +impl Part for TermsDto {} + + +/// 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 clientaccess](struct.ClientaccesUpdateCall.html) (request|response) +/// * [get clientaccess](struct.ClientaccesGetCall.html) (response) +/// * [insert clientaccess](struct.ClientaccesInsertCall.html) (request|response) +/// * [patch clientaccess](struct.ClientaccesPatchCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ClientAccessCapabilities { + /// no description provided + #[serde(rename="clientAccountId")] + pub client_account_id: Option, + /// no description provided + pub capabilities: Option>, +} + +impl RequestValue for ClientAccessCapabilities {} +impl ResponseResult for ClientAccessCapabilities {} + + +/// 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, Serialize, 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(rename="nextPageToken")] + pub next_page_token: Option, + /// A list of creatives. + pub items: Option>, + /// Resource type. + pub kind: Option, +} + +impl ResponseResult for CreativesList {} + + +/// 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, Serialize, Deserialize)] +pub struct AccountsList { + /// A list of accounts. + pub items: Option>, + /// Resource type. + pub kind: Option, +} + +impl ResponseResult for AccountsList {} + + +/// 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*). +/// +/// * [search marketplaceoffers](struct.MarketplaceofferSearchCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct GetOffersResponse { + /// The returned list of offers. + pub offers: Option>, +} + +impl ResponseResult for GetOffersResponse {} + + +/// 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 code for the price. + #[serde(rename="currencyCode")] + pub currency_code: Option, + /// The CPM value in micros. + #[serde(rename="amountMicros")] + pub amount_micros: Option, +} + +impl Part for Price {} + + +/// 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 ContactInformation { + /// Email address of the contact. + pub email: Option, + /// The name of the contact. + pub name: Option, +} + +impl Part for ContactInformation {} + + +/// 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 MarketplaceLabel { + /// The creation time (in ms since epoch) for the label. + #[serde(rename="createTimeMs")] + pub create_time_ms: Option, + /// Information about the party that created the label. + #[serde(rename="deprecatedMarketplaceDealParty")] + pub deprecated_marketplace_deal_party: Option, + /// The label to use. + pub label: Option, + /// The accountId of the party that created the label. + #[serde(rename="accountId")] + pub account_id: Option, +} + +impl Part for MarketplaceLabel {} + + +/// 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(rename="filteringCount")] + pub filtering_count: Option, + /// The filtering status code. Please refer to the creative-status-codes.txt file for different statuses. + #[serde(rename="filteringStatus")] + pub filtering_status: Option, +} + +impl NestedType for CreativeFilteringReasonsReasons {} +impl Part for CreativeFilteringReasonsReasons {} + + +/// 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 MoneyDto { + /// no description provided + pub micros: Option, + /// no description provided + #[serde(rename="currencyCode")] + pub currency_code: Option, +} + +impl Part for MoneyDto {} + + +/// 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 clientaccess](struct.ClientaccesListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ListClientAccessCapabilitiesResponse { + /// no description provided + #[serde(rename="clientAccessPermissions")] + pub client_access_permissions: Option>, +} + +impl ResponseResult for ListClientAccessCapabilitiesResponse {} + + +/// 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 negotiations](struct.NegotiationListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct GetNegotiationsResponse { + /// no description provided + pub kind: Option, + /// no description provided + pub negotiations: Option>, +} + +impl ResponseResult for GetNegotiationsResponse {} + + +/// 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 WebPropertyDto { + /// no description provided + #[serde(rename="enabledForPreferredDeals")] + pub enabled_for_preferred_deals: Option, + /// no description provided + pub name: Option, + /// no description provided + #[serde(rename="siteUrls")] + pub site_urls: Option>, + /// no description provided + #[serde(rename="syndicationProduct")] + pub syndication_product: Option, + /// no description provided + #[serde(rename="propertyCode")] + pub property_code: Option, + /// no description provided + #[serde(rename="allowInterestTargetedAds")] + pub allow_interest_targeted_ads: Option, + /// no description provided + pub id: Option, +} + +impl Part for WebPropertyDto {} + + +/// 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 negotiationrounds](struct.NegotiationroundInsertCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct NegotiationRoundDto { + /// no description provided + pub kind: Option, + /// The detailed terms proposed in this negotiation round. + pub terms: Option, + /// The number of this negotiation round, in sequence. + #[serde(rename="roundNumber")] + pub round_number: Option, + /// Notes regarding this negotiation round. + pub notes: Option, + /// The role, either buyer or seller, initiating this negotiation round. + #[serde(rename="originatorRole")] + pub originator_role: Option, + /// The ID of the negotiation to which this negotiation round applies. + #[serde(rename="negotiationId")] + pub negotiation_id: Option, + /// The edit history of this negotiation round. + #[serde(rename="editHistory")] + pub edit_history: Option, + /// Stores DBM partner ID for use by DBM + #[serde(rename="dbmPartnerId")] + pub dbm_partner_id: Option, + /// The action performed by this negotiation round. + pub action: Option, +} + +impl RequestValue for NegotiationRoundDto {} +impl ResponseResult for NegotiationRoundDto {} + + +/// 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 StatsDto { + /// no description provided + pub revenue: Option, + /// no description provided + pub impressions: Option, + /// no description provided + pub requests: Option, + /// no description provided + #[serde(rename="goodBids")] + pub good_bids: Option, + /// no description provided + pub bids: Option, + /// no description provided + pub spend: Option, +} + +impl Part for StatsDto {} + + +/// 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, Serialize, Deserialize)] +pub struct BillingInfo { + /// Resource type. + pub kind: Option, + /// 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(rename="billingId")] + pub billing_id: Option>, + /// Account id. + #[serde(rename="accountId")] + pub account_id: Option, + /// Account name. + #[serde(rename="accountName")] + pub account_name: Option, +} + +impl ResponseResult for BillingInfo {} + + +/// 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 Seller { + /// Optional sub-account id for the seller. + #[serde(rename="subAccountId")] + pub sub_account_id: Option, + /// The unique id for the seller. The seller fills in this field. The seller account id is then available to buyer in the offer. + #[serde(rename="accountId")] + pub account_id: Option, +} + +impl Part for Seller {} + + +/// 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 MarketplaceDealParty { + /// The buyer/seller associated with the deal. One of buyer/seller is specified for a deal-party. + pub buyer: Option, + /// The buyer/seller associated with the deal. One of buyer/seller is specified for a deal party. + pub seller: Option, +} + +impl Part for MarketplaceDealParty {} + + +/// 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*). +/// +/// * [search marketplaceorders](struct.MarketplaceorderSearchCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct GetOrdersResponse { + /// The list of matching orders. + pub orders: Option>, +} + +impl ResponseResult for GetOrdersResponse {} + + +/// 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(rename="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(rename="budgetAmount")] + pub budget_amount: Option, + /// The currency code for the buyer. This cannot be altered here. + #[serde(rename="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(rename="accountId")] + pub account_id: Option, +} + +impl RequestValue for Budget {} +impl ResponseResult for Budget {} + + +/// 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: Option, + /// Height in pixels. + pub height: Option, +} + +impl NestedType for PretargetingConfigDimensions {} +impl Part for PretargetingConfigDimensions {} + + +/// 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 deals](struct.DealGetCall.html) (response) +/// * [insert negotiations](struct.NegotiationInsertCall.html) (request|response) +/// * [get negotiations](struct.NegotiationGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct NegotiationDto { + /// The status of this negotiation. + pub status: Option, + /// The buyer party's contact email. + #[serde(rename="buyerEmailContacts")] + pub buyer_email_contacts: Option>, + /// A list of label names applicable to this negotiation. + #[serde(rename="labelNames")] + pub label_names: Option>, + /// The billed buyer; Specified by a buyer buying through an intermediary. + #[serde(rename="billedBuyer")] + pub billed_buyer: Option, + /// no description provided + pub kind: Option, + /// The ID of this negotiation's original offer. + #[serde(rename="offerId")] + pub offer_id: Option, + /// The series of negotiation rounds for this negotiation. + #[serde(rename="negotiationRounds")] + pub negotiation_rounds: Option>, + /// The unique ID of this negotiation. + #[serde(rename="negotiationId")] + pub negotiation_id: Option, + /// The state of this negotiation. + #[serde(rename="negotiationState")] + pub negotiation_state: Option, + /// Details of the buyer party in this negotiation. + pub buyer: Option, + /// The stats for this negotiation. + pub stats: Option, + /// For finalized negotiations, the ID of the finalized deal. + #[serde(rename="externalDealId")] + pub external_deal_id: Option, + /// Details of the seller party in this negotiation. + pub seller: Option, + /// The type of this deal. + #[serde(rename="dealType")] + pub deal_type: Option, + /// The seller party's contact email. + #[serde(rename="sellerEmailContacts")] + pub seller_email_contacts: Option>, +} + +impl RequestValue for NegotiationDto {} +impl ResponseResult for NegotiationDto {} + + +/// 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 offers](struct.OfferInsertCall.html) (request|response) +/// * [get offers](struct.OfferGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct OfferDto { + /// The status of this offer. + pub status: Option, + /// no description provided + pub kind: Option, + /// The list of label names applicable to this offer. + #[serde(rename="labelNames")] + pub label_names: Option>, + /// The point of contact for this offer. + #[serde(rename="pointOfContact")] + pub point_of_contact: Option, + /// Whether this offer is open. + #[serde(rename="isOpen")] + pub is_open: Option, + /// The creator of this offer. + pub creator: Option, + /// The list of buyer or seller parties this offer is closed to. + #[serde(rename="closedToDealParties")] + pub closed_to_deal_parties: Option>, + /// The billed buyer; For buyer initiated offers, buying through an intermediary. + #[serde(rename="billedBuyer")] + pub billed_buyer: Option, + /// The unique ID of this offer. + #[serde(rename="offerId")] + pub offer_id: Option, + /// The list of buyer or seller parties this offer is open to. + #[serde(rename="openToDealParties")] + pub open_to_deal_parties: Option>, + /// The state of this offer. + #[serde(rename="offerState")] + pub offer_state: Option, + /// Whether this offer is anonymous. + pub anonymous: Option, + /// The terms of this offer. + pub terms: Option, + /// The list of email contacts for this offer. + #[serde(rename="emailContacts")] + pub email_contacts: Option>, +} + +impl RequestValue for OfferDto {} +impl ResponseResult for OfferDto {} + + +/// 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 marketplacedeals](struct.MarketplacedealUpdateCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct EditAllOrderDealsRequest { + /// List of deals to edit. Service may perform 3 different operations based on comparison of deals in this list vs deals already persisted in database: 1. Add new deal to order If a deal in this list does not exist in the order, the service will create a new deal and add it to the order. Validation will follow AddOrderDealsRequest. 2. Update existing deal in the order If a deal in this list already exist in the order, the service will update that existing deal to this new deal in the request. Validation will follow UpdateOrderDealsRequest. 3. Delete deals from the order (just need the id) If a existing deal in the order is not present in this list, the service will delete that deal from the order. Validation will follow DeleteOrderDealsRequest. + pub deals: Option>, + /// The last known revision number for the order. + #[serde(rename="orderRevisionNumber")] + pub order_revision_number: Option, + /// If specified, also updates the order in the batch transaction. This is useful when the order and the deals need to be updated in one transaction. + pub order: Option, + /// Indicates an optional action to take on the order + #[serde(rename="updateAction")] + pub update_action: Option, +} + +impl RequestValue for EditAllOrderDealsRequest {} + + +/// An offer is segment of inventory that a seller wishes to sell. It is associated with certain terms and targeting information which helps buyer know more about the inventory. Each field in an order can have one of the following setting: +/// +/// (readonly) - It is an error to try and set this field. (buyer-readonly) - Only the seller can set this field. (seller-readonly) - Only the buyer can set this field. (updatable) - The field is updatable at all times by either buyer or the seller. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where 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 marketplaceoffers](struct.MarketplaceofferGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct MarketplaceOffer { + /// Optional contact information for the creator of this offer. (buyer-readonly) + #[serde(rename="creatorContacts")] + pub creator_contacts: Option>, + /// Targeting that is shared between the buyer and the seller. Each targeting criteria has a specified key and for each key there is a list of inclusion value or exclusion values. (buyer-readonly) + #[serde(rename="sharedTargetings")] + pub shared_targetings: Option>, + /// The negotiable terms of the deal (buyer-readonly) + pub terms: Option, + /// The proposed end time for the deal (ms since epoch) (buyer-readonly) + #[serde(rename="flightEndTimeMs")] + pub flight_end_time_ms: Option, + /// Optional List of labels for the offer (optional, buyer-readonly). + pub labels: Option>, + /// The unique id for the offer (readonly) + #[serde(rename="offerId")] + pub offer_id: Option, + /// Time of last update in ms. since epoch (readonly) + #[serde(rename="lastUpdateTimeMs")] + pub last_update_time_ms: Option, + /// The revision number of the offer. (readonly) + #[serde(rename="revisionNumber")] + pub revision_number: Option, + /// Identifies what kind of resource this is. Value: the fixed string "adexchangebuyer#marketplaceOffer". + pub kind: Option, + /// The name for this offer as set by the seller. (buyer-readonly) + pub name: Option, + /// The syndication product associated with the deal. (readonly, except on create) + #[serde(rename="syndicationProduct")] + pub syndication_product: Option, + /// Information about the seller that created this offer (readonly, except on create) + pub seller: Option, + /// no description provided + #[serde(rename="webPropertyCode")] + pub web_property_code: Option, + /// The state of the offer. (buyer-readonly) + pub state: Option, + /// If the creator has already signed off on the offer, then the buyer can finalize the deal by accepting the offer as is. When copying to an order, if any of the terms are changed, then auto_finalize is automatically set to false. + #[serde(rename="hasCreatorSignedOff")] + pub has_creator_signed_off: Option, + /// Inventory availability dates. (times are in ms since epoch) The granularity is generally in the order of seconds. (buyer-readonly) + #[serde(rename="flightStartTimeMs")] + pub flight_start_time_ms: Option, + /// Creation time in ms. since epoch (readonly) + #[serde(rename="creationTimeMs")] + pub creation_time_ms: Option, +} + +impl Resource for MarketplaceOffer {} +impl ResponseResult for MarketplaceOffer {} + + +/// An order can contain multiple deals. A deal contains the terms and targeting information that is used for serving. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct MarketplaceDeal { + /// The set of fields around delivery control that are interesting for a buyer to see but are non-negotiable. These are set by the publisher. This message is assigned an id of 100 since some day we would want to model this as a protobuf extension. + #[serde(rename="deliveryControl")] + pub delivery_control: Option, + /// no description provided + #[serde(rename="orderId")] + pub order_id: Option, + /// The negotiable terms of the deal. (updatable) + pub terms: Option, + /// Proposed flight end time of the deal (ms since epoch) This will generally be stored in a granularity of a second. (updatable) + #[serde(rename="flightEndTimeMs")] + pub flight_end_time_ms: Option, + /// The shared targeting visible to buyers and sellers. (updatable) + #[serde(rename="sharedTargetings")] + pub shared_targetings: Option>, + /// The offer-id from which this deal was created. (readonly, except on create) + #[serde(rename="offerId")] + pub offer_id: Option, + /// A unique deal=id for the deal (readonly). + #[serde(rename="dealId")] + pub deal_id: Option, + /// Optional Seller contact information for the deal (buyer-readonly) + #[serde(rename="sellerContacts")] + pub seller_contacts: Option>, + /// The revision number of the offer that the deal was created from (readonly, except on create) + #[serde(rename="offerRevisionNumber")] + pub offer_revision_number: Option, + /// The external deal id assigned to this deal once the deal is finalized. This is the deal-id that shows up in serving/reporting etc. (readonly) + #[serde(rename="externalDealId")] + pub external_deal_id: Option, + /// The time (ms since epoch) when the deal was last updated. (readonly) + #[serde(rename="lastUpdateTimeMs")] + pub last_update_time_ms: Option, + /// Identifies what kind of resource this is. Value: the fixed string "adexchangebuyer#marketplaceDeal". + pub kind: Option, + /// The name of the deal. (updatable) + pub name: Option, + /// Buyer private data (hidden from seller). + #[serde(rename="buyerPrivateData")] + pub buyer_private_data: Option, + /// The syndication product associated with the deal. (readonly, except on create) + #[serde(rename="syndicationProduct")] + pub syndication_product: Option, + /// no description provided + #[serde(rename="webPropertyCode")] + pub web_property_code: Option, + /// Proposed flight start time of the deal (ms since epoch) This will generally be stored in a granularity of a second. (updatable) + #[serde(rename="flightStartTimeMs")] + pub flight_start_time_ms: Option, + /// The time (ms since epoch) of the deal creation. (readonly) + #[serde(rename="creationTimeMs")] + pub creation_time_ms: Option, + /// Description for the deal terms. (updatable) + #[serde(rename="inventoryDescription")] + pub inventory_description: Option, +} + +impl Part for MarketplaceDeal {} + + +/// 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(rename="creativeType")] + pub creative_type: Option>, + /// Requests containing any of these geo criteria ids will match. + #[serde(rename="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(rename="mobileOperatingSystemVersions")] + pub mobile_operating_system_versions: Option>, + /// The config id; generated automatically. Leave this field blank for insert requests. + #[serde(rename="configId")] + pub config_id: Option, + /// Requests containing any of these users list ids will not match. + #[serde(rename="excludedUserLists")] + pub excluded_user_lists: Option>, + /// Whether this config is active. Required for all requests. + #[serde(rename="isActive")] + pub is_active: Option, + /// The name of the config. Must be unique. Required for all requests. + #[serde(rename="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(rename="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(rename="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(rename="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(rename="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(rename="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(rename="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(rename="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(rename="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(rename="mobileCarriers")] + pub mobile_carriers: Option>, + /// Requests containing any of these placements will not match. + #[serde(rename="excludedPlacements")] + pub excluded_placements: Option>, + /// Requests containing any of these placements will match. + pub placements: Option>, +} + +impl RequestValue for PretargetingConfig {} +impl ResponseResult for PretargetingConfig {} + + +/// 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 marketplaceorders](struct.MarketplaceorderInsertCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct CreateOrdersRequest { + /// no description provided + #[serde(rename="webPropertyCode")] + pub web_property_code: Option, + /// The list of orders to create. + pub orders: Option>, +} + +impl RequestValue for CreateOrdersRequest {} + + +/// 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 DeliveryControl { + /// no description provided + #[serde(rename="frequencyCaps")] + pub frequency_caps: Option>, + /// no description provided + #[serde(rename="deliveryRateType")] + pub delivery_rate_type: Option, +} + +impl Part for DeliveryControl {} + + +/// 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 AdSize { + /// no description provided + pub width: Option, + /// no description provided + pub height: Option, +} + +impl Part for AdSize {} + + +/// Used to specify pricing rules for buyers/advertisers. Each PricePerBuyer in an offer can become [0,1] deals. To check if there is a PricePerBuyer for a particular buyer or buyer/advertiser pair, we look for the most specific matching rule - we first look for a rule matching the buyer and advertiser, next a rule with the buyer but an empty advertiser list, and otherwise look for a matching rule where no buyer 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 PricePerBuyer { + /// The buyer who will pay this price. If unset, all buyers can pay this price (if the advertisers match, and there's no more specific rule matching the buyer). + pub buyer: Option, + /// The specified price + pub price: Option, +} + +impl Part for PricePerBuyer {} + + +/// 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 DeliveryControlFrequencyCap { + /// no description provided + #[serde(rename="numTimeUnits")] + pub num_time_units: Option, + /// no description provided + #[serde(rename="timeUnitType")] + pub time_unit_type: Option, + /// no description provided + #[serde(rename="maxImpressions")] + pub max_impressions: Option, +} + +impl Part for DeliveryControlFrequencyCap {} + + +/// 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 DealTermsGuaranteedFixedPriceTerms { + /// Guaranteed impressions as a percentage. This is the percentage of guaranteed looks that the buyer is guaranteeing to buy. + #[serde(rename="guaranteedImpressions")] + pub guaranteed_impressions: Option, + /// Fixed price for the specified buyer. + #[serde(rename="fixedPrices")] + pub fixed_prices: Option>, + /// Count of guaranteed looks. Required for deal, optional for offer. + #[serde(rename="guaranteedLooks")] + pub guaranteed_looks: Option, +} + +impl Part for DealTermsGuaranteedFixedPriceTerms {} + + +/// 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 EditHistoryDto { + /// no description provided + #[serde(rename="createdTimeStamp")] + pub created_time_stamp: Option, + /// no description provided + #[serde(rename="createdByLoginName")] + pub created_by_login_name: Option, + /// no description provided + #[serde(rename="lastUpdatedByLoginName")] + pub last_updated_by_login_name: Option, + /// no description provided + #[serde(rename="lastUpdateTimeStamp")] + pub last_update_time_stamp: Option, +} + +impl Part for EditHistoryDto {} + + +/// 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 RuleKeyValuePair { + /// no description provided + #[serde(rename="keyName")] + pub key_name: Option, + /// no description provided + pub value: Option, +} + +impl Part for RuleKeyValuePair {} + + +/// If nativeAd is set, HTMLSnippet and videoURL should not be 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 CreativeNativeAd { + /// A long description of the ad. + pub body: Option, + /// no description provided + pub advertiser: Option, + /// A short title for the ad. + pub headline: Option, + /// A large image. + pub image: Option, + /// The app rating in the app store. Must be in the range [0-5]. + #[serde(rename="starRating")] + pub star_rating: Option, + /// The URL to use for click tracking. + #[serde(rename="clickTrackingUrl")] + pub click_tracking_url: Option, + /// A label for the button that the user is supposed to click. + #[serde(rename="callToAction")] + pub call_to_action: Option, + /// The app icon, for app download ads. + #[serde(rename="appIcon")] + pub app_icon: Option, + /// A smaller image, for the advertiser logo. + pub logo: Option, + /// The URLs are called when the impression is rendered. + #[serde(rename="impressionTrackingUrl")] + pub impression_tracking_url: Option>, + /// The price of the promoted app including the currency info. + pub price: Option, + /// The URL to the app store to purchase/download the promoted app. + pub store: Option, +} + +impl NestedType for CreativeNativeAd {} +impl Part for CreativeNativeAd {} + + +/// 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 deals](struct.DealGetCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct GetFinalizedNegotiationByExternalDealIdRequest { + /// no description provided + #[serde(rename="includePrivateAuctions")] + pub include_private_auctions: Option, +} + +impl RequestValue for GetFinalizedNegotiationByExternalDealIdRequest {} + + +/// 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 marketplacenotes](struct.MarketplacenoteInsertCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct AddOrderNotesResponse { + /// no description provided + pub notes: Option>, +} + +impl ResponseResult for AddOrderNotesResponse {} + + +/// 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 marketplacedeals](struct.MarketplacedealInsertCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct AddOrderDealsRequest { + /// The list of deals to add + pub deals: Option>, + /// The last known order revision number. + #[serde(rename="orderRevisionNumber")] + pub order_revision_number: Option, + /// Indicates an optional action to take on the order + #[serde(rename="updateAction")] + pub update_action: Option, +} + +impl RequestValue for AddOrderDealsRequest {} + + +/// The reasons for disapproval within this restriction, if any. Note that not all disapproval reasons may be categorized, so it is possible for the creative to have a status of DISAPPROVED or CONDITIONALLY_APPROVED with an empty list for disapproval_reasons. In this case, please reach out to your TAM to help debug the issue. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct CreativeServingRestrictionsDisapprovalReasons { + /// The categorized reason for disapproval. + pub reason: Option, + /// Additional details about the reason for disapproval. + pub details: Option>, +} + +impl NestedType for CreativeServingRestrictionsDisapprovalReasons {} +impl Part for CreativeServingRestrictionsDisapprovalReasons {} + + + +// ################### +// 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_adexchangebuyer1d4 as adexchangebuyer1d4; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use adexchangebuyer1d4::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, A> + where C: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, +} + +impl<'a, C, A> MethodsBuilder for BillingInfoMethods<'a, C, A> {} + +impl<'a, C, A> BillingInfoMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Returns the billing information for one account specified by account ID. + /// + /// # Arguments + /// + /// * `accountId` - The account id. + pub fn get(&self, account_id: i32) -> BillingInfoGetCall<'a, C, 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, A> { + BillingInfoListCall { + hub: self.hub, + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *marketplacedeal* 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_adexchangebuyer1d4 as adexchangebuyer1d4; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use adexchangebuyer1d4::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(...)`, `insert(...)`, `list(...)` and `update(...)` +/// // to build up your call. +/// let rb = hub.marketplacedeals(); +/// # } +/// ``` +pub struct MarketplacedealMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, +} + +impl<'a, C, A> MethodsBuilder for MarketplacedealMethods<'a, C, A> {} + +impl<'a, C, A> MarketplacedealMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Delete the specified deals from the order + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `orderId` - The orderId to delete deals from. + pub fn delete(&self, request: DeleteOrderDealsRequest, order_id: &str) -> MarketplacedealDeleteCall<'a, C, A> { + MarketplacedealDeleteCall { + hub: self.hub, + _request: request, + _order_id: order_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Add new deals for the specified order + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `orderId` - OrderId for which deals need to be added. + pub fn insert(&self, request: AddOrderDealsRequest, order_id: &str) -> MarketplacedealInsertCall<'a, C, A> { + MarketplacedealInsertCall { + hub: self.hub, + _request: request, + _order_id: order_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Replaces all the deals in the order with the passed in deals + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `orderId` - The orderId to edit deals on. + pub fn update(&self, request: EditAllOrderDealsRequest, order_id: &str) -> MarketplacedealUpdateCall<'a, C, A> { + MarketplacedealUpdateCall { + hub: self.hub, + _request: request, + _order_id: order_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 the deals for a given order + /// + /// # Arguments + /// + /// * `orderId` - The orderId to get deals for. + pub fn list(&self, order_id: &str) -> MarketplacedealListCall<'a, C, A> { + MarketplacedealListCall { + hub: self.hub, + _order_id: order_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *marketplaceoffer* 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_adexchangebuyer1d4 as adexchangebuyer1d4; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use adexchangebuyer1d4::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 `search(...)` +/// // to build up your call. +/// let rb = hub.marketplaceoffers(); +/// # } +/// ``` +pub struct MarketplaceofferMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, +} + +impl<'a, C, A> MethodsBuilder for MarketplaceofferMethods<'a, C, A> {} + +impl<'a, C, A> MarketplaceofferMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Gets the requested negotiation. + /// + /// # Arguments + /// + /// * `offerId` - The offerId for the offer to get the head revision for. + pub fn get(&self, offer_id: &str) -> MarketplaceofferGetCall<'a, C, A> { + MarketplaceofferGetCall { + hub: self.hub, + _offer_id: offer_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 requested negotiation. + pub fn search(&self) -> MarketplaceofferSearchCall<'a, C, A> { + MarketplaceofferSearchCall { + hub: self.hub, + _pql_query: Default::default(), + _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_adexchangebuyer1d4 as adexchangebuyer1d4; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use adexchangebuyer1d4::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, A> + where C: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, +} + +impl<'a, C, A> MethodsBuilder for CreativeMethods<'a, C, A> {} + +impl<'a, C, A> CreativeMethods<'a, C, A> { + + /// 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, A> { + CreativeListCall { + hub: self.hub, + _page_token: Default::default(), + _open_auction_status_filter: Default::default(), + _max_results: Default::default(), + _deals_status_filter: 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. + /// + /// # Arguments + /// + /// * `accountId` - The id for the account that will serve this creative. + /// * `buyerCreativeId` - The buyer-specific id for this creative. + pub fn get(&self, account_id: i32, buyer_creative_id: &str) -> CreativeGetCall<'a, C, 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(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Submit a new creative. + /// + /// # Arguments + /// + /// * `request` - No description provided. + pub fn insert(&self, request: Creative) -> CreativeInsertCall<'a, C, A> { + CreativeInsertCall { + hub: self.hub, + _request: request, + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *deal* 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_adexchangebuyer1d4 as adexchangebuyer1d4; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use adexchangebuyer1d4::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(...)` +/// // to build up your call. +/// let rb = hub.deals(); +/// # } +/// ``` +pub struct DealMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, +} + +impl<'a, C, A> MethodsBuilder for DealMethods<'a, C, A> {} + +impl<'a, C, A> DealMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Gets the requested deal. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `dealId` - No description provided. + pub fn get(&self, request: GetFinalizedNegotiationByExternalDealIdRequest, deal_id: &str) -> DealGetCall<'a, C, A> { + DealGetCall { + hub: self.hub, + _request: request, + _deal_id: deal_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *offer* 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_adexchangebuyer1d4 as adexchangebuyer1d4; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use adexchangebuyer1d4::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.offers(); +/// # } +/// ``` +pub struct OfferMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, +} + +impl<'a, C, A> MethodsBuilder for OfferMethods<'a, C, A> {} + +impl<'a, C, A> OfferMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Gets the requested offer. + /// + /// # Arguments + /// + /// * `offerId` - No description provided. + pub fn get(&self, offer_id: &str) -> OfferGetCall<'a, C, A> { + OfferGetCall { + hub: self.hub, + _offer_id: offer_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 offers the authenticated user has access to. + /// + /// # Arguments + /// + /// * `request` - No description provided. + pub fn list(&self, request: ListOffersRequest) -> OfferListCall<'a, C, A> { + OfferListCall { + hub: self.hub, + _request: request, + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Creates or updates the requested offer. + /// + /// # Arguments + /// + /// * `request` - No description provided. + pub fn insert(&self, request: OfferDto) -> OfferInsertCall<'a, C, A> { + OfferInsertCall { + hub: self.hub, + _request: request, + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *clientacces* 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_adexchangebuyer1d4 as adexchangebuyer1d4; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use adexchangebuyer1d4::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.clientaccess(); +/// # } +/// ``` +pub struct ClientaccesMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, +} + +impl<'a, C, A> MethodsBuilder for ClientaccesMethods<'a, C, A> {} + +impl<'a, C, A> ClientaccesMethods<'a, C, A> { + + /// + /// # Arguments + /// + /// * `request` - No description provided. + pub fn insert(&self, request: ClientAccessCapabilities) -> ClientaccesInsertCall<'a, C, A> { + ClientaccesInsertCall { + hub: self.hub, + _request: request, + _sponsor_account_id: Default::default(), + _client_account_id: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// + /// # Arguments + /// + /// * `request` - No description provided. + pub fn list(&self, request: ListClientAccessCapabilitiesRequest) -> ClientaccesListCall<'a, C, A> { + ClientaccesListCall { + hub: self.hub, + _request: request, + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// + /// # Arguments + /// + /// * `clientAccountId` - No description provided. + /// * `sponsorAccountId` - No description provided. + pub fn get(&self, client_account_id: &str, sponsor_account_id: i32) -> ClientaccesGetCall<'a, C, A> { + ClientaccesGetCall { + hub: self.hub, + _client_account_id: client_account_id.to_string(), + _sponsor_account_id: sponsor_account_id, + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `clientAccountId` - No description provided. + /// * `sponsorAccountId` - No description provided. + pub fn patch(&self, request: ClientAccessCapabilities, client_account_id: &str, sponsor_account_id: i32) -> ClientaccesPatchCall<'a, C, A> { + ClientaccesPatchCall { + hub: self.hub, + _request: request, + _client_account_id: client_account_id.to_string(), + _sponsor_account_id: sponsor_account_id, + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// + /// # Arguments + /// + /// * `clientAccountId` - No description provided. + /// * `sponsorAccountId` - No description provided. + pub fn delete(&self, client_account_id: &str, sponsor_account_id: i32) -> ClientaccesDeleteCall<'a, C, A> { + ClientaccesDeleteCall { + hub: self.hub, + _client_account_id: client_account_id.to_string(), + _sponsor_account_id: sponsor_account_id, + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `clientAccountId` - No description provided. + /// * `sponsorAccountId` - No description provided. + pub fn update(&self, request: ClientAccessCapabilities, client_account_id: &str, sponsor_account_id: i32) -> ClientaccesUpdateCall<'a, C, A> { + ClientaccesUpdateCall { + hub: self.hub, + _request: request, + _client_account_id: client_account_id.to_string(), + _sponsor_account_id: sponsor_account_id, + _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_adexchangebuyer1d4 as adexchangebuyer1d4; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use adexchangebuyer1d4::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, A> + where C: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, +} + +impl<'a, C, A> MethodsBuilder for AccountMethods<'a, C, A> {} + +impl<'a, C, A> AccountMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing account. This method supports patch semantics. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `id` - The account id + pub fn patch(&self, request: Account, id: i32) -> AccountPatchCall<'a, C, A> { + AccountPatchCall { + hub: self.hub, + _request: request, + _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, 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. + /// + /// # Arguments + /// + /// * `id` - The account id + pub fn get(&self, id: i32) -> AccountGetCall<'a, C, A> { + AccountGetCall { + hub: self.hub, + _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. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `id` - The account id + pub fn update(&self, request: Account, id: i32) -> AccountUpdateCall<'a, C, A> { + AccountUpdateCall { + hub: self.hub, + _request: request, + _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_adexchangebuyer1d4 as adexchangebuyer1d4; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use adexchangebuyer1d4::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, A> + where C: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, +} + +impl<'a, C, A> MethodsBuilder for PerformanceReportMethods<'a, C, A> {} + +impl<'a, C, A> PerformanceReportMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the authenticated user's list of performance metrics. + /// + /// # Arguments + /// + /// * `accountId` - The account id to get the reports. + /// * `endDateTime` - The end time of the report in ISO 8601 timestamp format using UTC. + /// * `startDateTime` - The start time of the report in ISO 8601 timestamp format using UTC. + pub fn list(&self, account_id: &str, end_date_time: &str, start_date_time: &str) -> PerformanceReportListCall<'a, C, 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 *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_adexchangebuyer1d4 as adexchangebuyer1d4; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use adexchangebuyer1d4::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, A> + where C: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, +} + +impl<'a, C, A> MethodsBuilder for BudgetMethods<'a, C, A> {} + +impl<'a, C, A> BudgetMethods<'a, C, 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. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `accountId` - The account id associated with the budget being updated. + /// * `billingId` - The billing id associated with the budget being updated. + pub fn update(&self, request: Budget, account_id: &str, billing_id: &str) -> BudgetUpdateCall<'a, C, A> { + BudgetUpdateCall { + hub: self.hub, + _request: request, + _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. + /// + /// # Arguments + /// + /// * `accountId` - The account id to get the budget information for. + /// * `billingId` - The billing id to get the budget information for. + pub fn get(&self, account_id: &str, billing_id: &str) -> BudgetGetCall<'a, C, 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(), + } + } + + /// 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. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `accountId` - The account id associated with the budget being updated. + /// * `billingId` - The billing id associated with the budget being updated. + pub fn patch(&self, request: Budget, account_id: &str, billing_id: &str) -> BudgetPatchCall<'a, C, A> { + BudgetPatchCall { + hub: self.hub, + _request: request, + _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 *marketplacenote* 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_adexchangebuyer1d4 as adexchangebuyer1d4; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use adexchangebuyer1d4::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 `insert(...)` and `list(...)` +/// // to build up your call. +/// let rb = hub.marketplacenotes(); +/// # } +/// ``` +pub struct MarketplacenoteMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, +} + +impl<'a, C, A> MethodsBuilder for MarketplacenoteMethods<'a, C, A> {} + +impl<'a, C, A> MarketplacenoteMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Get all the notes associated with an order + /// + /// # Arguments + /// + /// * `orderId` - The orderId to get notes for. + pub fn list(&self, order_id: &str) -> MarketplacenoteListCall<'a, C, A> { + MarketplacenoteListCall { + hub: self.hub, + _order_id: order_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Add notes to the order + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `orderId` - The orderId to add notes for. + pub fn insert(&self, request: AddOrderNotesRequest, order_id: &str) -> MarketplacenoteInsertCall<'a, C, A> { + MarketplacenoteInsertCall { + hub: self.hub, + _request: request, + _order_id: order_id.to_string(), + _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_adexchangebuyer1d4 as adexchangebuyer1d4; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use adexchangebuyer1d4::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, A> + where C: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, +} + +impl<'a, C, A> MethodsBuilder for PretargetingConfigMethods<'a, C, A> {} + +impl<'a, C, A> PretargetingConfigMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Deletes an existing pretargeting config. + /// + /// # Arguments + /// + /// * `accountId` - The account id to delete the pretargeting config for. + /// * `configId` - The specific id of the configuration to delete. + pub fn delete(&self, account_id: &str, config_id: &str) -> PretargetingConfigDeleteCall<'a, C, 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: + /// + /// Inserts a new pretargeting configuration. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `accountId` - The account id to insert the pretargeting config for. + pub fn insert(&self, request: PretargetingConfig, account_id: &str) -> PretargetingConfigInsertCall<'a, C, A> { + PretargetingConfigInsertCall { + hub: self.hub, + _request: request, + _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. + /// + /// # Arguments + /// + /// * `accountId` - The account id to get the pretargeting configs for. + pub fn list(&self, account_id: &str) -> PretargetingConfigListCall<'a, C, 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. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `accountId` - The account id to update the pretargeting config for. + /// * `configId` - The specific id of the configuration to update. + pub fn update(&self, request: PretargetingConfig, account_id: &str, config_id: &str) -> PretargetingConfigUpdateCall<'a, C, A> { + PretargetingConfigUpdateCall { + hub: self.hub, + _request: request, + _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 + /// + /// # Arguments + /// + /// * `accountId` - The account id to get the pretargeting config for. + /// * `configId` - The specific id of the configuration to retrieve. + pub fn get(&self, account_id: &str, config_id: &str) -> PretargetingConfigGetCall<'a, C, 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: + /// + /// Updates an existing pretargeting config. This method supports patch semantics. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `accountId` - The account id to update the pretargeting config for. + /// * `configId` - The specific id of the configuration to update. + pub fn patch(&self, request: PretargetingConfig, account_id: &str, config_id: &str) -> PretargetingConfigPatchCall<'a, C, A> { + PretargetingConfigPatchCall { + hub: self.hub, + _request: request, + _account_id: account_id.to_string(), + _config_id: config_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *negotiationround* 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_adexchangebuyer1d4 as adexchangebuyer1d4; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use adexchangebuyer1d4::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 `insert(...)` +/// // to build up your call. +/// let rb = hub.negotiationrounds(); +/// # } +/// ``` +pub struct NegotiationroundMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, +} + +impl<'a, C, A> MethodsBuilder for NegotiationroundMethods<'a, C, A> {} + +impl<'a, C, A> NegotiationroundMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Adds the requested negotiationRound to the requested negotiation. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `negotiationId` - No description provided. + pub fn insert(&self, request: NegotiationRoundDto, negotiation_id: &str) -> NegotiationroundInsertCall<'a, C, A> { + NegotiationroundInsertCall { + hub: self.hub, + _request: request, + _negotiation_id: negotiation_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *negotiation* 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_adexchangebuyer1d4 as adexchangebuyer1d4; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use adexchangebuyer1d4::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.negotiations(); +/// # } +/// ``` +pub struct NegotiationMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, +} + +impl<'a, C, A> MethodsBuilder for NegotiationMethods<'a, C, A> {} + +impl<'a, C, A> NegotiationMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Lists all negotiations the authenticated user has access to. + /// + /// # Arguments + /// + /// * `request` - No description provided. + pub fn list(&self, request: GetNegotiationsRequest) -> NegotiationListCall<'a, C, A> { + NegotiationListCall { + hub: self.hub, + _request: request, + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets the requested negotiation. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `negotiationId` - No description provided. + pub fn get(&self, request: GetNegotiationByIdRequest, negotiation_id: &str) -> NegotiationGetCall<'a, C, A> { + NegotiationGetCall { + hub: self.hub, + _request: request, + _negotiation_id: negotiation_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 the requested negotiation. + /// + /// # Arguments + /// + /// * `request` - No description provided. + pub fn insert(&self, request: NegotiationDto) -> NegotiationInsertCall<'a, C, A> { + NegotiationInsertCall { + hub: self.hub, + _request: request, + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *marketplaceorder* 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_adexchangebuyer1d4 as adexchangebuyer1d4; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use adexchangebuyer1d4::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(...)`, `patch(...)`, `search(...)` and `update(...)` +/// // to build up your call. +/// let rb = hub.marketplaceorders(); +/// # } +/// ``` +pub struct MarketplaceorderMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, +} + +impl<'a, C, A> MethodsBuilder for MarketplaceorderMethods<'a, C, A> {} + +impl<'a, C, A> MarketplaceorderMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Update the given order. This method supports patch semantics. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `orderId` - The order id to update. + /// * `revisionNumber` - The last known revision number to update. If the head revision in the marketplace database has since changed, an error will be thrown. The caller should then fetch the lastest order at head revision and retry the update at that revision. + /// * `updateAction` - The proposed action to take on the order. + pub fn patch(&self, request: MarketplaceOrder, order_id: &str, revision_number: &str, update_action: &str) -> MarketplaceorderPatchCall<'a, C, A> { + MarketplaceorderPatchCall { + hub: self.hub, + _request: request, + _order_id: order_id.to_string(), + _revision_number: revision_number.to_string(), + _update_action: update_action.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Search for orders using pql query + pub fn search(&self) -> MarketplaceorderSearchCall<'a, C, A> { + MarketplaceorderSearchCall { + hub: self.hub, + _pql_query: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Update the given order + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `orderId` - The order id to update. + /// * `revisionNumber` - The last known revision number to update. If the head revision in the marketplace database has since changed, an error will be thrown. The caller should then fetch the lastest order at head revision and retry the update at that revision. + /// * `updateAction` - The proposed action to take on the order. + pub fn update(&self, request: MarketplaceOrder, order_id: &str, revision_number: &str, update_action: &str) -> MarketplaceorderUpdateCall<'a, C, A> { + MarketplaceorderUpdateCall { + hub: self.hub, + _request: request, + _order_id: order_id.to_string(), + _revision_number: revision_number.to_string(), + _update_action: update_action.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Create the given list of orders + /// + /// # Arguments + /// + /// * `request` - No description provided. + pub fn insert(&self, request: CreateOrdersRequest) -> MarketplaceorderInsertCall<'a, C, A> { + MarketplaceorderInsertCall { + hub: self.hub, + _request: request, + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Get an order given its id + /// + /// # Arguments + /// + /// * `orderId` - Id of the order to retrieve. + pub fn get(&self, order_id: &str) -> MarketplaceorderGetCall<'a, C, A> { + MarketplaceorderGetCall { + hub: self.hub, + _order_id: order_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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_adexchangebuyer1d4 as adexchangebuyer1d4; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangebuyer1d4::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(-85) +/// .doit(); +/// # } +/// ``` +pub struct BillingInfoGetCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, + _account_id: i32, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for BillingInfoGetCall<'a, C, A> {} + +impl<'a, C, A> BillingInfoGetCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.4/billinginfo/{accountId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeBuyer.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The account id. + /// + /// 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. + pub fn account_id(mut self, new_value: i32) -> BillingInfoGetCall<'a, C, A> { + self._account_id = new_value; + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> BillingInfoGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::AdexchangeBuyer`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_adexchangebuyer1d4 as adexchangebuyer1d4; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangebuyer1d4::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, A> + where C: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for BillingInfoListCall<'a, C, A> {} + +impl<'a, C, A> BillingInfoListCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.4/billinginfo".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeBuyer.as_ref().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> BillingInfoListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::AdexchangeBuyer`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Delete the specified deals from the order +/// +/// A builder for the *delete* method supported by a *marketplacedeal* resource. +/// It is not used directly, but through a `MarketplacedealMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_adexchangebuyer1d4 as adexchangebuyer1d4; +/// use adexchangebuyer1d4::DeleteOrderDealsRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangebuyer1d4::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 = DeleteOrderDealsRequest::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.marketplacedeals().delete(req, "orderId") +/// .doit(); +/// # } +/// ``` +pub struct MarketplacedealDeleteCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, + _request: DeleteOrderDealsRequest, + _order_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for MarketplacedealDeleteCall<'a, C, A> {} + +impl<'a, C, A> MarketplacedealDeleteCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, DeleteOrderDealsResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.marketplacedeals.delete", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("orderId", self._order_id.to_string())); + for &field in ["alt", "orderId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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.4/marketplaceOrders/{orderId}/deals/delete".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeBuyer.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{orderId}", "orderId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["orderId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: DeleteOrderDealsRequest) -> MarketplacedealDeleteCall<'a, C, A> { + self._request = new_value; + self + } + /// The orderId to delete deals from. + /// + /// Sets the *order id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn order_id(mut self, new_value: &str) -> MarketplacedealDeleteCall<'a, C, A> { + self._order_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> MarketplacedealDeleteCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> MarketplacedealDeleteCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::AdexchangeBuyer`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> MarketplacedealDeleteCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Add new deals for the specified order +/// +/// A builder for the *insert* method supported by a *marketplacedeal* resource. +/// It is not used directly, but through a `MarketplacedealMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_adexchangebuyer1d4 as adexchangebuyer1d4; +/// use adexchangebuyer1d4::AddOrderDealsRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangebuyer1d4::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 = AddOrderDealsRequest::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.marketplacedeals().insert(req, "orderId") +/// .doit(); +/// # } +/// ``` +pub struct MarketplacedealInsertCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, + _request: AddOrderDealsRequest, + _order_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for MarketplacedealInsertCall<'a, C, A> {} + +impl<'a, C, A> MarketplacedealInsertCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AddOrderDealsResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.marketplacedeals.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("orderId", self._order_id.to_string())); + for &field in ["alt", "orderId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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.4/marketplaceOrders/{orderId}/deals/insert".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeBuyer.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{orderId}", "orderId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["orderId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: AddOrderDealsRequest) -> MarketplacedealInsertCall<'a, C, A> { + self._request = new_value; + self + } + /// OrderId for which deals need to be added. + /// + /// Sets the *order id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn order_id(mut self, new_value: &str) -> MarketplacedealInsertCall<'a, C, A> { + self._order_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> MarketplacedealInsertCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> MarketplacedealInsertCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::AdexchangeBuyer`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> MarketplacedealInsertCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Replaces all the deals in the order with the passed in deals +/// +/// A builder for the *update* method supported by a *marketplacedeal* resource. +/// It is not used directly, but through a `MarketplacedealMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_adexchangebuyer1d4 as adexchangebuyer1d4; +/// use adexchangebuyer1d4::EditAllOrderDealsRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangebuyer1d4::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 = EditAllOrderDealsRequest::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.marketplacedeals().update(req, "orderId") +/// .doit(); +/// # } +/// ``` +pub struct MarketplacedealUpdateCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, + _request: EditAllOrderDealsRequest, + _order_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for MarketplacedealUpdateCall<'a, C, A> {} + +impl<'a, C, A> MarketplacedealUpdateCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, EditAllOrderDealsResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.marketplacedeals.update", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("orderId", self._order_id.to_string())); + for &field in ["alt", "orderId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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.4/marketplaceOrders/{orderId}/deals/update".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeBuyer.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{orderId}", "orderId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["orderId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: EditAllOrderDealsRequest) -> MarketplacedealUpdateCall<'a, C, A> { + self._request = new_value; + self + } + /// The orderId to edit deals on. + /// + /// Sets the *order id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn order_id(mut self, new_value: &str) -> MarketplacedealUpdateCall<'a, C, A> { + self._order_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> MarketplacedealUpdateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> MarketplacedealUpdateCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::AdexchangeBuyer`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> MarketplacedealUpdateCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// List all the deals for a given order +/// +/// A builder for the *list* method supported by a *marketplacedeal* resource. +/// It is not used directly, but through a `MarketplacedealMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_adexchangebuyer1d4 as adexchangebuyer1d4; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangebuyer1d4::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.marketplacedeals().list("orderId") +/// .doit(); +/// # } +/// ``` +pub struct MarketplacedealListCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, + _order_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for MarketplacedealListCall<'a, C, A> {} + +impl<'a, C, A> MarketplacedealListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, GetOrderDealsResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.marketplacedeals.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("orderId", self._order_id.to_string())); + for &field in ["alt", "orderId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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.4/marketplaceOrders/{orderId}/deals".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeBuyer.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{orderId}", "orderId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["orderId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The orderId to get deals for. + /// + /// Sets the *order id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn order_id(mut self, new_value: &str) -> MarketplacedealListCall<'a, C, A> { + self._order_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> MarketplacedealListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> MarketplacedealListCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::AdexchangeBuyer`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> MarketplacedealListCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Gets the requested negotiation. +/// +/// A builder for the *get* method supported by a *marketplaceoffer* resource. +/// It is not used directly, but through a `MarketplaceofferMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_adexchangebuyer1d4 as adexchangebuyer1d4; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangebuyer1d4::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.marketplaceoffers().get("offerId") +/// .doit(); +/// # } +/// ``` +pub struct MarketplaceofferGetCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, + _offer_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for MarketplaceofferGetCall<'a, C, A> {} + +impl<'a, C, A> MarketplaceofferGetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, MarketplaceOffer)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.marketplaceoffers.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("offerId", self._offer_id.to_string())); + for &field in ["alt", "offerId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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.4/marketplaceOffers/{offerId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeBuyer.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{offerId}", "offerId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["offerId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The offerId for the offer to get the head revision for. + /// + /// Sets the *offer id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn offer_id(mut self, new_value: &str) -> MarketplaceofferGetCall<'a, C, A> { + self._offer_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> MarketplaceofferGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> MarketplaceofferGetCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::AdexchangeBuyer`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> MarketplaceofferGetCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Gets the requested negotiation. +/// +/// A builder for the *search* method supported by a *marketplaceoffer* resource. +/// It is not used directly, but through a `MarketplaceofferMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_adexchangebuyer1d4 as adexchangebuyer1d4; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangebuyer1d4::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.marketplaceoffers().search() +/// .pql_query("amet.") +/// .doit(); +/// # } +/// ``` +pub struct MarketplaceofferSearchCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, + _pql_query: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for MarketplaceofferSearchCall<'a, C, A> {} + +impl<'a, C, A> MarketplaceofferSearchCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, GetOffersResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.marketplaceoffers.search", + 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._pql_query { + params.push(("pqlQuery", value.to_string())); + } + for &field in ["alt", "pqlQuery"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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.4/marketplaceOffers/search".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeBuyer.as_ref().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The pql query used to query for offers. + /// + /// Sets the *pql query* query property to the given value. + pub fn pql_query(mut self, new_value: &str) -> MarketplaceofferSearchCall<'a, C, A> { + self._pql_query = Some(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> MarketplaceofferSearchCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> MarketplaceofferSearchCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::AdexchangeBuyer`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> MarketplaceofferSearchCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_adexchangebuyer1d4 as adexchangebuyer1d4; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangebuyer1d4::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() +/// .page_token("erat") +/// .open_auction_status_filter("labore") +/// .max_results(92) +/// .deals_status_filter("nonumy") +/// .add_buyer_creative_id("dolores") +/// .add_account_id(-61) +/// .doit(); +/// # } +/// ``` +pub struct CreativeListCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, + _page_token: Option, + _open_auction_status_filter: Option, + _max_results: Option, + _deals_status_filter: Option, + _buyer_creative_id: Vec, + _account_id: Vec, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for CreativeListCall<'a, C, A> {} + +impl<'a, C, A> CreativeListCall<'a, C, A> where 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((8 + self._additional_params.len())); + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if let Some(value) = self._open_auction_status_filter { + params.push(("openAuctionStatusFilter", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._deals_status_filter { + params.push(("dealsStatusFilter", 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", "pageToken", "openAuctionStatusFilter", "maxResults", "dealsStatusFilter", "buyerCreativeId", "accountId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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.4/creatives".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeBuyer.as_ref().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_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. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> CreativeListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// When specified, only creatives having the given open auction status are returned. + /// + /// Sets the *open auction status filter* query property to the given value. + pub fn open_auction_status_filter(mut self, new_value: &str) -> CreativeListCall<'a, C, A> { + self._open_auction_status_filter = Some(new_value.to_string()); + self + } + /// Maximum number of entries returned on one result page. If not set, the default is 100. Optional. + /// + /// Sets the *max results* query property to the given value. + pub fn max_results(mut self, new_value: u32) -> CreativeListCall<'a, C, A> { + self._max_results = Some(new_value); + self + } + /// When specified, only creatives having the given direct deals status are returned. + /// + /// Sets the *deals status filter* query property to the given value. + pub fn deals_status_filter(mut self, new_value: &str) -> CreativeListCall<'a, C, A> { + self._deals_status_filter = Some(new_value.to_string()); + self + } + /// When specified, only creatives for the given buyer creative ids are returned. + /// + /// 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. + pub fn add_buyer_creative_id(mut self, new_value: &str) -> CreativeListCall<'a, C, A> { + self._buyer_creative_id.push(new_value.to_string()); + self + } + /// When specified, only creatives for the given account ids are returned. + /// + /// 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. + pub fn add_account_id(mut self, new_value: i32) -> CreativeListCall<'a, C, A> { + self._account_id.push(new_value); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CreativeListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::AdexchangeBuyer`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_adexchangebuyer1d4 as adexchangebuyer1d4; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangebuyer1d4::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(-95, "buyerCreativeId") +/// .doit(); +/// # } +/// ``` +pub struct CreativeGetCall<'a, C, A> + where C: '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, A> CallBuilder for CreativeGetCall<'a, C, A> {} + +impl<'a, C, A> CreativeGetCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.4/creatives/{accountId}/{buyerCreativeId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeBuyer.as_ref().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 ["buyerCreativeId", "accountId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The id for the account that will serve this creative. + /// + /// 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. + pub fn account_id(mut self, new_value: i32) -> CreativeGetCall<'a, C, A> { + self._account_id = new_value; + self + } + /// The buyer-specific id for this creative. + /// + /// 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. + pub fn buyer_creative_id(mut self, new_value: &str) -> CreativeGetCall<'a, C, A> { + self._buyer_creative_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CreativeGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::AdexchangeBuyer`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_adexchangebuyer1d4 as adexchangebuyer1d4; +/// use adexchangebuyer1d4::Creative; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangebuyer1d4::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, + _request: Creative, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for CreativeInsertCall<'a, C, A> {} + +impl<'a, C, A> CreativeInsertCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.4/creatives".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeBuyer.as_ref().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CreativeInsertCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::AdexchangeBuyer`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Gets the requested deal. +/// +/// A builder for the *get* method supported by a *deal* resource. +/// It is not used directly, but through a `DealMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_adexchangebuyer1d4 as adexchangebuyer1d4; +/// use adexchangebuyer1d4::GetFinalizedNegotiationByExternalDealIdRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangebuyer1d4::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 = GetFinalizedNegotiationByExternalDealIdRequest::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.deals().get(req, "dealId") +/// .doit(); +/// # } +/// ``` +pub struct DealGetCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, + _request: GetFinalizedNegotiationByExternalDealIdRequest, + _deal_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for DealGetCall<'a, C, A> {} + +impl<'a, C, A> DealGetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, NegotiationDto)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.deals.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("dealId", self._deal_id.to_string())); + for &field in ["alt", "dealId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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.4/deals/{dealId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeBuyer.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{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(1); + for param_name in ["dealId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: GetFinalizedNegotiationByExternalDealIdRequest) -> DealGetCall<'a, C, A> { + self._request = new_value; + 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. + pub fn deal_id(mut self, new_value: &str) -> DealGetCall<'a, C, A> { + self._deal_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DealGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> DealGetCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::AdexchangeBuyer`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DealGetCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Gets the requested offer. +/// +/// A builder for the *get* method supported by a *offer* resource. +/// It is not used directly, but through a `OfferMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_adexchangebuyer1d4 as adexchangebuyer1d4; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangebuyer1d4::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.offers().get("offerId") +/// .doit(); +/// # } +/// ``` +pub struct OfferGetCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, + _offer_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for OfferGetCall<'a, C, A> {} + +impl<'a, C, A> OfferGetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, OfferDto)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.offers.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("offerId", self._offer_id.to_string())); + for &field in ["alt", "offerId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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.4/offers/{offerId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeBuyer.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{offerId}", "offerId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["offerId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *offer id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn offer_id(mut self, new_value: &str) -> OfferGetCall<'a, C, A> { + self._offer_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> OfferGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> OfferGetCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::AdexchangeBuyer`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> OfferGetCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Lists all offers the authenticated user has access to. +/// +/// A builder for the *list* method supported by a *offer* resource. +/// It is not used directly, but through a `OfferMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_adexchangebuyer1d4 as adexchangebuyer1d4; +/// use adexchangebuyer1d4::ListOffersRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangebuyer1d4::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 = ListOffersRequest::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.offers().list(req) +/// .doit(); +/// # } +/// ``` +pub struct OfferListCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, + _request: ListOffersRequest, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for OfferListCall<'a, C, A> {} + +impl<'a, C, A> OfferListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ListOffersResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.offers.list", + http_method: hyper::method::Method::Get }); + 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.4/offers".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeBuyer.as_ref().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: ListOffersRequest) -> OfferListCall<'a, C, A> { + self._request = new_value; + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> OfferListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> OfferListCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::AdexchangeBuyer`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> OfferListCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Creates or updates the requested offer. +/// +/// A builder for the *insert* method supported by a *offer* resource. +/// It is not used directly, but through a `OfferMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_adexchangebuyer1d4 as adexchangebuyer1d4; +/// use adexchangebuyer1d4::OfferDto; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangebuyer1d4::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 = OfferDto::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.offers().insert(req) +/// .doit(); +/// # } +/// ``` +pub struct OfferInsertCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, + _request: OfferDto, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for OfferInsertCall<'a, C, A> {} + +impl<'a, C, A> OfferInsertCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, OfferDto)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.offers.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 Err(Error::FieldClash(field)); + } + } + for (name, 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.4/offers".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeBuyer.as_ref().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: OfferDto) -> OfferInsertCall<'a, C, A> { + self._request = new_value; + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> OfferInsertCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> OfferInsertCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::AdexchangeBuyer`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> OfferInsertCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// A builder for the *insert* method supported by a *clientacces* resource. +/// It is not used directly, but through a `ClientaccesMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_adexchangebuyer1d4 as adexchangebuyer1d4; +/// use adexchangebuyer1d4::ClientAccessCapabilities; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangebuyer1d4::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 = ClientAccessCapabilities::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.clientaccess().insert(req) +/// .sponsor_account_id(-21) +/// .client_account_id("justo") +/// .doit(); +/// # } +/// ``` +pub struct ClientaccesInsertCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, + _request: ClientAccessCapabilities, + _sponsor_account_id: Option, + _client_account_id: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ClientaccesInsertCall<'a, C, A> {} + +impl<'a, C, A> ClientaccesInsertCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ClientAccessCapabilities)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.clientaccess.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + if let Some(value) = self._sponsor_account_id { + params.push(("sponsorAccountId", value.to_string())); + } + if let Some(value) = self._client_account_id { + params.push(("clientAccountId", value.to_string())); + } + for &field in ["alt", "sponsorAccountId", "clientAccountId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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.4/clientAccess".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeBuyer.as_ref().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: ClientAccessCapabilities) -> ClientaccesInsertCall<'a, C, A> { + self._request = new_value; + self + } + /// + /// Sets the *sponsor account id* query property to the given value. + pub fn sponsor_account_id(mut self, new_value: i32) -> ClientaccesInsertCall<'a, C, A> { + self._sponsor_account_id = Some(new_value); + self + } + /// + /// Sets the *client account id* query property to the given value. + pub fn client_account_id(mut self, new_value: &str) -> ClientaccesInsertCall<'a, C, A> { + self._client_account_id = Some(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ClientaccesInsertCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ClientaccesInsertCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::AdexchangeBuyer`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ClientaccesInsertCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// A builder for the *list* method supported by a *clientacces* resource. +/// It is not used directly, but through a `ClientaccesMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_adexchangebuyer1d4 as adexchangebuyer1d4; +/// use adexchangebuyer1d4::ListClientAccessCapabilitiesRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangebuyer1d4::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 = ListClientAccessCapabilitiesRequest::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.clientaccess().list(req) +/// .doit(); +/// # } +/// ``` +pub struct ClientaccesListCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, + _request: ListClientAccessCapabilitiesRequest, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ClientaccesListCall<'a, C, A> {} + +impl<'a, C, A> ClientaccesListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ListClientAccessCapabilitiesResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.clientaccess.list", + http_method: hyper::method::Method::Get }); + 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.4/clientAccess".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeBuyer.as_ref().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: ListClientAccessCapabilitiesRequest) -> ClientaccesListCall<'a, C, A> { + self._request = new_value; + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ClientaccesListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ClientaccesListCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::AdexchangeBuyer`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ClientaccesListCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// A builder for the *get* method supported by a *clientacces* resource. +/// It is not used directly, but through a `ClientaccesMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_adexchangebuyer1d4 as adexchangebuyer1d4; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangebuyer1d4::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.clientaccess().get("clientAccountId", -17) +/// .doit(); +/// # } +/// ``` +pub struct ClientaccesGetCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, + _client_account_id: String, + _sponsor_account_id: i32, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ClientaccesGetCall<'a, C, A> {} + +impl<'a, C, A> ClientaccesGetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ClientAccessCapabilities)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.clientaccess.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("clientAccountId", self._client_account_id.to_string())); + params.push(("sponsorAccountId", self._sponsor_account_id.to_string())); + for &field in ["alt", "clientAccountId", "sponsorAccountId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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.4/clientAccess/{clientAccountId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeBuyer.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{clientAccountId}", "clientAccountId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["clientAccountId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *client 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. + pub fn client_account_id(mut self, new_value: &str) -> ClientaccesGetCall<'a, C, A> { + self._client_account_id = new_value.to_string(); + self + } + /// + /// Sets the *sponsor 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. + pub fn sponsor_account_id(mut self, new_value: i32) -> ClientaccesGetCall<'a, C, A> { + self._sponsor_account_id = new_value; + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ClientaccesGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ClientaccesGetCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::AdexchangeBuyer`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ClientaccesGetCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// A builder for the *patch* method supported by a *clientacces* resource. +/// It is not used directly, but through a `ClientaccesMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_adexchangebuyer1d4 as adexchangebuyer1d4; +/// use adexchangebuyer1d4::ClientAccessCapabilities; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangebuyer1d4::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 = ClientAccessCapabilities::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.clientaccess().patch(req, "clientAccountId", -55) +/// .doit(); +/// # } +/// ``` +pub struct ClientaccesPatchCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, + _request: ClientAccessCapabilities, + _client_account_id: String, + _sponsor_account_id: i32, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ClientaccesPatchCall<'a, C, A> {} + +impl<'a, C, A> ClientaccesPatchCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ClientAccessCapabilities)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.clientaccess.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("clientAccountId", self._client_account_id.to_string())); + params.push(("sponsorAccountId", self._sponsor_account_id.to_string())); + for &field in ["alt", "clientAccountId", "sponsorAccountId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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.4/clientAccess/{clientAccountId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeBuyer.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{clientAccountId}", "clientAccountId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["clientAccountId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: ClientAccessCapabilities) -> ClientaccesPatchCall<'a, C, A> { + self._request = new_value; + self + } + /// + /// Sets the *client 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. + pub fn client_account_id(mut self, new_value: &str) -> ClientaccesPatchCall<'a, C, A> { + self._client_account_id = new_value.to_string(); + self + } + /// + /// Sets the *sponsor 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. + pub fn sponsor_account_id(mut self, new_value: i32) -> ClientaccesPatchCall<'a, C, A> { + self._sponsor_account_id = new_value; + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ClientaccesPatchCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ClientaccesPatchCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::AdexchangeBuyer`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ClientaccesPatchCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// A builder for the *delete* method supported by a *clientacces* resource. +/// It is not used directly, but through a `ClientaccesMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_adexchangebuyer1d4 as adexchangebuyer1d4; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangebuyer1d4::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.clientaccess().delete("clientAccountId", -21) +/// .doit(); +/// # } +/// ``` +pub struct ClientaccesDeleteCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, + _client_account_id: String, + _sponsor_account_id: i32, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ClientaccesDeleteCall<'a, C, A> {} + +impl<'a, C, A> ClientaccesDeleteCall<'a, C, A> where 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.clientaccess.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("clientAccountId", self._client_account_id.to_string())); + params.push(("sponsorAccountId", self._sponsor_account_id.to_string())); + for &field in ["clientAccountId", "sponsorAccountId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/adexchangebuyer/v1.4/clientAccess/{clientAccountId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeBuyer.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{clientAccountId}", "clientAccountId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["clientAccountId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = res; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *client 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. + pub fn client_account_id(mut self, new_value: &str) -> ClientaccesDeleteCall<'a, C, A> { + self._client_account_id = new_value.to_string(); + self + } + /// + /// Sets the *sponsor 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. + pub fn sponsor_account_id(mut self, new_value: i32) -> ClientaccesDeleteCall<'a, C, A> { + self._sponsor_account_id = new_value; + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ClientaccesDeleteCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ClientaccesDeleteCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::AdexchangeBuyer`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ClientaccesDeleteCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// A builder for the *update* method supported by a *clientacces* resource. +/// It is not used directly, but through a `ClientaccesMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_adexchangebuyer1d4 as adexchangebuyer1d4; +/// use adexchangebuyer1d4::ClientAccessCapabilities; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangebuyer1d4::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 = ClientAccessCapabilities::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.clientaccess().update(req, "clientAccountId", -32) +/// .doit(); +/// # } +/// ``` +pub struct ClientaccesUpdateCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, + _request: ClientAccessCapabilities, + _client_account_id: String, + _sponsor_account_id: i32, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ClientaccesUpdateCall<'a, C, A> {} + +impl<'a, C, A> ClientaccesUpdateCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ClientAccessCapabilities)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.clientaccess.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("clientAccountId", self._client_account_id.to_string())); + params.push(("sponsorAccountId", self._sponsor_account_id.to_string())); + for &field in ["alt", "clientAccountId", "sponsorAccountId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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.4/clientAccess/{clientAccountId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeBuyer.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{clientAccountId}", "clientAccountId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["clientAccountId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: ClientAccessCapabilities) -> ClientaccesUpdateCall<'a, C, A> { + self._request = new_value; + self + } + /// + /// Sets the *client 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. + pub fn client_account_id(mut self, new_value: &str) -> ClientaccesUpdateCall<'a, C, A> { + self._client_account_id = new_value.to_string(); + self + } + /// + /// Sets the *sponsor 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. + pub fn sponsor_account_id(mut self, new_value: i32) -> ClientaccesUpdateCall<'a, C, A> { + self._sponsor_account_id = new_value; + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ClientaccesUpdateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ClientaccesUpdateCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::AdexchangeBuyer`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ClientaccesUpdateCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_adexchangebuyer1d4 as adexchangebuyer1d4; +/// use adexchangebuyer1d4::Account; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangebuyer1d4::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(); +/// +/// // You can configure optional parameters by calling 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, -9) +/// .doit(); +/// # } +/// ``` +pub struct AccountPatchCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, + _request: Account, + _id: i32, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for AccountPatchCall<'a, C, A> {} + +impl<'a, C, A> AccountPatchCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.4/accounts/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeBuyer.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// The account id + /// + /// 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. + pub fn id(mut self, new_value: i32) -> AccountPatchCall<'a, C, A> { + self._id = new_value; + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountPatchCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::AdexchangeBuyer`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_adexchangebuyer1d4 as adexchangebuyer1d4; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangebuyer1d4::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, A> + where C: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for AccountListCall<'a, C, A> {} + +impl<'a, C, A> AccountListCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.4/accounts".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeBuyer.as_ref().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::AdexchangeBuyer`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_adexchangebuyer1d4 as adexchangebuyer1d4; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangebuyer1d4::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(-55) +/// .doit(); +/// # } +/// ``` +pub struct AccountGetCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, + _id: i32, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for AccountGetCall<'a, C, A> {} + +impl<'a, C, A> AccountGetCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.4/accounts/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeBuyer.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The account id + /// + /// 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. + pub fn id(mut self, new_value: i32) -> AccountGetCall<'a, C, A> { + self._id = new_value; + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::AdexchangeBuyer`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_adexchangebuyer1d4 as adexchangebuyer1d4; +/// use adexchangebuyer1d4::Account; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangebuyer1d4::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(); +/// +/// // You can configure optional parameters by calling 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, -75) +/// .doit(); +/// # } +/// ``` +pub struct AccountUpdateCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, + _request: Account, + _id: i32, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for AccountUpdateCall<'a, C, A> {} + +impl<'a, C, A> AccountUpdateCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.4/accounts/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeBuyer.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// The account id + /// + /// 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. + pub fn id(mut self, new_value: i32) -> AccountUpdateCall<'a, C, A> { + self._id = new_value; + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountUpdateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::AdexchangeBuyer`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_adexchangebuyer1d4 as adexchangebuyer1d4; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangebuyer1d4::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("eirmod") +/// .max_results(58) +/// .doit(); +/// # } +/// ``` +pub struct PerformanceReportListCall<'a, C, A> + where C: '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, A> CallBuilder for PerformanceReportListCall<'a, C, A> {} + +impl<'a, C, A> PerformanceReportListCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.4/performancereport".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeBuyer.as_ref().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The account id to get the reports. + /// + /// 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. + pub fn account_id(mut self, new_value: &str) -> PerformanceReportListCall<'a, C, A> { + self._account_id = new_value.to_string(); + self + } + /// The end time of the report in ISO 8601 timestamp format using UTC. + /// + /// 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. + pub fn end_date_time(mut self, new_value: &str) -> PerformanceReportListCall<'a, C, A> { + self._end_date_time = new_value.to_string(); + self + } + /// The start time of the report in ISO 8601 timestamp format using UTC. + /// + /// 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. + pub fn start_date_time(mut self, new_value: &str) -> PerformanceReportListCall<'a, C, A> { + self._start_date_time = new_value.to_string(); + self + } + /// 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. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> PerformanceReportListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Maximum number of entries returned on one result page. If not set, the default is 100. Optional. + /// + /// Sets the *max results* query property to the given value. + pub fn max_results(mut self, new_value: u32) -> PerformanceReportListCall<'a, C, A> { + self._max_results = Some(new_value); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PerformanceReportListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::AdexchangeBuyer`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_adexchangebuyer1d4 as adexchangebuyer1d4; +/// use adexchangebuyer1d4::Budget; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangebuyer1d4::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: '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, A> CallBuilder for BudgetUpdateCall<'a, C, A> {} + +impl<'a, C, A> BudgetUpdateCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.4/billinginfo/{accountId}/{billingId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeBuyer.as_ref().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 ["billingId", "accountId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// The account id associated with the budget being updated. + /// + /// 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. + pub fn account_id(mut self, new_value: &str) -> BudgetUpdateCall<'a, C, A> { + self._account_id = new_value.to_string(); + self + } + /// The billing id associated with the budget being updated. + /// + /// 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. + pub fn billing_id(mut self, new_value: &str) -> BudgetUpdateCall<'a, C, A> { + self._billing_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> BudgetUpdateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::AdexchangeBuyer`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_adexchangebuyer1d4 as adexchangebuyer1d4; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangebuyer1d4::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, A> + where C: '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, A> CallBuilder for BudgetGetCall<'a, C, A> {} + +impl<'a, C, A> BudgetGetCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.4/billinginfo/{accountId}/{billingId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeBuyer.as_ref().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 ["billingId", "accountId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The account id to get the budget information for. + /// + /// 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. + pub fn account_id(mut self, new_value: &str) -> BudgetGetCall<'a, C, A> { + self._account_id = new_value.to_string(); + self + } + /// The billing id to get the budget information for. + /// + /// 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. + pub fn billing_id(mut self, new_value: &str) -> BudgetGetCall<'a, C, A> { + self._billing_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> BudgetGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::AdexchangeBuyer`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_adexchangebuyer1d4 as adexchangebuyer1d4; +/// use adexchangebuyer1d4::Budget; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangebuyer1d4::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: '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, A> CallBuilder for BudgetPatchCall<'a, C, A> {} + +impl<'a, C, A> BudgetPatchCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.4/billinginfo/{accountId}/{billingId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeBuyer.as_ref().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 ["billingId", "accountId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// The account id associated with the budget being updated. + /// + /// 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. + pub fn account_id(mut self, new_value: &str) -> BudgetPatchCall<'a, C, A> { + self._account_id = new_value.to_string(); + self + } + /// The billing id associated with the budget being updated. + /// + /// 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. + pub fn billing_id(mut self, new_value: &str) -> BudgetPatchCall<'a, C, A> { + self._billing_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> BudgetPatchCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::AdexchangeBuyer`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Get all the notes associated with an order +/// +/// A builder for the *list* method supported by a *marketplacenote* resource. +/// It is not used directly, but through a `MarketplacenoteMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_adexchangebuyer1d4 as adexchangebuyer1d4; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangebuyer1d4::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.marketplacenotes().list("orderId") +/// .doit(); +/// # } +/// ``` +pub struct MarketplacenoteListCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, + _order_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for MarketplacenoteListCall<'a, C, A> {} + +impl<'a, C, A> MarketplacenoteListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, GetOrderNotesResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.marketplacenotes.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("orderId", self._order_id.to_string())); + for &field in ["alt", "orderId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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.4/marketplaceOrders/{orderId}/notes".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeBuyer.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{orderId}", "orderId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["orderId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The orderId to get notes for. + /// + /// Sets the *order id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn order_id(mut self, new_value: &str) -> MarketplacenoteListCall<'a, C, A> { + self._order_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> MarketplacenoteListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> MarketplacenoteListCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::AdexchangeBuyer`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> MarketplacenoteListCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Add notes to the order +/// +/// A builder for the *insert* method supported by a *marketplacenote* resource. +/// It is not used directly, but through a `MarketplacenoteMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_adexchangebuyer1d4 as adexchangebuyer1d4; +/// use adexchangebuyer1d4::AddOrderNotesRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangebuyer1d4::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 = AddOrderNotesRequest::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.marketplacenotes().insert(req, "orderId") +/// .doit(); +/// # } +/// ``` +pub struct MarketplacenoteInsertCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, + _request: AddOrderNotesRequest, + _order_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for MarketplacenoteInsertCall<'a, C, A> {} + +impl<'a, C, A> MarketplacenoteInsertCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, AddOrderNotesResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.marketplacenotes.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("orderId", self._order_id.to_string())); + for &field in ["alt", "orderId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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.4/marketplaceOrders/{orderId}/notes/insert".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeBuyer.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{orderId}", "orderId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["orderId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: AddOrderNotesRequest) -> MarketplacenoteInsertCall<'a, C, A> { + self._request = new_value; + self + } + /// The orderId to add notes for. + /// + /// Sets the *order id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn order_id(mut self, new_value: &str) -> MarketplacenoteInsertCall<'a, C, A> { + self._order_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> MarketplacenoteInsertCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> MarketplacenoteInsertCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::AdexchangeBuyer`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> MarketplacenoteInsertCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_adexchangebuyer1d4 as adexchangebuyer1d4; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangebuyer1d4::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, A> + where C: '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, A> CallBuilder for PretargetingConfigDeleteCall<'a, C, A> {} + +impl<'a, C, A> PretargetingConfigDeleteCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/adexchangebuyer/v1.4/pretargetingconfigs/{accountId}/{configId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeBuyer.as_ref().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 ["configId", "accountId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = res; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The account id to delete the pretargeting config for. + /// + /// 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. + pub fn account_id(mut self, new_value: &str) -> PretargetingConfigDeleteCall<'a, C, A> { + self._account_id = new_value.to_string(); + self + } + /// The specific id of the configuration to delete. + /// + /// 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. + pub fn config_id(mut self, new_value: &str) -> PretargetingConfigDeleteCall<'a, C, A> { + self._config_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PretargetingConfigDeleteCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::AdexchangeBuyer`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_adexchangebuyer1d4 as adexchangebuyer1d4; +/// use adexchangebuyer1d4::PretargetingConfig; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangebuyer1d4::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, + _request: PretargetingConfig, + _account_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for PretargetingConfigInsertCall<'a, C, A> {} + +impl<'a, C, A> PretargetingConfigInsertCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.4/pretargetingconfigs/{accountId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeBuyer.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// The account id to insert the pretargeting config for. + /// + /// 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. + pub fn account_id(mut self, new_value: &str) -> PretargetingConfigInsertCall<'a, C, A> { + self._account_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PretargetingConfigInsertCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::AdexchangeBuyer`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_adexchangebuyer1d4 as adexchangebuyer1d4; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangebuyer1d4::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, A> + where C: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, + _account_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for PretargetingConfigListCall<'a, C, A> {} + +impl<'a, C, A> PretargetingConfigListCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.4/pretargetingconfigs/{accountId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeBuyer.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The account id to get the pretargeting configs for. + /// + /// 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. + pub fn account_id(mut self, new_value: &str) -> PretargetingConfigListCall<'a, C, A> { + self._account_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PretargetingConfigListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::AdexchangeBuyer`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_adexchangebuyer1d4 as adexchangebuyer1d4; +/// use adexchangebuyer1d4::PretargetingConfig; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangebuyer1d4::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: '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, A> CallBuilder for PretargetingConfigUpdateCall<'a, C, A> {} + +impl<'a, C, A> PretargetingConfigUpdateCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.4/pretargetingconfigs/{accountId}/{configId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeBuyer.as_ref().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 ["configId", "accountId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// The account id to update the pretargeting config for. + /// + /// 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. + pub fn account_id(mut self, new_value: &str) -> PretargetingConfigUpdateCall<'a, C, A> { + self._account_id = new_value.to_string(); + self + } + /// The specific id of the configuration to update. + /// + /// 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. + pub fn config_id(mut self, new_value: &str) -> PretargetingConfigUpdateCall<'a, C, A> { + self._config_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PretargetingConfigUpdateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::AdexchangeBuyer`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_adexchangebuyer1d4 as adexchangebuyer1d4; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangebuyer1d4::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, A> + where C: '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, A> CallBuilder for PretargetingConfigGetCall<'a, C, A> {} + +impl<'a, C, A> PretargetingConfigGetCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.4/pretargetingconfigs/{accountId}/{configId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeBuyer.as_ref().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 ["configId", "accountId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The account id to get the pretargeting config for. + /// + /// 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. + pub fn account_id(mut self, new_value: &str) -> PretargetingConfigGetCall<'a, C, A> { + self._account_id = new_value.to_string(); + self + } + /// The specific id of the configuration to retrieve. + /// + /// 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. + pub fn config_id(mut self, new_value: &str) -> PretargetingConfigGetCall<'a, C, A> { + self._config_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PretargetingConfigGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::AdexchangeBuyer`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_adexchangebuyer1d4 as adexchangebuyer1d4; +/// use adexchangebuyer1d4::PretargetingConfig; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangebuyer1d4::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: '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, A> CallBuilder for PretargetingConfigPatchCall<'a, C, A> {} + +impl<'a, C, A> PretargetingConfigPatchCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.4/pretargetingconfigs/{accountId}/{configId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeBuyer.as_ref().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 ["configId", "accountId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// The account id to update the pretargeting config for. + /// + /// 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. + pub fn account_id(mut self, new_value: &str) -> PretargetingConfigPatchCall<'a, C, A> { + self._account_id = new_value.to_string(); + self + } + /// The specific id of the configuration to update. + /// + /// 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. + pub fn config_id(mut self, new_value: &str) -> PretargetingConfigPatchCall<'a, C, A> { + self._config_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PretargetingConfigPatchCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::AdexchangeBuyer`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Adds the requested negotiationRound to the requested negotiation. +/// +/// A builder for the *insert* method supported by a *negotiationround* resource. +/// It is not used directly, but through a `NegotiationroundMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_adexchangebuyer1d4 as adexchangebuyer1d4; +/// use adexchangebuyer1d4::NegotiationRoundDto; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangebuyer1d4::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 = NegotiationRoundDto::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.negotiationrounds().insert(req, "negotiationId") +/// .doit(); +/// # } +/// ``` +pub struct NegotiationroundInsertCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, + _request: NegotiationRoundDto, + _negotiation_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for NegotiationroundInsertCall<'a, C, A> {} + +impl<'a, C, A> NegotiationroundInsertCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, NegotiationRoundDto)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.negotiationrounds.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("negotiationId", self._negotiation_id.to_string())); + for &field in ["alt", "negotiationId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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.4/negotiations/{negotiationId}/negotiationrounds".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeBuyer.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{negotiationId}", "negotiationId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["negotiationId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: NegotiationRoundDto) -> NegotiationroundInsertCall<'a, C, A> { + self._request = new_value; + self + } + /// + /// Sets the *negotiation id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn negotiation_id(mut self, new_value: &str) -> NegotiationroundInsertCall<'a, C, A> { + self._negotiation_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> NegotiationroundInsertCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> NegotiationroundInsertCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::AdexchangeBuyer`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> NegotiationroundInsertCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Lists all negotiations the authenticated user has access to. +/// +/// A builder for the *list* method supported by a *negotiation* resource. +/// It is not used directly, but through a `NegotiationMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_adexchangebuyer1d4 as adexchangebuyer1d4; +/// use adexchangebuyer1d4::GetNegotiationsRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangebuyer1d4::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 = GetNegotiationsRequest::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.negotiations().list(req) +/// .doit(); +/// # } +/// ``` +pub struct NegotiationListCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, + _request: GetNegotiationsRequest, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for NegotiationListCall<'a, C, A> {} + +impl<'a, C, A> NegotiationListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, GetNegotiationsResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.negotiations.list", + http_method: hyper::method::Method::Get }); + 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.4/negotiations".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeBuyer.as_ref().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: GetNegotiationsRequest) -> NegotiationListCall<'a, C, A> { + self._request = new_value; + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> NegotiationListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> NegotiationListCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::AdexchangeBuyer`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> NegotiationListCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Gets the requested negotiation. +/// +/// A builder for the *get* method supported by a *negotiation* resource. +/// It is not used directly, but through a `NegotiationMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_adexchangebuyer1d4 as adexchangebuyer1d4; +/// use adexchangebuyer1d4::GetNegotiationByIdRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangebuyer1d4::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 = GetNegotiationByIdRequest::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.negotiations().get(req, "negotiationId") +/// .doit(); +/// # } +/// ``` +pub struct NegotiationGetCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, + _request: GetNegotiationByIdRequest, + _negotiation_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for NegotiationGetCall<'a, C, A> {} + +impl<'a, C, A> NegotiationGetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, NegotiationDto)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.negotiations.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("negotiationId", self._negotiation_id.to_string())); + for &field in ["alt", "negotiationId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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.4/negotiations/{negotiationId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeBuyer.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{negotiationId}", "negotiationId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["negotiationId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: GetNegotiationByIdRequest) -> NegotiationGetCall<'a, C, A> { + self._request = new_value; + self + } + /// + /// Sets the *negotiation id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn negotiation_id(mut self, new_value: &str) -> NegotiationGetCall<'a, C, A> { + self._negotiation_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> NegotiationGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> NegotiationGetCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::AdexchangeBuyer`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> NegotiationGetCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Creates or updates the requested negotiation. +/// +/// A builder for the *insert* method supported by a *negotiation* resource. +/// It is not used directly, but through a `NegotiationMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_adexchangebuyer1d4 as adexchangebuyer1d4; +/// use adexchangebuyer1d4::NegotiationDto; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangebuyer1d4::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 = NegotiationDto::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.negotiations().insert(req) +/// .doit(); +/// # } +/// ``` +pub struct NegotiationInsertCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, + _request: NegotiationDto, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for NegotiationInsertCall<'a, C, A> {} + +impl<'a, C, A> NegotiationInsertCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, NegotiationDto)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.negotiations.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 Err(Error::FieldClash(field)); + } + } + for (name, 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.4/negotiations".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeBuyer.as_ref().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: NegotiationDto) -> NegotiationInsertCall<'a, C, A> { + self._request = new_value; + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> NegotiationInsertCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> NegotiationInsertCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::AdexchangeBuyer`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> NegotiationInsertCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Update the given order. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *marketplaceorder* resource. +/// It is not used directly, but through a `MarketplaceorderMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_adexchangebuyer1d4 as adexchangebuyer1d4; +/// use adexchangebuyer1d4::MarketplaceOrder; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangebuyer1d4::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 = MarketplaceOrder::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.marketplaceorders().patch(req, "orderId", "revisionNumber", "updateAction") +/// .doit(); +/// # } +/// ``` +pub struct MarketplaceorderPatchCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, + _request: MarketplaceOrder, + _order_id: String, + _revision_number: String, + _update_action: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for MarketplaceorderPatchCall<'a, C, A> {} + +impl<'a, C, A> MarketplaceorderPatchCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, MarketplaceOrder)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.marketplaceorders.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("orderId", self._order_id.to_string())); + params.push(("revisionNumber", self._revision_number.to_string())); + params.push(("updateAction", self._update_action.to_string())); + for &field in ["alt", "orderId", "revisionNumber", "updateAction"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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.4/marketplaceOrders/{orderId}/{revisionNumber}/{updateAction}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeBuyer.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{orderId}", "orderId"), ("{revisionNumber}", "revisionNumber"), ("{updateAction}", "updateAction")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + 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 ["updateAction", "revisionNumber", "orderId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: MarketplaceOrder) -> MarketplaceorderPatchCall<'a, C, A> { + self._request = new_value; + self + } + /// The order id to update. + /// + /// Sets the *order id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn order_id(mut self, new_value: &str) -> MarketplaceorderPatchCall<'a, C, A> { + self._order_id = new_value.to_string(); + self + } + /// The last known revision number to update. If the head revision in the marketplace database has since changed, an error will be thrown. The caller should then fetch the lastest order at head revision and retry the update at that revision. + /// + /// Sets the *revision number* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn revision_number(mut self, new_value: &str) -> MarketplaceorderPatchCall<'a, C, A> { + self._revision_number = new_value.to_string(); + self + } + /// The proposed action to take on the order. + /// + /// Sets the *update action* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn update_action(mut self, new_value: &str) -> MarketplaceorderPatchCall<'a, C, A> { + self._update_action = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> MarketplaceorderPatchCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> MarketplaceorderPatchCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::AdexchangeBuyer`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> MarketplaceorderPatchCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Search for orders using pql query +/// +/// A builder for the *search* method supported by a *marketplaceorder* resource. +/// It is not used directly, but through a `MarketplaceorderMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_adexchangebuyer1d4 as adexchangebuyer1d4; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangebuyer1d4::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.marketplaceorders().search() +/// .pql_query("dolor") +/// .doit(); +/// # } +/// ``` +pub struct MarketplaceorderSearchCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, + _pql_query: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for MarketplaceorderSearchCall<'a, C, A> {} + +impl<'a, C, A> MarketplaceorderSearchCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, GetOrdersResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.marketplaceorders.search", + 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._pql_query { + params.push(("pqlQuery", value.to_string())); + } + for &field in ["alt", "pqlQuery"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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.4/marketplaceOrders/search".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeBuyer.as_ref().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Query string to retrieve specific orders. + /// + /// Sets the *pql query* query property to the given value. + pub fn pql_query(mut self, new_value: &str) -> MarketplaceorderSearchCall<'a, C, A> { + self._pql_query = Some(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> MarketplaceorderSearchCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> MarketplaceorderSearchCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::AdexchangeBuyer`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> MarketplaceorderSearchCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Update the given order +/// +/// A builder for the *update* method supported by a *marketplaceorder* resource. +/// It is not used directly, but through a `MarketplaceorderMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_adexchangebuyer1d4 as adexchangebuyer1d4; +/// use adexchangebuyer1d4::MarketplaceOrder; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangebuyer1d4::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 = MarketplaceOrder::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.marketplaceorders().update(req, "orderId", "revisionNumber", "updateAction") +/// .doit(); +/// # } +/// ``` +pub struct MarketplaceorderUpdateCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, + _request: MarketplaceOrder, + _order_id: String, + _revision_number: String, + _update_action: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for MarketplaceorderUpdateCall<'a, C, A> {} + +impl<'a, C, A> MarketplaceorderUpdateCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, MarketplaceOrder)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.marketplaceorders.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("orderId", self._order_id.to_string())); + params.push(("revisionNumber", self._revision_number.to_string())); + params.push(("updateAction", self._update_action.to_string())); + for &field in ["alt", "orderId", "revisionNumber", "updateAction"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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.4/marketplaceOrders/{orderId}/{revisionNumber}/{updateAction}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeBuyer.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{orderId}", "orderId"), ("{revisionNumber}", "revisionNumber"), ("{updateAction}", "updateAction")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + 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 ["updateAction", "revisionNumber", "orderId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: MarketplaceOrder) -> MarketplaceorderUpdateCall<'a, C, A> { + self._request = new_value; + self + } + /// The order id to update. + /// + /// Sets the *order id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn order_id(mut self, new_value: &str) -> MarketplaceorderUpdateCall<'a, C, A> { + self._order_id = new_value.to_string(); + self + } + /// The last known revision number to update. If the head revision in the marketplace database has since changed, an error will be thrown. The caller should then fetch the lastest order at head revision and retry the update at that revision. + /// + /// Sets the *revision number* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn revision_number(mut self, new_value: &str) -> MarketplaceorderUpdateCall<'a, C, A> { + self._revision_number = new_value.to_string(); + self + } + /// The proposed action to take on the order. + /// + /// Sets the *update action* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn update_action(mut self, new_value: &str) -> MarketplaceorderUpdateCall<'a, C, A> { + self._update_action = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> MarketplaceorderUpdateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> MarketplaceorderUpdateCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::AdexchangeBuyer`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> MarketplaceorderUpdateCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Create the given list of orders +/// +/// A builder for the *insert* method supported by a *marketplaceorder* resource. +/// It is not used directly, but through a `MarketplaceorderMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_adexchangebuyer1d4 as adexchangebuyer1d4; +/// use adexchangebuyer1d4::CreateOrdersRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangebuyer1d4::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 = CreateOrdersRequest::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.marketplaceorders().insert(req) +/// .doit(); +/// # } +/// ``` +pub struct MarketplaceorderInsertCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, + _request: CreateOrdersRequest, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for MarketplaceorderInsertCall<'a, C, A> {} + +impl<'a, C, A> MarketplaceorderInsertCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, CreateOrdersResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.marketplaceorders.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 Err(Error::FieldClash(field)); + } + } + for (name, 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.4/marketplaceOrders/insert".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeBuyer.as_ref().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: CreateOrdersRequest) -> MarketplaceorderInsertCall<'a, C, A> { + self._request = new_value; + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> MarketplaceorderInsertCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> MarketplaceorderInsertCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::AdexchangeBuyer`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> MarketplaceorderInsertCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Get an order given its id +/// +/// A builder for the *get* method supported by a *marketplaceorder* resource. +/// It is not used directly, but through a `MarketplaceorderMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_adexchangebuyer1d4 as adexchangebuyer1d4; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use adexchangebuyer1d4::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.marketplaceorders().get("orderId") +/// .doit(); +/// # } +/// ``` +pub struct MarketplaceorderGetCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a AdExchangeBuyer, + _order_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for MarketplaceorderGetCall<'a, C, A> {} + +impl<'a, C, A> MarketplaceorderGetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, MarketplaceOrder)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.marketplaceorders.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("orderId", self._order_id.to_string())); + for &field in ["alt", "orderId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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.4/marketplaceOrders/{orderId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::AdexchangeBuyer.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{orderId}", "orderId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["orderId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Id of the order to retrieve. + /// + /// Sets the *order id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn order_id(mut self, new_value: &str) -> MarketplaceorderGetCall<'a, C, A> { + self._order_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> MarketplaceorderGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> MarketplaceorderGetCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::AdexchangeBuyer`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> MarketplaceorderGetCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + diff --git a/gen/adexchangeseller2-cli/Cargo.toml b/gen/adexchangeseller2-cli/Cargo.toml index 5451ba3dc5..df827a71e9 100644 --- a/gen/adexchangeseller2-cli/Cargo.toml +++ b/gen/adexchangeseller2-cli/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-adexchangeseller2-cli" -version = "0.3.2+20150719" +version = "0.3.2+20151013" 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-cli" diff --git a/gen/adexchangeseller2-cli/README.md b/gen/adexchangeseller2-cli/README.md index 90d2a94903..6656b6c3e4 100644 --- a/gen/adexchangeseller2-cli/README.md +++ b/gen/adexchangeseller2-cli/README.md @@ -24,7 +24,7 @@ Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/ma # Usage -This documentation was generated from the *Ad Exchange Seller* API at revision *20150719*. The CLI is at version *0.3.2*. +This documentation was generated from the *Ad Exchange Seller* API at revision *20151013*. The CLI is at version *0.3.2*. ```bash adexchangeseller2 [options] diff --git a/gen/adexchangeseller2-cli/mkdocs.yml b/gen/adexchangeseller2-cli/mkdocs.yml index fac63e774d..44a7d2650a 100644 --- a/gen/adexchangeseller2-cli/mkdocs.yml +++ b/gen/adexchangeseller2-cli/mkdocs.yml @@ -1,4 +1,4 @@ -site_name: Ad Exchange Seller v0.3.2+20150719 +site_name: Ad Exchange Seller v0.3.2+20151013 site_url: http://byron.github.io/google-apis-rs/google-adexchangeseller2-cli site_description: Write integrating applications with bcore diff --git a/gen/adexchangeseller2-cli/src/main.rs b/gen/adexchangeseller2-cli/src/main.rs index 6f46120b13..fb30d8b61c 100644 --- a/gen/adexchangeseller2-cli/src/main.rs +++ b/gen/adexchangeseller2-cli/src/main.rs @@ -1347,7 +1347,7 @@ fn main() { let mut app = App::new("adexchangeseller2") .author("Sebastian Thiel ") - .version("0.3.2+20150719") + .version("0.3.2+20151013") .about("Gives Ad Exchange seller users access to their inventory and the ability to generate reports") .after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_adexchangeseller2_cli") .arg(Arg::with_name("url") diff --git a/gen/adexchangeseller2/Cargo.toml b/gen/adexchangeseller2/Cargo.toml index a9e17244d9..cf3c7b48fc 100644 --- a/gen/adexchangeseller2/Cargo.toml +++ b/gen/adexchangeseller2/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-adexchangeseller2" -version = "0.1.9+20150719" +version = "0.1.9+20151013" 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" diff --git a/gen/adexchangeseller2/README.md b/gen/adexchangeseller2/README.md index 4e1d1dbf61..0a87b4a3d1 100644 --- a/gen/adexchangeseller2/README.md +++ b/gen/adexchangeseller2/README.md @@ -5,7 +5,7 @@ DO NOT EDIT ! --> 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.9+20150719*, where *20150719* is the exact revision of the *adexchangeseller:v2.0* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +This documentation was generated from *Ad Exchange Seller* crate version *0.1.9+20151013*, where *20151013* is the exact revision of the *adexchangeseller:v2.0* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. 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/). diff --git a/gen/adexchangeseller2/src/lib.rs b/gen/adexchangeseller2/src/lib.rs index 53857fc7e5..cc822e0ac7 100644 --- a/gen/adexchangeseller2/src/lib.rs +++ b/gen/adexchangeseller2/src/lib.rs @@ -2,7 +2,7 @@ // This file was generated automatically from 'src/mako/api/lib.rs.mako' // DO NOT EDIT ! -//! This documentation was generated from *Ad Exchange Seller* crate version *0.1.9+20150719*, where *20150719* is the exact revision of the *adexchangeseller:v2.0* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +//! This documentation was generated from *Ad Exchange Seller* crate version *0.1.9+20151013*, where *20151013* is the exact revision of the *adexchangeseller:v2.0* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. //! //! 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/). diff --git a/gen/admin1_directory-cli/Cargo.toml b/gen/admin1_directory-cli/Cargo.toml index 05f3cf020d..4a9401f2bb 100644 --- a/gen/admin1_directory-cli/Cargo.toml +++ b/gen/admin1_directory-cli/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-admin1_directory-cli" -version = "0.3.2+20150326" +version = "0.3.2+20151005" 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-cli" diff --git a/gen/admin1_directory-cli/README.md b/gen/admin1_directory-cli/README.md index 3f566740d9..517f9f29a5 100644 --- a/gen/admin1_directory-cli/README.md +++ b/gen/admin1_directory-cli/README.md @@ -24,7 +24,7 @@ Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/ma # Usage -This documentation was generated from the *directory* API at revision *20150326*. The CLI is at version *0.3.2*. +This documentation was generated from the *directory* API at revision *20151005*. The CLI is at version *0.3.2*. ```bash admin1-directory [options] @@ -39,6 +39,20 @@ admin1-directory [options] list [-p ]... [-o ] patch (-r )... [-p ]... [-o ] update (-r )... [-p ]... [-o ] + customers + get [-p ]... [-o ] + patch (-r )... [-p ]... [-o ] + update (-r )... [-p ]... [-o ] + domain-aliases + delete [-p ]... + get [-p ]... [-o ] + insert (-r )... [-p ]... [-o ] + list [-p ]... [-o ] + domains + delete [-p ]... + get [-p ]... [-o ] + insert (-r )... [-p ]... [-o ] + list [-p ]... [-o ] groups aliases-delete [-p ]... aliases-insert (-r )... [-p ]... [-o ] @@ -74,6 +88,20 @@ admin1-directory [options] list [-p ]... [-o ] patch ... (-r )... [-p ]... [-o ] update ... (-r )... [-p ]... [-o ] + privileges + list [-p ]... [-o ] + role-assignments + delete [-p ]... + get [-p ]... [-o ] + insert (-r )... [-p ]... [-o ] + list [-p ]... [-o ] + roles + delete [-p ]... + get [-p ]... [-o ] + insert (-r )... [-p ]... [-o ] + list [-p ]... [-o ] + patch (-r )... [-p ]... [-o ] + update (-r )... [-p ]... [-o ] schemas delete [-p ]... get [-p ]... [-o ] diff --git a/gen/admin1_directory-cli/mkdocs.yml b/gen/admin1_directory-cli/mkdocs.yml index f9899f0dac..0e330425cd 100644 --- a/gen/admin1_directory-cli/mkdocs.yml +++ b/gen/admin1_directory-cli/mkdocs.yml @@ -1,4 +1,4 @@ -site_name: directory v0.3.2+20150326 +site_name: directory v0.3.2+20151005 site_url: http://byron.github.io/google-apis-rs/google-admin1_directory-cli site_description: Write integrating applications with bcore @@ -17,6 +17,17 @@ pages: - ['chromeosdevices_list.md', 'Chromeosdevices', 'List'] - ['chromeosdevices_patch.md', 'Chromeosdevices', 'Patch'] - ['chromeosdevices_update.md', 'Chromeosdevices', 'Update'] +- ['customers_get.md', 'Customers', 'Get'] +- ['customers_patch.md', 'Customers', 'Patch'] +- ['customers_update.md', 'Customers', 'Update'] +- ['domain-aliases_delete.md', 'Domain Aliases', 'Delete'] +- ['domain-aliases_get.md', 'Domain Aliases', 'Get'] +- ['domain-aliases_insert.md', 'Domain Aliases', 'Insert'] +- ['domain-aliases_list.md', 'Domain Aliases', 'List'] +- ['domains_delete.md', 'Domains', 'Delete'] +- ['domains_get.md', 'Domains', 'Get'] +- ['domains_insert.md', 'Domains', 'Insert'] +- ['domains_list.md', 'Domains', 'List'] - ['groups_aliases-delete.md', 'Groups', 'Aliases Delete'] - ['groups_aliases-insert.md', 'Groups', 'Aliases Insert'] - ['groups_aliases-list.md', 'Groups', 'Aliases List'] @@ -47,6 +58,17 @@ pages: - ['orgunits_list.md', 'Orgunits', 'List'] - ['orgunits_patch.md', 'Orgunits', 'Patch'] - ['orgunits_update.md', 'Orgunits', 'Update'] +- ['privileges_list.md', 'Privileges', 'List'] +- ['role-assignments_delete.md', 'Role Assignments', 'Delete'] +- ['role-assignments_get.md', 'Role Assignments', 'Get'] +- ['role-assignments_insert.md', 'Role Assignments', 'Insert'] +- ['role-assignments_list.md', 'Role Assignments', 'List'] +- ['roles_delete.md', 'Roles', 'Delete'] +- ['roles_get.md', 'Roles', 'Get'] +- ['roles_insert.md', 'Roles', 'Insert'] +- ['roles_list.md', 'Roles', 'List'] +- ['roles_patch.md', 'Roles', 'Patch'] +- ['roles_update.md', 'Roles', 'Update'] - ['schemas_delete.md', 'Schemas', 'Delete'] - ['schemas_get.md', 'Schemas', 'Get'] - ['schemas_insert.md', 'Schemas', 'Insert'] diff --git a/gen/admin1_directory-cli/src/main.rs b/gen/admin1_directory-cli/src/main.rs index a925c733a0..15bb307bb7 100644 --- a/gen/admin1_directory-cli/src/main.rs +++ b/gen/admin1_directory-cli/src/main.rs @@ -630,6 +630,740 @@ impl<'n, 'a> Engine<'n, 'a> { } } + fn _customers_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.customers().get(opt.value_of("customer-key").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _customers_patch(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "customer-domain" => Some(("customerDomain", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "language" => Some(("language", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "alternate-email" => Some(("alternateEmail", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "customer-creation-time" => Some(("customerCreationTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "etag" => Some(("etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "phone-number" => Some(("phoneNumber", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "postal-address.organization-name" => Some(("postalAddress.organizationName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "postal-address.country-code" => Some(("postalAddress.countryCode", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "postal-address.locality" => Some(("postalAddress.locality", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "postal-address.region" => Some(("postalAddress.region", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "postal-address.address-line2" => Some(("postalAddress.addressLine2", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "postal-address.address-line3" => Some(("postalAddress.addressLine3", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "postal-address.contact-name" => Some(("postalAddress.contactName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "postal-address.address-line1" => Some(("postalAddress.addressLine1", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "postal-address.postal-code" => Some(("postalAddress.postalCode", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["address-line1", "address-line2", "address-line3", "alternate-email", "contact-name", "country-code", "customer-creation-time", "customer-domain", "etag", "id", "kind", "language", "locality", "organization-name", "phone-number", "postal-address", "postal-code", "region"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::Customer = json::value::from_value(object).unwrap(); + let mut call = self.hub.customers().patch(request, opt.value_of("customer-key").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _customers_update(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "customer-domain" => Some(("customerDomain", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "language" => Some(("language", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "alternate-email" => Some(("alternateEmail", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "customer-creation-time" => Some(("customerCreationTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "etag" => Some(("etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "phone-number" => Some(("phoneNumber", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "postal-address.organization-name" => Some(("postalAddress.organizationName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "postal-address.country-code" => Some(("postalAddress.countryCode", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "postal-address.locality" => Some(("postalAddress.locality", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "postal-address.region" => Some(("postalAddress.region", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "postal-address.address-line2" => Some(("postalAddress.addressLine2", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "postal-address.address-line3" => Some(("postalAddress.addressLine3", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "postal-address.contact-name" => Some(("postalAddress.contactName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "postal-address.address-line1" => Some(("postalAddress.addressLine1", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "postal-address.postal-code" => Some(("postalAddress.postalCode", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["address-line1", "address-line2", "address-line3", "alternate-email", "contact-name", "country-code", "customer-creation-time", "customer-domain", "etag", "id", "kind", "language", "locality", "organization-name", "phone-number", "postal-address", "postal-code", "region"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::Customer = json::value::from_value(object).unwrap(); + let mut call = self.hub.customers().update(request, opt.value_of("customer-key").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _domain_aliases_delete(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.domain_aliases().delete(opt.value_of("customer").unwrap_or(""), opt.value_of("domain-alias-name").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok(mut response) => { + Ok(()) + } + } + } + } + + fn _domain_aliases_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.domain_aliases().get(opt.value_of("customer").unwrap_or(""), opt.value_of("domain-alias-name").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _domain_aliases_insert(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "verified" => Some(("verified", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "creation-time" => Some(("creationTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "etag" => Some(("etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "domain-alias-name" => Some(("domainAliasName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "parent-domain-name" => Some(("parentDomainName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["creation-time", "domain-alias-name", "etag", "kind", "parent-domain-name", "verified"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::DomainAlias = json::value::from_value(object).unwrap(); + let mut call = self.hub.domain_aliases().insert(request, opt.value_of("customer").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _domain_aliases_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.domain_aliases().list(opt.value_of("customer").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "parent-domain-name" => { + call = call.parent_domain_name(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["parent-domain-name"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _domains_delete(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.domains().delete(opt.value_of("customer").unwrap_or(""), opt.value_of("domain-name").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok(mut response) => { + Ok(()) + } + } + } + } + + fn _domains_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.domains().get(opt.value_of("customer").unwrap_or(""), opt.value_of("domain-name").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _domains_insert(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "verified" => Some(("verified", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "domain-name" => Some(("domainName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "creation-time" => Some(("creationTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "etag" => Some(("etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "is-primary" => Some(("isPrimary", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["creation-time", "domain-name", "etag", "is-primary", "kind", "verified"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::Domains = json::value::from_value(object).unwrap(); + let mut call = self.hub.domains().insert(request, opt.value_of("customer").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _domains_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.domains().list(opt.value_of("customer").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + fn _groups_aliases_delete(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) -> Result<(), DoitError> { let mut call = self.hub.groups().aliases_delete(opt.value_of("group-key").unwrap_or(""), opt.value_of("alias").unwrap_or("")); @@ -2713,6 +3447,738 @@ impl<'n, 'a> Engine<'n, 'a> { } } + fn _privileges_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.privileges().list(opt.value_of("customer").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _role_assignments_delete(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.role_assignments().delete(opt.value_of("customer").unwrap_or(""), opt.value_of("role-assignment-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok(mut response) => { + Ok(()) + } + } + } + } + + fn _role_assignments_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.role_assignments().get(opt.value_of("customer").unwrap_or(""), opt.value_of("role-assignment-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _role_assignments_insert(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "role-assignment-id" => Some(("roleAssignmentId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "role-id" => Some(("roleId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "assigned-to" => Some(("assignedTo", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "etag" => Some(("etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "scope-type" => Some(("scopeType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "org-unit-id" => Some(("orgUnitId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["assigned-to", "etag", "kind", "org-unit-id", "role-assignment-id", "role-id", "scope-type"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::RoleAssignment = json::value::from_value(object).unwrap(); + let mut call = self.hub.role_assignments().insert(request, opt.value_of("customer").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _role_assignments_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.role_assignments().list(opt.value_of("customer").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "user-key" => { + call = call.user_key(value.unwrap_or("")); + }, + "role-id" => { + call = call.role_id(value.unwrap_or("")); + }, + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "max-results" => { + call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["user-key", "max-results", "page-token", "role-id"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _roles_delete(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.roles().delete(opt.value_of("customer").unwrap_or(""), opt.value_of("role-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok(mut response) => { + Ok(()) + } + } + } + } + + fn _roles_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.roles().get(opt.value_of("customer").unwrap_or(""), opt.value_of("role-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _roles_insert(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "role-id" => Some(("roleId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "role-description" => Some(("roleDescription", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "etag" => Some(("etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "is-super-admin-role" => Some(("isSuperAdminRole", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "role-name" => Some(("roleName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "is-system-role" => Some(("isSystemRole", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["etag", "is-super-admin-role", "is-system-role", "kind", "role-description", "role-id", "role-name"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::Role = json::value::from_value(object).unwrap(); + let mut call = self.hub.roles().insert(request, opt.value_of("customer").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _roles_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.roles().list(opt.value_of("customer").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "max-results" => { + call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["page-token", "max-results"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _roles_patch(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "role-id" => Some(("roleId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "role-description" => Some(("roleDescription", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "etag" => Some(("etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "is-super-admin-role" => Some(("isSuperAdminRole", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "role-name" => Some(("roleName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "is-system-role" => Some(("isSystemRole", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["etag", "is-super-admin-role", "is-system-role", "kind", "role-description", "role-id", "role-name"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::Role = json::value::from_value(object).unwrap(); + let mut call = self.hub.roles().patch(request, opt.value_of("customer").unwrap_or(""), opt.value_of("role-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _roles_update(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "role-id" => Some(("roleId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "role-description" => Some(("roleDescription", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "etag" => Some(("etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "is-super-admin-role" => Some(("isSuperAdminRole", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "role-name" => Some(("roleName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "is-system-role" => Some(("isSystemRole", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["etag", "is-super-admin-role", "is-system-role", "kind", "role-description", "role-id", "role-name"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::Role = json::value::from_value(object).unwrap(); + let mut call = self.hub.roles().update(request, opt.value_of("customer").unwrap_or(""), opt.value_of("role-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + fn _schemas_delete(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) -> Result<(), DoitError> { let mut call = self.hub.schemas().delete(opt.value_of("customer-id").unwrap_or(""), opt.value_of("schema-key").unwrap_or("")); @@ -4846,6 +6312,63 @@ impl<'n, 'a> Engine<'n, 'a> { } } }, + ("customers", Some(opt)) => { + match opt.subcommand() { + ("get", Some(opt)) => { + call_result = self._customers_get(opt, dry_run, &mut err); + }, + ("patch", Some(opt)) => { + call_result = self._customers_patch(opt, dry_run, &mut err); + }, + ("update", Some(opt)) => { + call_result = self._customers_update(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("customers".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("domain-aliases", Some(opt)) => { + match opt.subcommand() { + ("delete", Some(opt)) => { + call_result = self._domain_aliases_delete(opt, dry_run, &mut err); + }, + ("get", Some(opt)) => { + call_result = self._domain_aliases_get(opt, dry_run, &mut err); + }, + ("insert", Some(opt)) => { + call_result = self._domain_aliases_insert(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._domain_aliases_list(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("domain-aliases".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("domains", Some(opt)) => { + match opt.subcommand() { + ("delete", Some(opt)) => { + call_result = self._domains_delete(opt, dry_run, &mut err); + }, + ("get", Some(opt)) => { + call_result = self._domains_get(opt, dry_run, &mut err); + }, + ("insert", Some(opt)) => { + call_result = self._domains_insert(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._domains_list(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("domains".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, ("groups", Some(opt)) => { match opt.subcommand() { ("aliases-delete", Some(opt)) => { @@ -4976,6 +6499,63 @@ impl<'n, 'a> Engine<'n, 'a> { } } }, + ("privileges", Some(opt)) => { + match opt.subcommand() { + ("list", Some(opt)) => { + call_result = self._privileges_list(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("privileges".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("role-assignments", Some(opt)) => { + match opt.subcommand() { + ("delete", Some(opt)) => { + call_result = self._role_assignments_delete(opt, dry_run, &mut err); + }, + ("get", Some(opt)) => { + call_result = self._role_assignments_get(opt, dry_run, &mut err); + }, + ("insert", Some(opt)) => { + call_result = self._role_assignments_insert(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._role_assignments_list(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("role-assignments".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("roles", Some(opt)) => { + match opt.subcommand() { + ("delete", Some(opt)) => { + call_result = self._roles_delete(opt, dry_run, &mut err); + }, + ("get", Some(opt)) => { + call_result = self._roles_get(opt, dry_run, &mut err); + }, + ("insert", Some(opt)) => { + call_result = self._roles_insert(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._roles_list(opt, dry_run, &mut err); + }, + ("patch", Some(opt)) => { + call_result = self._roles_patch(opt, dry_run, &mut err); + }, + ("update", Some(opt)) => { + call_result = self._roles_update(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("roles".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, ("schemas", Some(opt)) => { match opt.subcommand() { ("delete", Some(opt)) => { @@ -5392,6 +6972,293 @@ fn main() { ]), ]), + ("customers", "methods: 'get', 'patch' and 'update'", vec![ + ("get", + Some(r##"Retrives a customer."##), + "Details at http://byron.github.io/google-apis-rs/google_admin1_directory_cli/customers_get", + vec![ + (Some(r##"customer-key"##), + None, + Some(r##"Id of the customer to be retrieved"##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("patch", + Some(r##"Updates a customer. This method supports patch semantics."##), + "Details at http://byron.github.io/google-apis-rs/google_admin1_directory_cli/customers_patch", + vec![ + (Some(r##"customer-key"##), + None, + Some(r##"Id of the customer to be updated"##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("update", + Some(r##"Updates a customer."##), + "Details at http://byron.github.io/google-apis-rs/google_admin1_directory_cli/customers_update", + vec![ + (Some(r##"customer-key"##), + None, + Some(r##"Id of the customer to be updated"##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("domain-aliases", "methods: 'delete', 'get', 'insert' and 'list'", vec![ + ("delete", + Some(r##"Deletes a Domain Alias of the customer."##), + "Details at http://byron.github.io/google-apis-rs/google_admin1_directory_cli/domain-aliases_delete", + vec![ + (Some(r##"customer"##), + None, + Some(r##"Immutable id of the Google Apps account."##), + Some(true), + Some(false)), + + (Some(r##"domain-alias-name"##), + None, + Some(r##"Name of domain alias to be retrieved."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + ]), + ("get", + Some(r##"Retrieves a domain alias of the customer."##), + "Details at http://byron.github.io/google-apis-rs/google_admin1_directory_cli/domain-aliases_get", + vec![ + (Some(r##"customer"##), + None, + Some(r##"Immutable id of the Google Apps account."##), + Some(true), + Some(false)), + + (Some(r##"domain-alias-name"##), + None, + Some(r##"Name of domain alias to be retrieved."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("insert", + Some(r##"Inserts a Domain alias of the customer."##), + "Details at http://byron.github.io/google-apis-rs/google_admin1_directory_cli/domain-aliases_insert", + vec![ + (Some(r##"customer"##), + None, + Some(r##"Immutable id of the Google Apps account."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Lists the domain aliases of the customer."##), + "Details at http://byron.github.io/google-apis-rs/google_admin1_directory_cli/domain-aliases_list", + vec![ + (Some(r##"customer"##), + None, + Some(r##"Immutable id of the Google Apps account."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("domains", "methods: 'delete', 'get', 'insert' and 'list'", vec![ + ("delete", + Some(r##"Deletes a domain of the customer."##), + "Details at http://byron.github.io/google-apis-rs/google_admin1_directory_cli/domains_delete", + vec![ + (Some(r##"customer"##), + None, + Some(r##"Immutable id of the Google Apps account."##), + Some(true), + Some(false)), + + (Some(r##"domain-name"##), + None, + Some(r##"Name of domain to be deleted"##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + ]), + ("get", + Some(r##"Retrives a domain of the customer."##), + "Details at http://byron.github.io/google-apis-rs/google_admin1_directory_cli/domains_get", + vec![ + (Some(r##"customer"##), + None, + Some(r##"Immutable id of the Google Apps account."##), + Some(true), + Some(false)), + + (Some(r##"domain-name"##), + None, + Some(r##"Name of domain to be retrieved"##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("insert", + Some(r##"Inserts a domain of the customer."##), + "Details at http://byron.github.io/google-apis-rs/google_admin1_directory_cli/domains_insert", + vec![ + (Some(r##"customer"##), + None, + Some(r##"Immutable id of the Google Apps account."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Lists the domains of the customer."##), + "Details at http://byron.github.io/google-apis-rs/google_admin1_directory_cli/domains_list", + vec![ + (Some(r##"customer"##), + None, + Some(r##"Immutable id of the Google Apps account."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + ("groups", "methods: 'aliases-delete', 'aliases-insert', 'aliases-list', 'delete', 'get', 'insert', 'list', 'patch' and 'update'", vec![ ("aliases-delete", Some(r##"Remove a alias for the group"##), @@ -6187,6 +8054,305 @@ fn main() { ]), ]), + ("privileges", "methods: 'list'", vec![ + ("list", + Some(r##"Retrieves a paginated list of all privileges for a customer."##), + "Details at http://byron.github.io/google-apis-rs/google_admin1_directory_cli/privileges_list", + vec![ + (Some(r##"customer"##), + None, + Some(r##"Immutable ID of the Google Apps account."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("role-assignments", "methods: 'delete', 'get', 'insert' and 'list'", vec![ + ("delete", + Some(r##"Deletes a role assignment."##), + "Details at http://byron.github.io/google-apis-rs/google_admin1_directory_cli/role-assignments_delete", + vec![ + (Some(r##"customer"##), + None, + Some(r##"Immutable ID of the Google Apps account."##), + Some(true), + Some(false)), + + (Some(r##"role-assignment-id"##), + None, + Some(r##"Immutable ID of the role assignment."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + ]), + ("get", + Some(r##"Retrieve a role assignment."##), + "Details at http://byron.github.io/google-apis-rs/google_admin1_directory_cli/role-assignments_get", + vec![ + (Some(r##"customer"##), + None, + Some(r##"Immutable ID of the Google Apps account."##), + Some(true), + Some(false)), + + (Some(r##"role-assignment-id"##), + None, + Some(r##"Immutable ID of the role assignment."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("insert", + Some(r##"Creates a role assignment."##), + "Details at http://byron.github.io/google-apis-rs/google_admin1_directory_cli/role-assignments_insert", + vec![ + (Some(r##"customer"##), + None, + Some(r##"Immutable ID of the Google Apps account."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Retrieves a paginated list of all roleAssignments."##), + "Details at http://byron.github.io/google-apis-rs/google_admin1_directory_cli/role-assignments_list", + vec![ + (Some(r##"customer"##), + None, + Some(r##"Immutable ID of the Google Apps account."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("roles", "methods: 'delete', 'get', 'insert', 'list', 'patch' and 'update'", vec![ + ("delete", + Some(r##"Deletes a role."##), + "Details at http://byron.github.io/google-apis-rs/google_admin1_directory_cli/roles_delete", + vec![ + (Some(r##"customer"##), + None, + Some(r##"Immutable ID of the Google Apps account."##), + Some(true), + Some(false)), + + (Some(r##"role-id"##), + None, + Some(r##"Immutable ID of the role."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + ]), + ("get", + Some(r##"Retrieves a role."##), + "Details at http://byron.github.io/google-apis-rs/google_admin1_directory_cli/roles_get", + vec![ + (Some(r##"customer"##), + None, + Some(r##"Immutable ID of the Google Apps account."##), + Some(true), + Some(false)), + + (Some(r##"role-id"##), + None, + Some(r##"Immutable ID of the role."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("insert", + Some(r##"Creates a role."##), + "Details at http://byron.github.io/google-apis-rs/google_admin1_directory_cli/roles_insert", + vec![ + (Some(r##"customer"##), + None, + Some(r##"Immutable ID of the Google Apps account."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Retrieves a paginated list of all the roles in a domain."##), + "Details at http://byron.github.io/google-apis-rs/google_admin1_directory_cli/roles_list", + vec![ + (Some(r##"customer"##), + None, + Some(r##"Immutable id of the Google Apps account."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("patch", + Some(r##"Updates a role. This method supports patch semantics."##), + "Details at http://byron.github.io/google-apis-rs/google_admin1_directory_cli/roles_patch", + vec![ + (Some(r##"customer"##), + None, + Some(r##"Immutable ID of the Google Apps account."##), + Some(true), + Some(false)), + + (Some(r##"role-id"##), + None, + Some(r##"Immutable ID of the role."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("update", + Some(r##"Updates a role."##), + "Details at http://byron.github.io/google-apis-rs/google_admin1_directory_cli/roles_update", + vec![ + (Some(r##"customer"##), + None, + Some(r##"Immutable ID of the Google Apps account."##), + Some(true), + Some(false)), + + (Some(r##"role-id"##), + None, + Some(r##"Immutable ID of the role."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + ("schemas", "methods: 'delete', 'get', 'insert', 'list', 'patch' and 'update'", vec![ ("delete", Some(r##"Delete schema"##), @@ -6889,7 +9055,7 @@ fn main() { let mut app = App::new("admin1-directory") .author("Sebastian Thiel ") - .version("0.3.2+20150326") + .version("0.3.2+20151005") .about("The Admin SDK Directory API lets you view and manage enterprise resources such as users and groups, administrative notifications, security features, and more.") .after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_admin1_directory_cli") .arg(Arg::with_name("url") diff --git a/gen/admin1_directory/Cargo.toml b/gen/admin1_directory/Cargo.toml index ec63d1519d..c07331ef2c 100644 --- a/gen/admin1_directory/Cargo.toml +++ b/gen/admin1_directory/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-admin1_directory" -version = "0.1.9+20150326" +version = "0.1.9+20151005" 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" diff --git a/gen/admin1_directory/README.md b/gen/admin1_directory/README.md index c20e90e2ff..046bfc9971 100644 --- a/gen/admin1_directory/README.md +++ b/gen/admin1_directory/README.md @@ -5,7 +5,7 @@ DO NOT EDIT ! --> 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.9+20150326*, where *20150326* is the exact revision of the *admin:directory_v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +This documentation was generated from *directory* crate version *0.1.9+20151005*, where *20151005* is the exact revision of the *admin:directory_v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. Everything else about the *directory* *v1_directory* API can be found at the [official documentation site](https://developers.google.com/admin-sdk/directory/). @@ -19,6 +19,12 @@ Handle the following *Resources* with ease from the central [hub](http://byron.g * [*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) +* [customers](http://byron.github.io/google-apis-rs/google_admin1_directory/struct.Customer.html) + * [*get*](http://byron.github.io/google-apis-rs/google_admin1_directory/struct.CustomerGetCall.html), [*patch*](http://byron.github.io/google-apis-rs/google_admin1_directory/struct.CustomerPatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google_admin1_directory/struct.CustomerUpdateCall.html) +* domain aliases + * [*delete*](http://byron.github.io/google-apis-rs/google_admin1_directory/struct.DomainAliaseDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google_admin1_directory/struct.DomainAliaseGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google_admin1_directory/struct.DomainAliaseInsertCall.html) and [*list*](http://byron.github.io/google-apis-rs/google_admin1_directory/struct.DomainAliaseListCall.html) +* domains + * [*delete*](http://byron.github.io/google-apis-rs/google_admin1_directory/struct.DomainDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google_admin1_directory/struct.DomainGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google_admin1_directory/struct.DomainInsertCall.html) and [*list*](http://byron.github.io/google-apis-rs/google_admin1_directory/struct.DomainListCall.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) @@ -29,6 +35,12 @@ Handle the following *Resources* with ease from the central [hub](http://byron.g * [*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) +* [privileges](http://byron.github.io/google-apis-rs/google_admin1_directory/struct.Privilege.html) + * [*list*](http://byron.github.io/google-apis-rs/google_admin1_directory/struct.PrivilegeListCall.html) +* [role assignments](http://byron.github.io/google-apis-rs/google_admin1_directory/struct.RoleAssignment.html) + * [*delete*](http://byron.github.io/google-apis-rs/google_admin1_directory/struct.RoleAssignmentDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google_admin1_directory/struct.RoleAssignmentGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google_admin1_directory/struct.RoleAssignmentInsertCall.html) and [*list*](http://byron.github.io/google-apis-rs/google_admin1_directory/struct.RoleAssignmentListCall.html) +* [roles](http://byron.github.io/google-apis-rs/google_admin1_directory/struct.Role.html) + * [*delete*](http://byron.github.io/google-apis-rs/google_admin1_directory/struct.RoleDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google_admin1_directory/struct.RoleGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google_admin1_directory/struct.RoleInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google_admin1_directory/struct.RoleListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google_admin1_directory/struct.RolePatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google_admin1_directory/struct.RoleUpdateCall.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) @@ -42,9 +54,9 @@ Handle the following *Resources* with ease from the central [hub](http://byron.g 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 users*](http://byron.github.io/google-apis-rs/google_admin1_directory/struct.UserAliaseListCall.html) * [*aliases list groups*](http://byron.github.io/google-apis-rs/google_admin1_directory/struct.GroupAliaseListCall.html) diff --git a/gen/admin1_directory/src/lib.rs b/gen/admin1_directory/src/lib.rs index dd28ba35e0..05d51e6a7a 100644 --- a/gen/admin1_directory/src/lib.rs +++ b/gen/admin1_directory/src/lib.rs @@ -2,7 +2,7 @@ // This file was generated automatically from 'src/mako/api/lib.rs.mako' // DO NOT EDIT ! -//! This documentation was generated from *directory* crate version *0.1.9+20150326*, where *20150326* is the exact revision of the *admin:directory_v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +//! This documentation was generated from *directory* crate version *0.1.9+20151005*, where *20151005* is the exact revision of the *admin:directory_v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. //! //! Everything else about the *directory* *v1_directory* API can be found at the //! [official documentation site](https://developers.google.com/admin-sdk/directory/). @@ -17,6 +17,12 @@ //! * [*stop*](struct.ChannelStopCall.html) //! * chromeosdevices //! * [*get*](struct.ChromeosdeviceGetCall.html), [*list*](struct.ChromeosdeviceListCall.html), [*patch*](struct.ChromeosdevicePatchCall.html) and [*update*](struct.ChromeosdeviceUpdateCall.html) +//! * [customers](struct.Customer.html) +//! * [*get*](struct.CustomerGetCall.html), [*patch*](struct.CustomerPatchCall.html) and [*update*](struct.CustomerUpdateCall.html) +//! * domain aliases +//! * [*delete*](struct.DomainAliaseDeleteCall.html), [*get*](struct.DomainAliaseGetCall.html), [*insert*](struct.DomainAliaseInsertCall.html) and [*list*](struct.DomainAliaseListCall.html) +//! * domains +//! * [*delete*](struct.DomainDeleteCall.html), [*get*](struct.DomainGetCall.html), [*insert*](struct.DomainInsertCall.html) and [*list*](struct.DomainListCall.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) @@ -27,6 +33,12 @@ //! * [*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) +//! * [privileges](struct.Privilege.html) +//! * [*list*](struct.PrivilegeListCall.html) +//! * [role assignments](struct.RoleAssignment.html) +//! * [*delete*](struct.RoleAssignmentDeleteCall.html), [*get*](struct.RoleAssignmentGetCall.html), [*insert*](struct.RoleAssignmentInsertCall.html) and [*list*](struct.RoleAssignmentListCall.html) +//! * [roles](struct.Role.html) +//! * [*delete*](struct.RoleDeleteCall.html), [*get*](struct.RoleGetCall.html), [*insert*](struct.RoleInsertCall.html), [*list*](struct.RoleListCall.html), [*patch*](struct.RolePatchCall.html) and [*update*](struct.RoleUpdateCall.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) @@ -40,9 +52,9 @@ //! 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 users*](struct.UserAliaseListCall.html) //! * [*aliases list groups*](struct.GroupAliaseListCall.html) //! //! @@ -146,18 +158,18 @@ //! // execute the final call using `doit()`. //! // Values shown here are possibly random and not representative ! //! let result = hub.users().watch(req) -//! .view_type("sanctus") -//! .sort_order("voluptua.") -//! .show_deleted("dolor") -//! .query("et") -//! .projection("et") -//! .page_token("vero") -//! .order_by("ut") -//! .max_results(-30) -//! .event("et") -//! .domain("ipsum") -//! .customer("justo") -//! .custom_field_mask("dolore") +//! .view_type("et") +//! .sort_order("Stet") +//! .show_deleted("sed") +//! .query("dolor") +//! .projection("sanctus") +//! .page_token("dolore") +//! .order_by("Lorem") +//! .max_results(-96) +//! .event("consetetur") +//! .domain("eirmod") +//! .customer("labore") +//! .custom_field_mask("gubergren") //! .doit(); //! //! match result { diff --git a/gen/admin1_directory/src/lib.rs.in b/gen/admin1_directory/src/lib.rs.in index c88d8f32ec..14613794ca 100644 --- a/gen/admin1_directory/src/lib.rs.in +++ b/gen/admin1_directory/src/lib.rs.in @@ -35,29 +35,38 @@ pub use cmn::{MultiPartReader, ToParts, MethodInfo, Result, Error, CallBuilder, /// [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 the provisioning of users on your domain + DirectoryUser, /// View and manage notifications received on your domain DirectoryNotification, + /// Manage data access permissions for users on your domain + DirectoryUserSecurity, + + /// Manage delegated admin roles for your domain + DirectoryRolemanagement, + /// View groups on your domain DirectoryGroupReadonly, - /// View and manage the provisioning of user schemas on your domain - DirectoryUserschema, + /// View and manage customer related information + DirectoryCustomer, + + /// View and manage the provisioning of domains for your customers + DirectoryDomain, /// View your Chrome OS devices' metadata DirectoryDeviceChromeoReadonly, + /// View domains related to your customers + DirectoryDomainReadonly, + /// View group subscriptions on your domain DirectoryGroupMemberReadonly, - /// Manage data access permissions for users on your domain - DirectoryUserSecurity, + /// View your mobile devices' metadata + DirectoryDeviceMobileReadonly, /// View organization units on your domain DirectoryOrgunitReadonly, @@ -68,8 +77,14 @@ pub enum Scope { /// View and manage your mobile devices' metadata DirectoryDeviceMobile, - /// View and manage the provisioning of users on your domain - DirectoryUser, + /// View and manage user aliases on your domain + DirectoryUserAlia, + + /// View and manage the provisioning of user schemas on your domain + DirectoryUserschema, + + /// View customer related information + DirectoryCustomerReadonly, /// Manage your mobile devices by performing administrative tasks DirectoryDeviceMobileAction, @@ -91,23 +106,31 @@ pub enum Scope { /// View and manage organization units on your domain DirectoryOrgunit, + + /// View delegated admin roles for your domain + DirectoryRolemanagementReadonly, } impl AsRef for Scope { fn as_ref(&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::DirectoryUser => "https://www.googleapis.com/auth/admin.directory.user", 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::DirectoryRolemanagement => "https://www.googleapis.com/auth/admin.directory.rolemanagement", + Scope::DirectoryGroupReadonly => "https://www.googleapis.com/auth/admin.directory.group.readonly", + Scope::DirectoryCustomer => "https://www.googleapis.com/auth/admin.directory.customer", + Scope::DirectoryDomain => "https://www.googleapis.com/auth/admin.directory.domain", + Scope::DirectoryDeviceChromeoReadonly => "https://www.googleapis.com/auth/admin.directory.device.chromeos.readonly", + Scope::DirectoryDomainReadonly => "https://www.googleapis.com/auth/admin.directory.domain.readonly", + Scope::DirectoryGroupMemberReadonly => "https://www.googleapis.com/auth/admin.directory.group.member.readonly", + Scope::DirectoryDeviceMobileReadonly => "https://www.googleapis.com/auth/admin.directory.device.mobile.readonly", 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::DirectoryUserAlia => "https://www.googleapis.com/auth/admin.directory.user.alias", + Scope::DirectoryUserschema => "https://www.googleapis.com/auth/admin.directory.userschema", + Scope::DirectoryCustomerReadonly => "https://www.googleapis.com/auth/admin.directory.customer.readonly", 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", @@ -115,13 +138,14 @@ impl AsRef for Scope { 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", + Scope::DirectoryRolemanagementReadonly => "https://www.googleapis.com/auth/admin.directory.rolemanagement.readonly", } } } impl Default for Scope { fn default() -> Scope { - Scope::DirectoryDeviceMobileReadonly + Scope::DirectoryGroupReadonly } } @@ -229,6 +253,15 @@ impl<'a, C, A> Directory pub fn chromeosdevices(&'a self) -> ChromeosdeviceMethods<'a, C, A> { ChromeosdeviceMethods { hub: &self } } + pub fn customers(&'a self) -> CustomerMethods<'a, C, A> { + CustomerMethods { hub: &self } + } + pub fn domain_aliases(&'a self) -> DomainAliaseMethods<'a, C, A> { + DomainAliaseMethods { hub: &self } + } + pub fn domains(&'a self) -> DomainMethods<'a, C, A> { + DomainMethods { hub: &self } + } pub fn groups(&'a self) -> GroupMethods<'a, C, A> { GroupMethods { hub: &self } } @@ -244,6 +277,15 @@ impl<'a, C, A> Directory pub fn orgunits(&'a self) -> OrgunitMethods<'a, C, A> { OrgunitMethods { hub: &self } } + pub fn privileges(&'a self) -> PrivilegeMethods<'a, C, A> { + PrivilegeMethods { hub: &self } + } + pub fn role_assignments(&'a self) -> RoleAssignmentMethods<'a, C, A> { + RoleAssignmentMethods { hub: &self } + } + pub fn roles(&'a self) -> RoleMethods<'a, C, A> { + RoleMethods { hub: &self } + } pub fn schemas(&'a self) -> SchemaMethods<'a, C, A> { SchemaMethods { hub: &self } } @@ -292,6 +334,49 @@ pub struct UserName { impl Part for UserName {} +/// The set of privileges that are granted to this role. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct RoleRolePrivileges { + /// The obfuscated ID of the service this privilege is for. + #[serde(rename="serviceId")] + pub service_id: Option, + /// The name of the privilege. + #[serde(rename="privilegeName")] + pub privilege_name: Option, +} + +impl NestedType for RoleRolePrivileges {} +impl Part for RoleRolePrivileges {} + + +/// JSON response template for List roleAssignments 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 role assignments](struct.RoleAssignmentListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct RoleAssignments { + /// no description provided + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// A list of RoleAssignment resources. + pub items: Option>, + /// The type of the API resource. This is always admin#directory#roleAssignments. + pub kind: Option, + /// ETag of the resource. + pub etag: Option, +} + +impl ResponseResult for RoleAssignments {} + + /// JSON template for Group resource in Directory API. /// /// # Activities @@ -383,39 +468,26 @@ impl Resource for Notification {} impl ResponseResult for Notification {} -/// JSON template for FieldSpec resource for Schemas in Directory API. +/// JSON response template for List privileges operation in Directory API. /// -/// This type is not used in any activity, and only used as *part* of another schema. +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where 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 privileges](struct.PrivilegeListCall.html) (response) /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] -pub struct SchemaFieldSpec { - /// Kind of resource this is. +pub struct Privileges { + /// A list of Privilege resources. + pub items: Option>, + /// The type of the API resource. This is always admin#directory#privileges. pub kind: Option, /// ETag of the resource. pub etag: Option, - /// Read ACLs on the field specifying who can view values of this field. Valid values are "ALL_DOMAIN_USERS" and "ADMINS_AND_SELF". - #[serde(rename="readAccessType")] - pub read_access_type: Option, - /// Type of the field. - #[serde(rename="fieldType")] - pub field_type: Option, - /// Boolean specifying whether the field is indexed or not. - pub indexed: Option, - /// Name of the field. - #[serde(rename="fieldName")] - pub field_name: Option, - /// 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(rename="numericIndexingSpec")] - pub numeric_indexing_spec: Option, - /// Unique identifier of Field (Read-only) - #[serde(rename="fieldId")] - pub field_id: Option, - /// Boolean specifying whether this is a multi-valued field or not. - #[serde(rename="multiValued")] - pub multi_valued: Option, } -impl Part for SchemaFieldSpec {} +impl ResponseResult for Privileges {} /// JSON template for Member resource in Directory API. @@ -454,6 +526,24 @@ impl Resource for Member {} impl ResponseResult for Member {} +/// 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, Deserialize)] +pub struct MobileDeviceAction { + /// Action to be taken on the Mobile Device + pub action: Option, +} + +impl RequestValue for MobileDeviceAction {} + + /// JSON response template for List Organization Units operation in Directory API. /// /// # Activities @@ -477,43 +567,49 @@ pub struct OrgUnits { impl ResponseResult for OrgUnits {} -/// JSON template for token resource in Directory API. +/// JSON template for role 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) +/// * [update roles](struct.RoleUpdateCall.html) (request|response) +/// * [insert roles](struct.RoleInsertCall.html) (request|response) +/// * [get roles](struct.RoleGetCall.html) (response) +/// * [patch roles](struct.RolePatchCall.html) (request|response) +/// * [list roles](struct.RoleListCall.html) (none) +/// * [delete roles](struct.RoleDeleteCall.html) (none) /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] -pub struct Token { - /// A list of authorization scopes the application is granted. - pub scopes: Option>, - /// The type of the API resource. This is always admin#directory#token. +pub struct Role { + /// The type of the API resource. This is always admin#directory#role. pub kind: Option, - /// The Client ID of the application the token is issued to. - #[serde(rename="clientId")] - pub client_id: Option, - /// 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(rename="nativeApp")] - pub native_app: Option, - /// The displayable name of the application the token is issued to. - #[serde(rename="displayText")] - pub display_text: Option, + /// ID of the role. + #[serde(rename="roleId")] + pub role_id: Option, + /// A short description of the role. + #[serde(rename="roleDescription")] + pub role_description: Option, /// ETag of the resource. pub etag: Option, - /// Whether the application is registered with Google. The value is true if the application has an anonymous Client ID. - pub anonymous: Option, - /// The unique ID of the user that issued the token. - #[serde(rename="userKey")] - pub user_key: Option, + /// Returns true if the role is a super admin role. + #[serde(rename="isSuperAdminRole")] + pub is_super_admin_role: Option, + /// Name of the role. + #[serde(rename="roleName")] + pub role_name: Option, + /// Returns true if this is a pre-defined system role. + #[serde(rename="isSystemRole")] + pub is_system_role: Option, + /// The set of privileges that are granted to this role. + #[serde(rename="rolePrivileges")] + pub role_privileges: Option>, } -impl Resource for Token {} -impl ResponseResult for Token {} +impl RequestValue for Role {} +impl Resource for Role {} +impl ResponseResult for Role {} /// There is no detailed description. @@ -538,6 +634,77 @@ pub struct Asps { impl ResponseResult for Asps {} +/// JSON template for privilege 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 privileges](struct.PrivilegeListCall.html) (none) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Privilege { + /// The type of the API resource. This is always admin#directory#privilege. + pub kind: Option, + /// The obfuscated ID of the service this privilege is for. + #[serde(rename="serviceId")] + pub service_id: Option, + /// The name of the privilege. + #[serde(rename="privilegeName")] + pub privilege_name: Option, + /// ETag of the resource. + pub etag: Option, + /// The name of the service this privilege is for. + #[serde(rename="serviceName")] + pub service_name: Option, + /// A list of child privileges. Privileges for a service form a tree. Each privilege can have a list of child privileges; this list is empty for a leaf privilege. + #[serde(rename="childPrivileges")] + pub child_privileges: Option>, + /// If the privilege can be restricted to an organization unit. + #[serde(rename="isOuScopable")] + pub is_ou_scopable: Option, +} + +impl Resource for Privilege {} + + +/// JSON template for postal address of a customer. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct CustomerPostalAddress { + /// The company or company division name. + #[serde(rename="organizationName")] + pub organization_name: Option, + /// This is a required property. For countryCode information see the ISO 3166 country code elements. + #[serde(rename="countryCode")] + pub country_code: Option, + /// Name of the locality. An example of a locality value is the city of San Francisco. + pub locality: Option, + /// Name of the region. An example of a region value is NY for the state of New York. + pub region: Option, + /// Address line 2 of the address. + #[serde(rename="addressLine2")] + pub address_line2: Option, + /// Address line 3 of the address. + #[serde(rename="addressLine3")] + pub address_line3: Option, + /// The customer contact's name. + #[serde(rename="contactName")] + pub contact_name: Option, + /// A customer's physical address. The address can be composed of one to three lines. + #[serde(rename="addressLine1")] + pub address_line1: Option, + /// The postal code. A postalCode example is a postal zip code such as 10009. This is in accordance with - http://portablecontacts.net/draft-spec.html#address_element. + #[serde(rename="postalCode")] + pub postal_code: Option, +} + +impl Part for CustomerPostalAddress {} + + /// An notification channel used to watch for resource changes. /// /// # Activities @@ -653,6 +820,48 @@ impl Resource for Asp {} impl ResponseResult for Asp {} +/// JSON template for roleAssignment 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*). +/// +/// * [insert role assignments](struct.RoleAssignmentInsertCall.html) (request|response) +/// * [list role assignments](struct.RoleAssignmentListCall.html) (none) +/// * [delete role assignments](struct.RoleAssignmentDeleteCall.html) (none) +/// * [get role assignments](struct.RoleAssignmentGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct RoleAssignment { + /// The unique ID of the user this role is assigned to. + #[serde(rename="assignedTo")] + pub assigned_to: Option, + /// The type of the API resource. This is always admin#directory#roleAssignment. + pub kind: Option, + /// ETag of the resource. + pub etag: Option, + /// ID of this roleAssignment. + #[serde(rename="roleAssignmentId")] + pub role_assignment_id: Option, + /// The ID of the role that is assigned. + #[serde(rename="roleId")] + pub role_id: Option, + /// The scope in which this role is assigned. Possible values are: + /// - CUSTOMER + /// - ORG_UNIT + #[serde(rename="scopeType")] + pub scope_type: Option, + /// If the role is restricted to an organization unit, this contains the ID for the organization unit the exercise of this role is restricted to. + #[serde(rename="orgUnitId")] + pub org_unit_id: Option, +} + +impl RequestValue for RoleAssignment {} +impl Resource for RoleAssignment {} +impl ResponseResult for RoleAssignment {} + + /// JSON response template for List tokens operation in Directory API. /// /// # Activities @@ -703,6 +912,39 @@ pub struct Notifications { impl ResponseResult for Notifications {} +/// JSON template for Domain 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*). +/// +/// * [get domain aliases](struct.DomainAliaseGetCall.html) (response) +/// * [insert domain aliases](struct.DomainAliaseInsertCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct DomainAlias { + /// Kind of resource this is. + pub kind: Option, + /// ETag of the resource. + pub etag: Option, + /// Indicates the verification state of a domain alias. (Read-only) + pub verified: Option, + /// The domain alias name. + #[serde(rename="domainAliasName")] + pub domain_alias_name: Option, + /// The creation time of the domain alias. (Read-only). + #[serde(rename="creationTime")] + pub creation_time: Option, + /// The parent domain name that the domain alias is associated with. This can either be a primary or secondary domain name within a customer. + #[serde(rename="parentDomainName")] + pub parent_domain_name: Option, +} + +impl RequestValue for DomainAlias {} +impl ResponseResult for DomainAlias {} + + /// JSON template for Chrome Os Device resource in Directory API. /// /// # Activities @@ -958,40 +1200,29 @@ impl NestedType for ChromeOsDeviceRecentUsers {} impl Part for ChromeOsDeviceRecentUsers {} -/// List of applications installed on Mobile Device +/// JSON response template for List Mobile Devices operation in Directory API. /// -/// This type is not used in any activity, and only used as *part* of another schema. +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where 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, Serialize, Deserialize)] -pub struct MobileDeviceApplications { - /// Version code of application - #[serde(rename="versionCode")] - pub version_code: Option, - /// Package name of application - #[serde(rename="packageName")] - pub package_name: Option, - /// Display name of application - #[serde(rename="displayName")] - pub display_name: Option, - /// Version name of application - #[serde(rename="versionName")] - pub version_name: Option, - /// List of Permissions for application - pub permission: Option>, +pub struct MobileDevices { + /// Token used to access next page of this result. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// Kind of resource this is. + pub kind: Option, + /// ETag of the resource. + pub etag: Option, + /// List of Mobile Device objects. + pub mobiledevices: Option>, } -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(Option>); - -impl Part for UserCustomProperties {} +impl ResponseResult for MobileDevices {} /// JSON response template for List Members operation in Directory API. @@ -1019,6 +1250,119 @@ pub struct Members { impl ResponseResult for Members {} +/// JSON template for Customer Resource 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*). +/// +/// * [patch customers](struct.CustomerPatchCall.html) (request|response) +/// * [update customers](struct.CustomerUpdateCall.html) (request|response) +/// * [get customers](struct.CustomerGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Customer { + /// The customer's primary domain name string. Do not include the www prefix when creating a new customer. + #[serde(rename="customerDomain")] + pub customer_domain: Option, + /// The customer's ISO 639-2 language code. The default value is en-US + pub language: Option, + /// The customer's secondary contact email address. This email address cannot be on the same domain as the customerDomain + #[serde(rename="alternateEmail")] + pub alternate_email: Option, + /// The customer's creation time (Readonly) + #[serde(rename="customerCreationTime")] + pub customer_creation_time: Option, + /// Identifies the resource as a customer. Value: admin#directory#customer + pub kind: Option, + /// ETag of the resource. + pub etag: Option, + /// The customer's contact phone number in E.164 format. + #[serde(rename="phoneNumber")] + pub phone_number: Option, + /// The customer's postal address information. + #[serde(rename="postalAddress")] + pub postal_address: Option, + /// The unique ID for the customer's Google account. (Readonly) + pub id: Option, +} + +impl RequestValue for Customer {} +impl Resource for Customer {} +impl ResponseResult for Customer {} + + +/// 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(Option>); + +impl Part for UserCustomProperties {} + + +/// 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: Option, + /// ETag of the resource. + pub etag: Option, + /// Read ACLs on the field specifying who can view values of this field. Valid values are "ALL_DOMAIN_USERS" and "ADMINS_AND_SELF". + #[serde(rename="readAccessType")] + pub read_access_type: Option, + /// Type of the field. + #[serde(rename="fieldType")] + pub field_type: Option, + /// Boolean specifying whether the field is indexed or not. + pub indexed: Option, + /// Name of the field. + #[serde(rename="fieldName")] + pub field_name: Option, + /// 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(rename="numericIndexingSpec")] + pub numeric_indexing_spec: Option, + /// Unique identifier of Field (Read-only) + #[serde(rename="fieldId")] + pub field_id: Option, + /// Boolean specifying whether this is a multi-valued field or not. + #[serde(rename="multiValued")] + pub multi_valued: Option, +} + +impl Part for SchemaFieldSpec {} + + +/// JSON response template for List roles 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 roles](struct.RoleListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Roles { + /// no description provided + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// A list of Role resources. + pub items: Option>, + /// The type of the API resource. This is always admin#directory#roles. + pub kind: Option, + /// ETag of the resource. + pub etag: Option, +} + +impl ResponseResult for Roles {} + + /// JSON request template to undelete a user in Directory API. /// /// # Activities @@ -1038,6 +1382,29 @@ pub struct UserUndelete { impl RequestValue for UserUndelete {} +/// JSON response template to list domain 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*). +/// +/// * [list domain aliases](struct.DomainAliaseListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct DomainAliases { + /// List of domain alias objects. + #[serde(rename="domainAliases")] + pub domain_aliases: Option>, + /// Kind of resource this is. + pub kind: Option, + /// ETag of the resource. + pub etag: Option, +} + +impl ResponseResult for DomainAliases {} + + /// JSON response template for List verification codes operation in Directory API. /// /// # Activities @@ -1060,58 +1427,29 @@ pub struct VerificationCodes { impl ResponseResult for VerificationCodes {} -/// JSON template for Alias object in Directory API. +/// 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*). /// -/// * [aliases insert users](struct.UserAliaseInsertCall.html) (request|response) -/// * [aliases insert groups](struct.GroupAliaseInsertCall.html) (request|response) +/// * [list chromeosdevices](struct.ChromeosdeviceListCall.html) (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(rename="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, Serialize, Deserialize)] -pub struct MobileDevices { +pub struct ChromeOsDevices { /// Token used to access next page of this result. #[serde(rename="nextPageToken")] pub next_page_token: Option, - /// Kind of resource this is. - pub kind: Option, + /// List of Chrome OS Device objects. + pub chromeosdevices: Option>, /// ETag of the resource. pub etag: Option, - /// List of Mobile Device objects. - pub mobiledevices: Option>, + /// Kind of resource this is. + pub kind: Option, } -impl ResponseResult for MobileDevices {} +impl ResponseResult for ChromeOsDevices {} /// List of active time ranges (Read-only) @@ -1169,22 +1507,66 @@ impl RequestValue for UserPhoto {} impl ResponseResult for UserPhoto {} -/// JSON request template for firing commands on Mobile Device in Directory Devices API. +/// 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, Serialize, Deserialize)] +pub struct MobileDeviceApplications { + /// Version code of application + #[serde(rename="versionCode")] + pub version_code: Option, + /// Package name of application + #[serde(rename="packageName")] + pub package_name: Option, + /// Display name of application + #[serde(rename="displayName")] + pub display_name: Option, + /// Version name of application + #[serde(rename="versionName")] + pub version_name: Option, + /// List of Permissions for application + pub permission: Option>, +} + +impl NestedType for MobileDeviceApplications {} +impl Part for MobileDeviceApplications {} + + +/// JSON template for Domain 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*). /// -/// * [action mobiledevices](struct.MobiledeviceActionCall.html) (request) +/// * [insert domains](struct.DomainInsertCall.html) (request|response) +/// * [get domains](struct.DomainGetCall.html) (response) /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] -pub struct MobileDeviceAction { - /// Action to be taken on the Mobile Device - pub action: Option, +pub struct Domains { + /// Kind of resource this is. + pub kind: Option, + /// ETag of the resource. + pub etag: Option, + /// Indicates the verification state of a domain. (Read-only). + pub verified: Option, + /// The domain name of the customer. + #[serde(rename="domainName")] + pub domain_name: Option, + /// List of domain alias objects. (Read-only) + #[serde(rename="domainAliases")] + pub domain_aliases: Option>, + /// Indicates if the domain is a primary domain (Read-only). + #[serde(rename="isPrimary")] + pub is_primary: Option, + /// Creation time of the domain. (Read-only). + #[serde(rename="creationTime")] + pub creation_time: Option, } -impl RequestValue for MobileDeviceAction {} +impl RequestValue for Domains {} +impl ResponseResult for Domains {} /// JSON request template for setting/revoking admin status of a user in Directory API. @@ -1232,6 +1614,35 @@ pub struct Users { impl ResponseResult for Users {} +/// 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(rename="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 template for Mobile Device resource in Directory API. /// /// # Activities @@ -1260,6 +1671,9 @@ pub struct MobileDevice { /// The default locale used on the Mobile Device (Read-only) #[serde(rename="defaultLanguage")] pub default_language: Option, + /// Work profile supported on device (Read-only) + #[serde(rename="supportsWorkProfile")] + pub supports_work_profile: Option, /// Mobile Device Build number (Read-only) #[serde(rename="buildNumber")] pub build_number: Option, @@ -1273,16 +1687,25 @@ pub struct MobileDevice { /// Mobile Device user agent #[serde(rename="userAgent")] pub user_agent: Option, + /// Adb (USB debugging) enabled or disabled on device (Read-only) + #[serde(rename="adbStatus")] + pub adb_status: Option, /// Mobile Device Baseband version (Read-only) #[serde(rename="basebandVersion")] pub baseband_version: Option, /// Kind of resource this is. pub kind: Option, + /// Developer options enabled or disabled on device (Read-only) + #[serde(rename="developerOptionsStatus")] + pub developer_options_status: Option, /// List of owner user's names (Read-only) pub name: Option>, /// Date and time the device was first synchronized with the policy settings in the Google Apps administrator control panel (Read-only) #[serde(rename="firstSync")] pub first_sync: Option, + /// List of accounts added on device (Read-only) + #[serde(rename="otherAccountsInfo")] + pub other_accounts_info: Option>, /// Name of the mobile operating system pub os: Option, /// Mobile Device SSN or Serial Number (Read-only) @@ -1298,6 +1721,9 @@ pub struct MobileDevice { pub etag: Option, /// Status of the device (Read-only) pub status: Option, + /// Unknown sources enabled or disabled on device (Read-only) + #[serde(rename="unknownSourcesStatus")] + pub unknown_sources_status: Option, /// Boolean indicating if this account is on owner/primary profile or not (Read-only) #[serde(rename="managedAccountIsOnOwnerProfile")] pub managed_account_is_on_owner_profile: Option, @@ -1317,29 +1743,65 @@ impl Resource for MobileDevice {} impl ResponseResult for MobileDevice {} -/// JSON response template for List Chrome OS Devices operation in Directory API. +/// JSON response template to list Domains 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) +/// * [list domains](struct.DomainListCall.html) (response) /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] -pub struct ChromeOsDevices { - /// Token used to access next page of this result. - #[serde(rename="nextPageToken")] - pub next_page_token: Option, - /// List of Chrome OS Device objects. - pub chromeosdevices: Option>, - /// ETag of the resource. - pub etag: Option, +pub struct Domains2 { + /// List of domain objects. + pub domains: Option>, /// Kind of resource this is. pub kind: Option, + /// ETag of the resource. + pub etag: Option, } -impl ResponseResult for ChromeOsDevices {} +impl ResponseResult for Domains2 {} + + +/// 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, Serialize, Deserialize)] +pub struct Token { + /// A list of authorization scopes the application is granted. + pub scopes: Option>, + /// The type of the API resource. This is always admin#directory#token. + pub kind: Option, + /// The Client ID of the application the token is issued to. + #[serde(rename="clientId")] + pub client_id: Option, + /// 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(rename="nativeApp")] + pub native_app: Option, + /// The displayable name of the application the token is issued to. + #[serde(rename="displayText")] + pub display_text: Option, + /// ETag of the resource. + pub etag: Option, + /// Whether the application is registered with Google. The value is true if the application has an anonymous Client ID. + pub anonymous: Option, + /// The unique ID of the user that issued the token. + #[serde(rename="userKey")] + pub user_key: Option, +} + +impl Resource for Token {} +impl ResponseResult for Token {} /// JSON template for Org Unit resource in Directory API. @@ -1432,28 +1894,6 @@ 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, Serialize, Deserialize)] -pub struct Schemas { - /// Kind of resource this is. - pub kind: Option, - /// ETag of the resource. - pub etag: Option, - /// List of UserSchema objects. - pub schemas: Option>, -} - -impl ResponseResult for Schemas {} - - /// JSON response template to list aliases in Directory API. /// /// # Activities @@ -1477,12 +1917,34 @@ pub struct Aliases { impl ResponseResult for Aliases {} +/// 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, Serialize, Deserialize)] +pub struct Schemas { + /// Kind of resource this is. + pub kind: Option, + /// ETag of the resource. + pub etag: Option, + /// List of UserSchema objects. + pub schemas: Option>, +} + +impl ResponseResult for Schemas {} + + // ################### // MethodBuilders ### // ################# -/// A builder providing access to all methods supported on *token* resources. +/// A builder providing access to all methods supported on *group* resources. /// It is not used directly, but through the `Directory` hub. /// /// # Example @@ -1505,34 +1967,32 @@ impl ResponseResult for Aliases {} /// ::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(...)` +/// // like `aliases_delete(...)`, `aliases_insert(...)`, `aliases_list(...)`, `delete(...)`, `get(...)`, `insert(...)`, `list(...)`, `patch(...)` and `update(...)` /// // to build up your call. -/// let rb = hub.tokens(); +/// let rb = hub.groups(); /// # } /// ``` -pub struct TokenMethods<'a, C, A> +pub struct GroupMethods<'a, C, A> where C: 'a, A: 'a { hub: &'a Directory, } -impl<'a, C, A> MethodsBuilder for TokenMethods<'a, C, A> {} +impl<'a, C, A> MethodsBuilder for GroupMethods<'a, C, A> {} -impl<'a, C, A> TokenMethods<'a, C, A> { +impl<'a, C, A> GroupMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Get information about an access token issued by a user. + /// Delete Group /// /// # Arguments /// - /// * `userKey` - Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID. - /// * `clientId` - The Client ID of the application the token is issued to. - pub fn get(&self, user_key: &str, client_id: &str) -> TokenGetCall<'a, C, A> { - TokenGetCall { + /// * `groupKey` - Email or immutable Id of the group + pub fn delete(&self, group_key: &str) -> GroupDeleteCall<'a, C, A> { + GroupDeleteCall { hub: self.hub, - _user_key: user_key.to_string(), - _client_id: client_id.to_string(), + _group_key: group_key.to_string(), _delegate: Default::default(), _scopes: Default::default(), _additional_params: Default::default(), @@ -1541,412 +2001,15 @@ impl<'a, C, A> TokenMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Returns the set of tokens specified user has issued to 3rd party applications. - /// - /// # Arguments - /// - /// * `userKey` - 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 list(&self, user_key: &str) -> TokenListCall<'a, C, A> { - TokenListCall { + /// Retrieve all groups in a domain (paginated) + pub fn list(&self) -> GroupListCall<'a, C, A> { + GroupListCall { 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. - /// - /// # Arguments - /// - /// * `userKey` - Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID. - /// * `clientId` - The Client ID of the application the token is issued to. - pub fn delete(&self, user_key: &str, client_id: &str) -> TokenDeleteCall<'a, C, 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, A> - where C: 'a, A: 'a { - - hub: &'a Directory, -} - -impl<'a, C, A> MethodsBuilder for ChannelMethods<'a, C, A> {} - -impl<'a, C, A> ChannelMethods<'a, C, A> { - - /// Create a builder to help you perform the following task: - /// - /// Stop watching resources through this channel - /// - /// # Arguments - /// - /// * `request` - No description provided. - pub fn stop(&self, request: Channel) -> ChannelStopCall<'a, C, A> { - ChannelStopCall { - hub: self.hub, - _request: request, - _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, A> - where C: 'a, A: 'a { - - hub: &'a Directory, -} - -impl<'a, C, A> MethodsBuilder for OrgunitMethods<'a, C, A> {} - -impl<'a, C, A> OrgunitMethods<'a, C, A> { - - /// Create a builder to help you perform the following task: - /// - /// Add Organization Unit - /// - /// # Arguments - /// - /// * `request` - No description provided. - /// * `customerId` - Immutable id of the Google Apps account - pub fn insert(&self, request: OrgUnit, customer_id: &str) -> OrgunitInsertCall<'a, C, A> { - OrgunitInsertCall { - hub: self.hub, - _request: request, - _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 - /// - /// # Arguments - /// - /// * `customerId` - Immutable id of the Google Apps account - pub fn list(&self, customer_id: &str) -> OrgunitListCall<'a, C, 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 - /// - /// # Arguments - /// - /// * `customerId` - Immutable id of the Google Apps account - /// * `orgUnitPath` - Full path of the organization unit or its Id - pub fn get(&self, customer_id: &str, org_unit_path: &Vec) -> OrgunitGetCall<'a, C, 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 - /// - /// # Arguments - /// - /// * `request` - No description provided. - /// * `customerId` - Immutable id of the Google Apps account - /// * `orgUnitPath` - Full path of the organization unit or its Id - pub fn update(&self, request: OrgUnit, customer_id: &str, org_unit_path: &Vec) -> OrgunitUpdateCall<'a, C, A> { - OrgunitUpdateCall { - hub: self.hub, - _request: request, - _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 - /// - /// # Arguments - /// - /// * `customerId` - Immutable id of the Google Apps account - /// * `orgUnitPath` - Full path of the organization unit or its Id - pub fn delete(&self, customer_id: &str, org_unit_path: &Vec) -> OrgunitDeleteCall<'a, C, 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. - /// - /// # Arguments - /// - /// * `request` - No description provided. - /// * `customerId` - Immutable id of the Google Apps account - /// * `orgUnitPath` - Full path of the organization unit or its Id - pub fn patch(&self, request: OrgUnit, customer_id: &str, org_unit_path: &Vec) -> OrgunitPatchCall<'a, C, A> { - OrgunitPatchCall { - hub: self.hub, - _request: request, - _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, A> - where C: 'a, A: 'a { - - hub: &'a Directory, -} - -impl<'a, C, A> MethodsBuilder for UserMethods<'a, C, A> {} - -impl<'a, C, A> UserMethods<'a, C, A> { - - /// Create a builder to help you perform the following task: - /// - /// create user. - /// - /// # Arguments - /// - /// * `request` - No description provided. - pub fn insert(&self, request: User) -> UserInsertCall<'a, C, A> { - UserInsertCall { - hub: self.hub, - _request: request, - _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 - /// - /// # Arguments - /// - /// * `userKey` - Email or immutable Id of the user - pub fn photos_delete(&self, user_key: &str) -> UserPhotoDeleteCall<'a, C, 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 - /// - /// # Arguments - /// - /// * `request` - No description provided. - /// * `userKey` - The immutable id of the user - pub fn undelete(&self, request: UserUndelete, user_key: &str) -> UserUndeleteCall<'a, C, A> { - UserUndeleteCall { - hub: self.hub, - _request: request, - _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 - /// - /// # Arguments - /// - /// * `request` - No description provided. - /// * `userKey` - Email or immutable Id of the user as admin - pub fn make_admin(&self, request: UserMakeAdmin, user_key: &str) -> UserMakeAdminCall<'a, C, A> { - UserMakeAdminCall { - hub: self.hub, - _request: request, - _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. - /// - /// # Arguments - /// - /// * `request` - No description provided. - /// * `userKey` - Email or immutable Id of the user. If Id, it should match with id of user object - pub fn patch(&self, request: User, user_key: &str) -> UserPatchCall<'a, C, A> { - UserPatchCall { - hub: self.hub, - _request: request, - _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 - /// - /// # Arguments - /// - /// * `request` - No description provided. - pub fn watch(&self, request: Channel) -> UserWatchCall<'a, C, A> { - UserWatchCall { - hub: self.hub, - _request: request, - _view_type: Default::default(), - _sort_order: Default::default(), - _show_deleted: Default::default(), - _query: Default::default(), - _projection: Default::default(), + _user_key: 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(), @@ -1955,34 +2018,17 @@ impl<'a, C, A> UserMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Delete user - /// - /// # Arguments - /// - /// * `userKey` - Email or immutable Id of the user - pub fn delete(&self, user_key: &str) -> UserDeleteCall<'a, C, 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 + /// Update Group /// /// # Arguments /// /// * `request` - No description provided. - /// * `userKey` - Email or immutable Id of the user - pub fn photos_update(&self, request: UserPhoto, user_key: &str) -> UserPhotoUpdateCall<'a, C, A> { - UserPhotoUpdateCall { + /// * `groupKey` - Email or immutable Id of the group. If Id, it should match with id of group object + pub fn update(&self, request: Group, group_key: &str) -> GroupUpdateCall<'a, C, A> { + GroupUpdateCall { hub: self.hub, _request: request, - _user_key: user_key.to_string(), + _group_key: group_key.to_string(), _delegate: Default::default(), _scopes: Default::default(), _additional_params: Default::default(), @@ -1991,37 +2037,15 @@ impl<'a, C, A> UserMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// retrieve user - /// - /// # Arguments - /// - /// * `userKey` - Email or immutable Id of the user - pub fn get(&self, user_key: &str) -> UserGetCall<'a, C, 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 + /// Create Group /// /// # Arguments /// /// * `request` - No description provided. - /// * `userKey` - Email or immutable Id of the user - pub fn aliases_insert(&self, request: Alias, user_key: &str) -> UserAliaseInsertCall<'a, C, A> { - UserAliaseInsertCall { + pub fn insert(&self, request: Group) -> GroupInsertCall<'a, C, A> { + GroupInsertCall { hub: self.hub, _request: request, - _user_key: user_key.to_string(), _delegate: Default::default(), _scopes: Default::default(), _additional_params: Default::default(), @@ -2030,692 +2054,94 @@ impl<'a, C, A> UserMethods<'a, C, A> { /// 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, 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 + /// Add a alias for the group /// /// # Arguments /// - /// * `userKey` - Email or immutable Id of the user + /// * `request` - No description provided. + /// * `groupKey` - Email or immutable Id of the group + pub fn aliases_insert(&self, request: Alias, group_key: &str) -> GroupAliaseInsertCall<'a, C, A> { + GroupAliaseInsertCall { + hub: self.hub, + _request: request, + _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: + /// + /// List all aliases for a group + /// + /// # Arguments + /// + /// * `groupKey` - Email or immutable Id of the group + pub fn aliases_list(&self, group_key: &str) -> GroupAliaseListCall<'a, C, 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: + /// + /// Retrieve Group + /// + /// # Arguments + /// + /// * `groupKey` - Email or immutable Id of the group + pub fn get(&self, group_key: &str) -> GroupGetCall<'a, C, 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: + /// + /// Update Group. This method supports patch semantics. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `groupKey` - Email or immutable Id of the group. If Id, it should match with id of group object + pub fn patch(&self, request: Group, group_key: &str) -> GroupPatchCall<'a, C, A> { + GroupPatchCall { + hub: self.hub, + _request: request, + _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 + /// + /// # Arguments + /// + /// * `groupKey` - Email or immutable Id of the group /// * `alias` - The alias to be removed - pub fn aliases_delete(&self, user_key: &str, alias: &str) -> UserAliaseDeleteCall<'a, C, A> { - UserAliaseDeleteCall { + pub fn aliases_delete(&self, group_key: &str, alias: &str) -> GroupAliaseDeleteCall<'a, C, A> { + GroupAliaseDeleteCall { hub: self.hub, - _user_key: user_key.to_string(), + _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: - /// - /// update user - /// - /// # Arguments - /// - /// * `request` - No description provided. - /// * `userKey` - Email or immutable Id of the user. If Id, it should match with id of user object - pub fn update(&self, request: User, user_key: &str) -> UserUpdateCall<'a, C, A> { - UserUpdateCall { - hub: self.hub, - _request: request, - _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 - /// - /// # Arguments - /// - /// * `request` - No description provided. - /// * `userKey` - Email or immutable Id of the user - pub fn aliases_watch(&self, request: Channel, user_key: &str) -> UserAliaseWatchCall<'a, C, A> { - UserAliaseWatchCall { - hub: self.hub, - _request: request, - _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 - /// - /// # Arguments - /// - /// * `userKey` - Email or immutable Id of the user - pub fn aliases_list(&self, user_key: &str) -> UserAliaseListCall<'a, C, 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 - /// - /// # Arguments - /// - /// * `userKey` - Email or immutable Id of the user - pub fn photos_get(&self, user_key: &str) -> UserPhotoGetCall<'a, C, 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. - /// - /// # Arguments - /// - /// * `request` - No description provided. - /// * `userKey` - Email or immutable Id of the user - pub fn photos_patch(&self, request: UserPhoto, user_key: &str) -> UserPhotoPatchCall<'a, C, A> { - UserPhotoPatchCall { - hub: self.hub, - _request: request, - _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, A> - where C: 'a, A: 'a { - - hub: &'a Directory, -} - -impl<'a, C, A> MethodsBuilder for MobiledeviceMethods<'a, C, A> {} - -impl<'a, C, A> MobiledeviceMethods<'a, C, A> { - - /// Create a builder to help you perform the following task: - /// - /// Delete Mobile Device - /// - /// # Arguments - /// - /// * `customerId` - Immutable id of the Google Apps account - /// * `resourceId` - Immutable id of Mobile Device - pub fn delete(&self, customer_id: &str, resource_id: &str) -> MobiledeviceDeleteCall<'a, C, 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 - /// - /// # Arguments - /// - /// * `customerId` - Immutable id of the Google Apps account - /// * `resourceId` - Immutable id of Mobile Device - pub fn get(&self, customer_id: &str, resource_id: &str) -> MobiledeviceGetCall<'a, C, 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) - /// - /// # Arguments - /// - /// * `customerId` - Immutable id of the Google Apps account - pub fn list(&self, customer_id: &str) -> MobiledeviceListCall<'a, C, 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 - /// - /// # Arguments - /// - /// * `request` - No description provided. - /// * `customerId` - Immutable id of the Google Apps account - /// * `resourceId` - Immutable id of Mobile Device - pub fn action(&self, request: MobileDeviceAction, customer_id: &str, resource_id: &str) -> MobiledeviceActionCall<'a, C, A> { - MobiledeviceActionCall { - hub: self.hub, - _request: request, - _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, A> - where C: 'a, A: 'a { - - hub: &'a Directory, -} - -impl<'a, C, A> MethodsBuilder for MemberMethods<'a, C, A> {} - -impl<'a, C, A> MemberMethods<'a, C, A> { - - /// Create a builder to help you perform the following task: - /// - /// Update membership of a user in the specified group. - /// - /// # Arguments - /// - /// * `request` - No description provided. - /// * `groupKey` - Email or immutable Id of the group. If Id, it should match with id of group object - /// * `memberKey` - Email or immutable Id of the user. If Id, it should match with id of member object - pub fn update(&self, request: Member, group_key: &str, member_key: &str) -> MemberUpdateCall<'a, C, A> { - MemberUpdateCall { - hub: self.hub, - _request: request, - _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 - /// - /// # Arguments - /// - /// * `groupKey` - Email or immutable Id of the group - /// * `memberKey` - Email or immutable Id of the member - pub fn get(&self, group_key: &str, member_key: &str) -> MemberGetCall<'a, C, 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. - /// - /// # Arguments - /// - /// * `request` - No description provided. - /// * `groupKey` - Email or immutable Id of the group - pub fn insert(&self, request: Member, group_key: &str) -> MemberInsertCall<'a, C, A> { - MemberInsertCall { - hub: self.hub, - _request: request, - _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. - /// - /// # Arguments - /// - /// * `request` - No description provided. - /// * `groupKey` - Email or immutable Id of the group. If Id, it should match with id of group object - /// * `memberKey` - Email or immutable Id of the user. If Id, it should match with id of member object - pub fn patch(&self, request: Member, group_key: &str, member_key: &str) -> MemberPatchCall<'a, C, A> { - MemberPatchCall { - hub: self.hub, - _request: request, - _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. - /// - /// # Arguments - /// - /// * `groupKey` - Email or immutable Id of the group - /// * `memberKey` - Email or immutable Id of the member - pub fn delete(&self, group_key: &str, member_key: &str) -> MemberDeleteCall<'a, C, 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) - /// - /// # Arguments - /// - /// * `groupKey` - Email or immutable Id of the group - pub fn list(&self, group_key: &str) -> MemberListCall<'a, C, 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, A> - where C: 'a, A: 'a { - - hub: &'a Directory, -} - -impl<'a, C, A> MethodsBuilder for NotificationMethods<'a, C, A> {} - -impl<'a, C, A> NotificationMethods<'a, C, A> { - - /// Create a builder to help you perform the following task: - /// - /// Retrieves a list of notifications. - /// - /// # Arguments - /// - /// * `customer` - The unique ID for the customer's Google account. - pub fn list(&self, customer: &str) -> NotificationListCall<'a, C, 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 - /// - /// # Arguments - /// - /// * `customer` - The unique ID for the customer's Google account. The customerId is also returned as part of the Users resource. - /// * `notificationId` - The unique ID of the notification. - pub fn delete(&self, customer: &str, notification_id: &str) -> NotificationDeleteCall<'a, C, 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. - /// - /// # Arguments - /// - /// * `request` - No description provided. - /// * `customer` - The unique ID for the customer's Google account. - /// * `notificationId` - The unique ID of the notification. - pub fn patch(&self, request: Notification, customer: &str, notification_id: &str) -> NotificationPatchCall<'a, C, A> { - NotificationPatchCall { - hub: self.hub, - _request: request, - _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. - /// - /// # Arguments - /// - /// * `request` - No description provided. - /// * `customer` - The unique ID for the customer's Google account. - /// * `notificationId` - The unique ID of the notification. - pub fn update(&self, request: Notification, customer: &str, notification_id: &str) -> NotificationUpdateCall<'a, C, A> { - NotificationUpdateCall { - hub: self.hub, - _request: request, - _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. - /// - /// # Arguments - /// - /// * `customer` - The unique ID for the customer's Google account. The customerId is also returned as part of the Users resource. - /// * `notificationId` - The unique ID of the notification. - pub fn get(&self, customer: &str, notification_id: &str) -> NotificationGetCall<'a, C, 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, A> - where C: 'a, A: 'a { - - hub: &'a Directory, -} - -impl<'a, C, A> MethodsBuilder for ChromeosdeviceMethods<'a, C, A> {} - -impl<'a, C, A> ChromeosdeviceMethods<'a, C, A> { - - /// Create a builder to help you perform the following task: - /// - /// Retrieve all Chrome OS Devices of a customer (paginated) - /// - /// # Arguments - /// - /// * `customerId` - Immutable id of the Google Apps account - pub fn list(&self, customer_id: &str) -> ChromeosdeviceListCall<'a, C, 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. - /// - /// # Arguments - /// - /// * `request` - No description provided. - /// * `customerId` - Immutable id of the Google Apps account - /// * `deviceId` - Immutable id of Chrome OS Device - pub fn patch(&self, request: ChromeOsDevice, customer_id: &str, device_id: &str) -> ChromeosdevicePatchCall<'a, C, A> { - ChromeosdevicePatchCall { - hub: self.hub, - _request: request, - _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 - /// - /// # Arguments - /// - /// * `customerId` - Immutable id of the Google Apps account - /// * `deviceId` - Immutable id of Chrome OS Device - pub fn get(&self, customer_id: &str, device_id: &str) -> ChromeosdeviceGetCall<'a, C, 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 - /// - /// # Arguments - /// - /// * `request` - No description provided. - /// * `customerId` - Immutable id of the Google Apps account - /// * `deviceId` - Immutable id of Chrome OS Device - pub fn update(&self, request: ChromeOsDevice, customer_id: &str, device_id: &str) -> ChromeosdeviceUpdateCall<'a, C, A> { - ChromeosdeviceUpdateCall { - hub: self.hub, - _request: request, - _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(), - } - } } @@ -2812,7 +2238,7 @@ impl<'a, C, A> VerificationCodeMethods<'a, C, A> { -/// A builder providing access to all methods supported on *group* resources. +/// A builder providing access to all methods supported on *customer* resources. /// It is not used directly, but through the `Directory` hub. /// /// # Example @@ -2835,32 +2261,34 @@ impl<'a, C, A> VerificationCodeMethods<'a, C, A> { /// ::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(...)` +/// // like `get(...)`, `patch(...)` and `update(...)` /// // to build up your call. -/// let rb = hub.groups(); +/// let rb = hub.customers(); /// # } /// ``` -pub struct GroupMethods<'a, C, A> +pub struct CustomerMethods<'a, C, A> where C: 'a, A: 'a { hub: &'a Directory, } -impl<'a, C, A> MethodsBuilder for GroupMethods<'a, C, A> {} +impl<'a, C, A> MethodsBuilder for CustomerMethods<'a, C, A> {} -impl<'a, C, A> GroupMethods<'a, C, A> { +impl<'a, C, A> CustomerMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Retrieve Group + /// Updates a customer. This method supports patch semantics. /// /// # Arguments /// - /// * `groupKey` - Email or immutable Id of the group - pub fn get(&self, group_key: &str) -> GroupGetCall<'a, C, A> { - GroupGetCall { + /// * `request` - No description provided. + /// * `customerKey` - Id of the customer to be updated + pub fn patch(&self, request: Customer, customer_key: &str) -> CustomerPatchCall<'a, C, A> { + CustomerPatchCall { hub: self.hub, - _group_key: group_key.to_string(), + _request: request, + _customer_key: customer_key.to_string(), _delegate: Default::default(), _scopes: Default::default(), _additional_params: Default::default(), @@ -2869,15 +2297,374 @@ impl<'a, C, A> GroupMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Retrieve all groups in a domain (paginated) - pub fn list(&self) -> GroupListCall<'a, C, A> { - GroupListCall { + /// Retrives a customer. + /// + /// # Arguments + /// + /// * `customerKey` - Id of the customer to be retrieved + pub fn get(&self, customer_key: &str) -> CustomerGetCall<'a, C, A> { + CustomerGetCall { hub: self.hub, - _user_key: Default::default(), + _customer_key: customer_key.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates a customer. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `customerKey` - Id of the customer to be updated + pub fn update(&self, request: Customer, customer_key: &str) -> CustomerUpdateCall<'a, C, A> { + CustomerUpdateCall { + hub: self.hub, + _request: request, + _customer_key: customer_key.to_string(), + _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, A> + where C: 'a, A: 'a { + + hub: &'a Directory, +} + +impl<'a, C, A> MethodsBuilder for OrgunitMethods<'a, C, A> {} + +impl<'a, C, A> OrgunitMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieve all Organization Units + /// + /// # Arguments + /// + /// * `customerId` - Immutable id of the Google Apps account + pub fn list(&self, customer_id: &str) -> OrgunitListCall<'a, C, 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: + /// + /// Add Organization Unit + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `customerId` - Immutable id of the Google Apps account + pub fn insert(&self, request: OrgUnit, customer_id: &str) -> OrgunitInsertCall<'a, C, A> { + OrgunitInsertCall { + hub: self.hub, + _request: request, + _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: + /// + /// Update Organization Unit + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `customerId` - Immutable id of the Google Apps account + /// * `orgUnitPath` - Full path of the organization unit or its Id + pub fn update(&self, request: OrgUnit, customer_id: &str, org_unit_path: &Vec) -> OrgunitUpdateCall<'a, C, A> { + OrgunitUpdateCall { + hub: self.hub, + _request: request, + _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 + /// + /// # Arguments + /// + /// * `customerId` - Immutable id of the Google Apps account + /// * `orgUnitPath` - Full path of the organization unit or its Id + pub fn delete(&self, customer_id: &str, org_unit_path: &Vec) -> OrgunitDeleteCall<'a, C, 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: + /// + /// Retrieve Organization Unit + /// + /// # Arguments + /// + /// * `customerId` - Immutable id of the Google Apps account + /// * `orgUnitPath` - Full path of the organization unit or its Id + pub fn get(&self, customer_id: &str, org_unit_path: &Vec) -> OrgunitGetCall<'a, C, 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. This method supports patch semantics. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `customerId` - Immutable id of the Google Apps account + /// * `orgUnitPath` - Full path of the organization unit or its Id + pub fn patch(&self, request: OrgUnit, customer_id: &str, org_unit_path: &Vec) -> OrgunitPatchCall<'a, C, A> { + OrgunitPatchCall { + hub: self.hub, + _request: request, + _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, A> + where C: 'a, A: 'a { + + hub: &'a Directory, +} + +impl<'a, C, A> MethodsBuilder for UserMethods<'a, C, A> {} + +impl<'a, C, A> UserMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Undelete a deleted user + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `userKey` - The immutable id of the user + pub fn undelete(&self, request: UserUndelete, user_key: &str) -> UserUndeleteCall<'a, C, A> { + UserUndeleteCall { + hub: self.hub, + _request: request, + _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: + /// + /// Remove photos for the user + /// + /// # Arguments + /// + /// * `userKey` - Email or immutable Id of the user + pub fn photos_delete(&self, user_key: &str) -> UserPhotoDeleteCall<'a, C, 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: + /// + /// Add a photo for the user. This method supports patch semantics. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `userKey` - Email or immutable Id of the user + pub fn photos_patch(&self, request: UserPhoto, user_key: &str) -> UserPhotoPatchCall<'a, C, A> { + UserPhotoPatchCall { + hub: self.hub, + _request: request, + _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: + /// + /// create user. + /// + /// # Arguments + /// + /// * `request` - No description provided. + pub fn insert(&self, request: User) -> UserInsertCall<'a, C, A> { + UserInsertCall { + hub: self.hub, + _request: request, + _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 + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `userKey` - Email or immutable Id of the user + pub fn aliases_watch(&self, request: Channel, user_key: &str) -> UserAliaseWatchCall<'a, C, A> { + UserAliaseWatchCall { + hub: self.hub, + _request: request, + _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: + /// + /// Add a photo for the user + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `userKey` - Email or immutable Id of the user + pub fn photos_update(&self, request: UserPhoto, user_key: &str) -> UserPhotoUpdateCall<'a, C, A> { + UserPhotoUpdateCall { + hub: self.hub, + _request: request, + _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 + /// + /// # Arguments + /// + /// * `request` - No description provided. + pub fn watch(&self, request: Channel) -> UserWatchCall<'a, C, A> { + UserWatchCall { + hub: self.hub, + _request: request, + _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(), @@ -2886,34 +2673,17 @@ impl<'a, C, A> GroupMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// List all aliases for a group - /// - /// # Arguments - /// - /// * `groupKey` - Email or immutable Id of the group - pub fn aliases_list(&self, group_key: &str) -> GroupAliaseListCall<'a, C, 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. + /// update user /// /// # Arguments /// /// * `request` - No description provided. - /// * `groupKey` - Email or immutable Id of the group. If Id, it should match with id of group object - pub fn patch(&self, request: Group, group_key: &str) -> GroupPatchCall<'a, C, A> { - GroupPatchCall { + /// * `userKey` - Email or immutable Id of the user. If Id, it should match with id of user object + pub fn update(&self, request: User, user_key: &str) -> UserUpdateCall<'a, C, A> { + UserUpdateCall { hub: self.hub, _request: request, - _group_key: group_key.to_string(), + _user_key: user_key.to_string(), _delegate: Default::default(), _scopes: Default::default(), _additional_params: Default::default(), @@ -2922,17 +2692,78 @@ impl<'a, C, A> GroupMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Update Group + /// Retrieve photo of a user + /// + /// # Arguments + /// + /// * `userKey` - Email or immutable Id of the user + pub fn photos_get(&self, user_key: &str) -> UserPhotoGetCall<'a, C, 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: + /// + /// Retrieve either deleted users or all users in a domain (paginated) + pub fn list(&self) -> UserListCall<'a, C, 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: + /// + /// retrieve user + /// + /// # Arguments + /// + /// * `userKey` - Email or immutable Id of the user + pub fn get(&self, user_key: &str) -> UserGetCall<'a, C, 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 /// /// # Arguments /// /// * `request` - No description provided. - /// * `groupKey` - Email or immutable Id of the group. If Id, it should match with id of group object - pub fn update(&self, request: Group, group_key: &str) -> GroupUpdateCall<'a, C, A> { - GroupUpdateCall { + /// * `userKey` - Email or immutable Id of the user + pub fn aliases_insert(&self, request: Alias, user_key: &str) -> UserAliaseInsertCall<'a, C, A> { + UserAliaseInsertCall { hub: self.hub, _request: request, - _group_key: group_key.to_string(), + _user_key: user_key.to_string(), _delegate: Default::default(), _scopes: Default::default(), _additional_params: Default::default(), @@ -2941,15 +2772,16 @@ impl<'a, C, A> GroupMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Delete Group + /// List all aliases for a user /// /// # Arguments /// - /// * `groupKey` - Email or immutable Id of the group - pub fn delete(&self, group_key: &str) -> GroupDeleteCall<'a, C, A> { - GroupDeleteCall { + /// * `userKey` - Email or immutable Id of the user + pub fn aliases_list(&self, user_key: &str) -> UserAliaseListCall<'a, C, A> { + UserAliaseListCall { hub: self.hub, - _group_key: group_key.to_string(), + _user_key: user_key.to_string(), + _event: Default::default(), _delegate: Default::default(), _scopes: Default::default(), _additional_params: Default::default(), @@ -2958,17 +2790,17 @@ impl<'a, C, A> GroupMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Add a alias for the group + /// change admin status of a user /// /// # Arguments /// /// * `request` - No description provided. - /// * `groupKey` - Email or immutable Id of the group - pub fn aliases_insert(&self, request: Alias, group_key: &str) -> GroupAliaseInsertCall<'a, C, A> { - GroupAliaseInsertCall { + /// * `userKey` - Email or immutable Id of the user as admin + pub fn make_admin(&self, request: UserMakeAdmin, user_key: &str) -> UserMakeAdminCall<'a, C, A> { + UserMakeAdminCall { hub: self.hub, _request: request, - _group_key: group_key.to_string(), + _user_key: user_key.to_string(), _delegate: Default::default(), _scopes: Default::default(), _additional_params: Default::default(), @@ -2977,16 +2809,35 @@ impl<'a, C, A> GroupMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Remove a alias for the group + /// update user. This method supports patch semantics. /// /// # Arguments /// - /// * `groupKey` - Email or immutable Id of the group + /// * `request` - No description provided. + /// * `userKey` - Email or immutable Id of the user. If Id, it should match with id of user object + pub fn patch(&self, request: User, user_key: &str) -> UserPatchCall<'a, C, A> { + UserPatchCall { + hub: self.hub, + _request: request, + _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: + /// + /// Remove a alias for the user + /// + /// # Arguments + /// + /// * `userKey` - Email or immutable Id of the user /// * `alias` - The alias to be removed - pub fn aliases_delete(&self, group_key: &str, alias: &str) -> GroupAliaseDeleteCall<'a, C, A> { - GroupAliaseDeleteCall { + pub fn aliases_delete(&self, user_key: &str, alias: &str) -> UserAliaseDeleteCall<'a, C, A> { + UserAliaseDeleteCall { hub: self.hub, - _group_key: group_key.to_string(), + _user_key: user_key.to_string(), _alias: alias.to_string(), _delegate: Default::default(), _scopes: Default::default(), @@ -2996,15 +2847,881 @@ impl<'a, C, A> GroupMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Create Group + /// Delete user + /// + /// # Arguments + /// + /// * `userKey` - Email or immutable Id of the user + pub fn delete(&self, user_key: &str) -> UserDeleteCall<'a, C, A> { + UserDeleteCall { + 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 *role* 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.roles(); +/// # } +/// ``` +pub struct RoleMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Directory, +} + +impl<'a, C, A> MethodsBuilder for RoleMethods<'a, C, A> {} + +impl<'a, C, A> RoleMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Updates a role. /// /// # Arguments /// /// * `request` - No description provided. - pub fn insert(&self, request: Group) -> GroupInsertCall<'a, C, A> { - GroupInsertCall { + /// * `customer` - Immutable ID of the Google Apps account. + /// * `roleId` - Immutable ID of the role. + pub fn update(&self, request: Role, customer: &str, role_id: &str) -> RoleUpdateCall<'a, C, A> { + RoleUpdateCall { hub: self.hub, _request: request, + _customer: customer.to_string(), + _role_id: role_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 role. + /// + /// # Arguments + /// + /// * `customer` - Immutable ID of the Google Apps account. + /// * `roleId` - Immutable ID of the role. + pub fn get(&self, customer: &str, role_id: &str) -> RoleGetCall<'a, C, A> { + RoleGetCall { + hub: self.hub, + _customer: customer.to_string(), + _role_id: role_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 role. + /// + /// # Arguments + /// + /// * `customer` - Immutable ID of the Google Apps account. + /// * `roleId` - Immutable ID of the role. + pub fn delete(&self, customer: &str, role_id: &str) -> RoleDeleteCall<'a, C, A> { + RoleDeleteCall { + hub: self.hub, + _customer: customer.to_string(), + _role_id: role_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 role. This method supports patch semantics. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `customer` - Immutable ID of the Google Apps account. + /// * `roleId` - Immutable ID of the role. + pub fn patch(&self, request: Role, customer: &str, role_id: &str) -> RolePatchCall<'a, C, A> { + RolePatchCall { + hub: self.hub, + _request: request, + _customer: customer.to_string(), + _role_id: role_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 role. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `customer` - Immutable ID of the Google Apps account. + pub fn insert(&self, request: Role, customer: &str) -> RoleInsertCall<'a, C, A> { + RoleInsertCall { + hub: self.hub, + _request: request, + _customer: customer.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a paginated list of all the roles in a domain. + /// + /// # Arguments + /// + /// * `customer` - Immutable id of the Google Apps account. + pub fn list(&self, customer: &str) -> RoleListCall<'a, C, A> { + RoleListCall { + hub: self.hub, + _customer: customer.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 *privilege* 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 `list(...)` +/// // to build up your call. +/// let rb = hub.privileges(); +/// # } +/// ``` +pub struct PrivilegeMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Directory, +} + +impl<'a, C, A> MethodsBuilder for PrivilegeMethods<'a, C, A> {} + +impl<'a, C, A> PrivilegeMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a paginated list of all privileges for a customer. + /// + /// # Arguments + /// + /// * `customer` - Immutable ID of the Google Apps account. + pub fn list(&self, customer: &str) -> PrivilegeListCall<'a, C, A> { + PrivilegeListCall { + hub: self.hub, + _customer: customer.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, A> + where C: 'a, A: 'a { + + hub: &'a Directory, +} + +impl<'a, C, A> MethodsBuilder for MobiledeviceMethods<'a, C, A> {} + +impl<'a, C, A> MobiledeviceMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieve Mobile Device + /// + /// # Arguments + /// + /// * `customerId` - Immutable id of the Google Apps account + /// * `resourceId` - Immutable id of Mobile Device + pub fn get(&self, customer_id: &str, resource_id: &str) -> MobiledeviceGetCall<'a, C, 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) + /// + /// # Arguments + /// + /// * `customerId` - Immutable id of the Google Apps account + pub fn list(&self, customer_id: &str) -> MobiledeviceListCall<'a, C, 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: + /// + /// Delete Mobile Device + /// + /// # Arguments + /// + /// * `customerId` - Immutable id of the Google Apps account + /// * `resourceId` - Immutable id of Mobile Device + pub fn delete(&self, customer_id: &str, resource_id: &str) -> MobiledeviceDeleteCall<'a, C, 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: + /// + /// Take action on Mobile Device + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `customerId` - Immutable id of the Google Apps account + /// * `resourceId` - Immutable id of Mobile Device + pub fn action(&self, request: MobileDeviceAction, customer_id: &str, resource_id: &str) -> MobiledeviceActionCall<'a, C, A> { + MobiledeviceActionCall { + hub: self.hub, + _request: request, + _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 *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, A> + where C: 'a, A: 'a { + + hub: &'a Directory, +} + +impl<'a, C, A> MethodsBuilder for TokenMethods<'a, C, A> {} + +impl<'a, C, A> TokenMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Get information about an access token issued by a user. + /// + /// # Arguments + /// + /// * `userKey` - Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID. + /// * `clientId` - The Client ID of the application the token is issued to. + pub fn get(&self, user_key: &str, client_id: &str) -> TokenGetCall<'a, C, 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. + /// + /// # Arguments + /// + /// * `userKey` - 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 list(&self, user_key: &str) -> TokenListCall<'a, C, 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. + /// + /// # Arguments + /// + /// * `userKey` - Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID. + /// * `clientId` - The Client ID of the application the token is issued to. + pub fn delete(&self, user_key: &str, client_id: &str) -> TokenDeleteCall<'a, C, 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 *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, A> + where C: 'a, A: 'a { + + hub: &'a Directory, +} + +impl<'a, C, A> MethodsBuilder for NotificationMethods<'a, C, A> {} + +impl<'a, C, A> NotificationMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a list of notifications. + /// + /// # Arguments + /// + /// * `customer` - The unique ID for the customer's Google account. + pub fn list(&self, customer: &str) -> NotificationListCall<'a, C, 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: + /// + /// Updates a notification. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `customer` - The unique ID for the customer's Google account. + /// * `notificationId` - The unique ID of the notification. + pub fn update(&self, request: Notification, customer: &str, notification_id: &str) -> NotificationUpdateCall<'a, C, A> { + NotificationUpdateCall { + hub: self.hub, + _request: request, + _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: + /// + /// Deletes a notification + /// + /// # Arguments + /// + /// * `customer` - The unique ID for the customer's Google account. The customerId is also returned as part of the Users resource. + /// * `notificationId` - The unique ID of the notification. + pub fn delete(&self, customer: &str, notification_id: &str) -> NotificationDeleteCall<'a, C, 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: + /// + /// Retrieves a notification. + /// + /// # Arguments + /// + /// * `customer` - The unique ID for the customer's Google account. The customerId is also returned as part of the Users resource. + /// * `notificationId` - The unique ID of the notification. + pub fn get(&self, customer: &str, notification_id: &str) -> NotificationGetCall<'a, C, 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(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates a notification. This method supports patch semantics. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `customer` - The unique ID for the customer's Google account. + /// * `notificationId` - The unique ID of the notification. + pub fn patch(&self, request: Notification, customer: &str, notification_id: &str) -> NotificationPatchCall<'a, C, A> { + NotificationPatchCall { + hub: self.hub, + _request: request, + _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, A> + where C: 'a, A: 'a { + + hub: &'a Directory, +} + +impl<'a, C, A> MethodsBuilder for ChromeosdeviceMethods<'a, C, A> {} + +impl<'a, C, A> ChromeosdeviceMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieve all Chrome OS Devices of a customer (paginated) + /// + /// # Arguments + /// + /// * `customerId` - Immutable id of the Google Apps account + pub fn list(&self, customer_id: &str) -> ChromeosdeviceListCall<'a, C, 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. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `customerId` - Immutable id of the Google Apps account + /// * `deviceId` - Immutable id of Chrome OS Device + pub fn patch(&self, request: ChromeOsDevice, customer_id: &str, device_id: &str) -> ChromeosdevicePatchCall<'a, C, A> { + ChromeosdevicePatchCall { + hub: self.hub, + _request: request, + _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 + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `customerId` - Immutable id of the Google Apps account + /// * `deviceId` - Immutable id of Chrome OS Device + pub fn update(&self, request: ChromeOsDevice, customer_id: &str, device_id: &str) -> ChromeosdeviceUpdateCall<'a, C, A> { + ChromeosdeviceUpdateCall { + hub: self.hub, + _request: request, + _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 + /// + /// # Arguments + /// + /// * `customerId` - Immutable id of the Google Apps account + /// * `deviceId` - Immutable id of Chrome OS Device + pub fn get(&self, customer_id: &str, device_id: &str) -> ChromeosdeviceGetCall<'a, C, 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(), + } + } +} + + + +/// 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, A> + where C: 'a, A: 'a { + + hub: &'a Directory, +} + +impl<'a, C, A> MethodsBuilder for MemberMethods<'a, C, A> {} + +impl<'a, C, A> MemberMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Add user to the specified group. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `groupKey` - Email or immutable Id of the group + pub fn insert(&self, request: Member, group_key: &str) -> MemberInsertCall<'a, C, A> { + MemberInsertCall { + hub: self.hub, + _request: request, + _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. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `groupKey` - Email or immutable Id of the group. If Id, it should match with id of group object + /// * `memberKey` - Email or immutable Id of the user. If Id, it should match with id of member object + pub fn patch(&self, request: Member, group_key: &str, member_key: &str) -> MemberPatchCall<'a, C, A> { + MemberPatchCall { + hub: self.hub, + _request: request, + _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: + /// + /// Update membership of a user in the specified group. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `groupKey` - Email or immutable Id of the group. If Id, it should match with id of group object + /// * `memberKey` - Email or immutable Id of the user. If Id, it should match with id of member object + pub fn update(&self, request: Member, group_key: &str, member_key: &str) -> MemberUpdateCall<'a, C, A> { + MemberUpdateCall { + hub: self.hub, + _request: request, + _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) + /// + /// # Arguments + /// + /// * `groupKey` - Email or immutable Id of the group + pub fn list(&self, group_key: &str) -> MemberListCall<'a, C, 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(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieve Group Member + /// + /// # Arguments + /// + /// * `groupKey` - Email or immutable Id of the group + /// * `memberKey` - Email or immutable Id of the member + pub fn get(&self, group_key: &str, member_key: &str) -> MemberGetCall<'a, C, 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: + /// + /// Remove membership. + /// + /// # Arguments + /// + /// * `groupKey` - Email or immutable Id of the group + /// * `memberKey` - Email or immutable Id of the member + pub fn delete(&self, group_key: &str, member_key: &str) -> MemberDeleteCall<'a, C, 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(), @@ -3052,6 +3769,25 @@ impl<'a, C, A> MethodsBuilder for AspMethods<'a, C, A> {} impl<'a, C, A> AspMethods<'a, C, A> { + /// Create a builder to help you perform the following task: + /// + /// Get information about an ASP issued by a user. + /// + /// # Arguments + /// + /// * `userKey` - Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID. + /// * `codeId` - The unique ID of the ASP. + pub fn get(&self, user_key: &str, code_id: i32) -> AspGetCall<'a, C, 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(), + } + } + /// Create a builder to help you perform the following task: /// /// Delete an ASP issued by a user. @@ -3087,20 +3823,232 @@ impl<'a, C, A> AspMethods<'a, C, A> { _additional_params: Default::default(), } } +} + + + +/// A builder providing access to all methods supported on *domain* 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(...)` and `list(...)` +/// // to build up your call. +/// let rb = hub.domains(); +/// # } +/// ``` +pub struct DomainMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Directory, +} + +impl<'a, C, A> MethodsBuilder for DomainMethods<'a, C, A> {} + +impl<'a, C, A> DomainMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Get information about an ASP issued by a user. + /// Lists the domains of the customer. /// /// # Arguments /// - /// * `userKey` - Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID. - /// * `codeId` - The unique ID of the ASP. - pub fn get(&self, user_key: &str, code_id: i32) -> AspGetCall<'a, C, A> { - AspGetCall { + /// * `customer` - Immutable id of the Google Apps account. + pub fn list(&self, customer: &str) -> DomainListCall<'a, C, A> { + DomainListCall { hub: self.hub, - _user_key: user_key.to_string(), - _code_id: code_id, + _customer: customer.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrives a domain of the customer. + /// + /// # Arguments + /// + /// * `customer` - Immutable id of the Google Apps account. + /// * `domainName` - Name of domain to be retrieved + pub fn get(&self, customer: &str, domain_name: &str) -> DomainGetCall<'a, C, A> { + DomainGetCall { + hub: self.hub, + _customer: customer.to_string(), + _domain_name: domain_name.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Inserts a domain of the customer. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `customer` - Immutable id of the Google Apps account. + pub fn insert(&self, request: Domains, customer: &str) -> DomainInsertCall<'a, C, A> { + DomainInsertCall { + hub: self.hub, + _request: request, + _customer: customer.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Deletes a domain of the customer. + /// + /// # Arguments + /// + /// * `customer` - Immutable id of the Google Apps account. + /// * `domainName` - Name of domain to be deleted + pub fn delete(&self, customer: &str, domain_name: &str) -> DomainDeleteCall<'a, C, A> { + DomainDeleteCall { + hub: self.hub, + _customer: customer.to_string(), + _domain_name: domain_name.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *domainAliase* 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(...)` and `list(...)` +/// // to build up your call. +/// let rb = hub.domain_aliases(); +/// # } +/// ``` +pub struct DomainAliaseMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Directory, +} + +impl<'a, C, A> MethodsBuilder for DomainAliaseMethods<'a, C, A> {} + +impl<'a, C, A> DomainAliaseMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Inserts a Domain alias of the customer. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `customer` - Immutable id of the Google Apps account. + pub fn insert(&self, request: DomainAlias, customer: &str) -> DomainAliaseInsertCall<'a, C, A> { + DomainAliaseInsertCall { + hub: self.hub, + _request: request, + _customer: customer.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a domain alias of the customer. + /// + /// # Arguments + /// + /// * `customer` - Immutable id of the Google Apps account. + /// * `domainAliasName` - Name of domain alias to be retrieved. + pub fn get(&self, customer: &str, domain_alias_name: &str) -> DomainAliaseGetCall<'a, C, A> { + DomainAliaseGetCall { + hub: self.hub, + _customer: customer.to_string(), + _domain_alias_name: domain_alias_name.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Lists the domain aliases of the customer. + /// + /// # Arguments + /// + /// * `customer` - Immutable id of the Google Apps account. + pub fn list(&self, customer: &str) -> DomainAliaseListCall<'a, C, A> { + DomainAliaseListCall { + hub: self.hub, + _customer: customer.to_string(), + _parent_domain_name: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Deletes a Domain Alias of the customer. + /// + /// # Arguments + /// + /// * `customer` - Immutable id of the Google Apps account. + /// * `domainAliasName` - Name of domain alias to be retrieved. + pub fn delete(&self, customer: &str, domain_alias_name: &str) -> DomainAliaseDeleteCall<'a, C, A> { + DomainAliaseDeleteCall { + hub: self.hub, + _customer: customer.to_string(), + _domain_alias_name: domain_alias_name.to_string(), _delegate: Default::default(), _scopes: Default::default(), _additional_params: Default::default(), @@ -3148,23 +4096,6 @@ impl<'a, C, A> MethodsBuilder for SchemaMethods<'a, C, A> {} impl<'a, C, A> SchemaMethods<'a, C, A> { - /// Create a builder to help you perform the following task: - /// - /// Retrieve all schemas for a customer - /// - /// # Arguments - /// - /// * `customerId` - Immutable id of the Google Apps account - pub fn list(&self, customer_id: &str) -> SchemaListCall<'a, C, 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 @@ -3184,65 +4115,6 @@ impl<'a, C, A> SchemaMethods<'a, C, A> { } } - /// Create a builder to help you perform the following task: - /// - /// Update schema. This method supports patch semantics. - /// - /// # Arguments - /// - /// * `request` - No description provided. - /// * `customerId` - Immutable id of the Google Apps account - /// * `schemaKey` - Name or immutable Id of the schema. - pub fn patch(&self, request: Schema, customer_id: &str, schema_key: &str) -> SchemaPatchCall<'a, C, A> { - SchemaPatchCall { - hub: self.hub, - _request: request, - _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. - /// - /// # Arguments - /// - /// * `request` - No description provided. - /// * `customerId` - Immutable id of the Google Apps account - pub fn insert(&self, request: Schema, customer_id: &str) -> SchemaInsertCall<'a, C, A> { - SchemaInsertCall { - hub: self.hub, - _request: request, - _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 - /// - /// # Arguments - /// - /// * `customerId` - Immutable id of the Google Apps account - /// * `schemaKey` - Name or immutable Id of the schema - pub fn delete(&self, customer_id: &str, schema_key: &str) -> SchemaDeleteCall<'a, C, 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 @@ -3263,6 +4135,259 @@ impl<'a, C, A> SchemaMethods<'a, C, A> { _additional_params: Default::default(), } } + + /// Create a builder to help you perform the following task: + /// + /// Retrieve all schemas for a customer + /// + /// # Arguments + /// + /// * `customerId` - Immutable id of the Google Apps account + pub fn list(&self, customer_id: &str) -> SchemaListCall<'a, C, 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: + /// + /// Update schema. This method supports patch semantics. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `customerId` - Immutable id of the Google Apps account + /// * `schemaKey` - Name or immutable Id of the schema. + pub fn patch(&self, request: Schema, customer_id: &str, schema_key: &str) -> SchemaPatchCall<'a, C, A> { + SchemaPatchCall { + hub: self.hub, + _request: request, + _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: + /// + /// Delete schema + /// + /// # Arguments + /// + /// * `customerId` - Immutable id of the Google Apps account + /// * `schemaKey` - Name or immutable Id of the schema + pub fn delete(&self, customer_id: &str, schema_key: &str) -> SchemaDeleteCall<'a, C, 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: + /// + /// Create schema. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `customerId` - Immutable id of the Google Apps account + pub fn insert(&self, request: Schema, customer_id: &str) -> SchemaInsertCall<'a, C, A> { + SchemaInsertCall { + hub: self.hub, + _request: request, + _customer_id: customer_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, A> + where C: 'a, A: 'a { + + hub: &'a Directory, +} + +impl<'a, C, A> MethodsBuilder for ChannelMethods<'a, C, A> {} + +impl<'a, C, A> ChannelMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Stop watching resources through this channel + /// + /// # Arguments + /// + /// * `request` - No description provided. + pub fn stop(&self, request: Channel) -> ChannelStopCall<'a, C, A> { + ChannelStopCall { + hub: self.hub, + _request: request, + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *roleAssignment* 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(...)` and `list(...)` +/// // to build up your call. +/// let rb = hub.role_assignments(); +/// # } +/// ``` +pub struct RoleAssignmentMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Directory, +} + +impl<'a, C, A> MethodsBuilder for RoleAssignmentMethods<'a, C, A> {} + +impl<'a, C, A> RoleAssignmentMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Creates a role assignment. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `customer` - Immutable ID of the Google Apps account. + pub fn insert(&self, request: RoleAssignment, customer: &str) -> RoleAssignmentInsertCall<'a, C, A> { + RoleAssignmentInsertCall { + hub: self.hub, + _request: request, + _customer: customer.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieve a role assignment. + /// + /// # Arguments + /// + /// * `customer` - Immutable ID of the Google Apps account. + /// * `roleAssignmentId` - Immutable ID of the role assignment. + pub fn get(&self, customer: &str, role_assignment_id: &str) -> RoleAssignmentGetCall<'a, C, A> { + RoleAssignmentGetCall { + hub: self.hub, + _customer: customer.to_string(), + _role_assignment_id: role_assignment_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 role assignment. + /// + /// # Arguments + /// + /// * `customer` - Immutable ID of the Google Apps account. + /// * `roleAssignmentId` - Immutable ID of the role assignment. + pub fn delete(&self, customer: &str, role_assignment_id: &str) -> RoleAssignmentDeleteCall<'a, C, A> { + RoleAssignmentDeleteCall { + hub: self.hub, + _customer: customer.to_string(), + _role_assignment_id: role_assignment_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 paginated list of all roleAssignments. + /// + /// # Arguments + /// + /// * `customer` - Immutable ID of the Google Apps account. + pub fn list(&self, customer: &str) -> RoleAssignmentListCall<'a, C, A> { + RoleAssignmentListCall { + hub: self.hub, + _customer: customer.to_string(), + _user_key: Default::default(), + _role_id: Default::default(), + _page_token: Default::default(), + _max_results: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } } @@ -3273,6 +4398,12699 @@ impl<'a, C, A> SchemaMethods<'a, C, A> { // CallBuilders ### // ################# +/// Delete Group +/// +/// A builder for the *delete* method supported by a *group* resource. +/// It is not used directly, but through a `GroupMethods` instance. +/// +/// # 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, A> + where C: 'a, A: 'a { + + hub: &'a Directory, + _group_key: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for GroupDeleteCall<'a, C, A> {} + +impl<'a, C, A> GroupDeleteCall<'a, C, A> where 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 Err(Error::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::DirectoryGroup.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = res; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Email or immutable Id of the group + /// + /// 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. + pub fn group_key(mut self, new_value: &str) -> GroupDeleteCall<'a, C, A> { + self._group_key = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> GroupDeleteCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::DirectoryGroup`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # 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("diam") +/// .page_token("ipsum") +/// .max_results(-5) +/// .domain("et") +/// .customer("duo") +/// .doit(); +/// # } +/// ``` +pub struct GroupListCall<'a, C, A> + where C: '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, A> CallBuilder for GroupListCall<'a, C, A> {} + +impl<'a, C, A> GroupListCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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::DirectoryGroupReadonly.as_ref().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_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 + /// + /// Sets the *user key* query property to the given value. + pub fn user_key(mut self, new_value: &str) -> GroupListCall<'a, C, A> { + self._user_key = Some(new_value.to_string()); + self + } + /// Token to specify next page in the list + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> GroupListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Maximum number of results to return. Default is 200 + /// + /// Sets the *max results* query property to the given value. + pub fn max_results(mut self, new_value: i32) -> GroupListCall<'a, C, A> { + self._max_results = Some(new_value); + self + } + /// 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. + /// + /// Sets the *domain* query property to the given value. + pub fn domain(mut self, new_value: &str) -> GroupListCall<'a, C, A> { + self._domain = Some(new_value.to_string()); + self + } + /// 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. + /// + /// Sets the *customer* query property to the given value. + pub fn customer(mut self, new_value: &str) -> GroupListCall<'a, C, A> { + self._customer = Some(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> GroupListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::DirectoryGroupReadonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # 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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: 'a, A: 'a { + + hub: &'a Directory, + _request: Group, + _group_key: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for GroupUpdateCall<'a, C, A> {} + +impl<'a, C, A> GroupUpdateCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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::DirectoryGroup.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// Email or immutable Id of the group. If Id, it should match with id of group object + /// + /// 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. + pub fn group_key(mut self, new_value: &str) -> GroupUpdateCall<'a, C, A> { + self._group_key = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> GroupUpdateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::DirectoryGroup`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # 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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: 'a, A: 'a { + + hub: &'a Directory, + _request: Group, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for GroupInsertCall<'a, C, A> {} + +impl<'a, C, A> GroupInsertCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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::DirectoryGroup.as_ref().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> GroupInsertCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::DirectoryGroup`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # 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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: 'a, A: 'a { + + hub: &'a Directory, + _request: Alias, + _group_key: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for GroupAliaseInsertCall<'a, C, A> {} + +impl<'a, C, A> GroupAliaseInsertCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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::DirectoryGroup.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// Email or immutable Id of the group + /// + /// 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. + pub fn group_key(mut self, new_value: &str) -> GroupAliaseInsertCall<'a, C, A> { + self._group_key = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> GroupAliaseInsertCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::DirectoryGroup`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # 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, A> + where C: 'a, A: 'a { + + hub: &'a Directory, + _group_key: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for GroupAliaseListCall<'a, C, A> {} + +impl<'a, C, A> GroupAliaseListCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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::DirectoryGroupReadonly.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Email or immutable Id of the group + /// + /// 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. + pub fn group_key(mut self, new_value: &str) -> GroupAliaseListCall<'a, C, A> { + self._group_key = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> GroupAliaseListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::DirectoryGroupReadonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # 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, A> + where C: 'a, A: 'a { + + hub: &'a Directory, + _group_key: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for GroupGetCall<'a, C, A> {} + +impl<'a, C, A> GroupGetCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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::DirectoryGroupReadonly.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Email or immutable Id of the group + /// + /// 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. + pub fn group_key(mut self, new_value: &str) -> GroupGetCall<'a, C, A> { + self._group_key = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> GroupGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::DirectoryGroupReadonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # 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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: 'a, A: 'a { + + hub: &'a Directory, + _request: Group, + _group_key: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for GroupPatchCall<'a, C, A> {} + +impl<'a, C, A> GroupPatchCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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::DirectoryGroup.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// Email or immutable Id of the group. If Id, it should match with id of group object + /// + /// 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. + pub fn group_key(mut self, new_value: &str) -> GroupPatchCall<'a, C, A> { + self._group_key = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> GroupPatchCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::DirectoryGroup`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # 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, A> + where C: 'a, A: 'a { + + hub: &'a Directory, + _group_key: String, + _alias: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for GroupAliaseDeleteCall<'a, C, A> {} + +impl<'a, C, A> GroupAliaseDeleteCall<'a, C, A> where 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 Err(Error::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::DirectoryGroup.as_ref().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 ["alias", "groupKey"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = res; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Email or immutable Id of the group + /// + /// 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. + pub fn group_key(mut self, new_value: &str) -> GroupAliaseDeleteCall<'a, C, A> { + self._group_key = new_value.to_string(); + self + } + /// The alias to be removed + /// + /// 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. + pub fn alias(mut self, new_value: &str) -> GroupAliaseDeleteCall<'a, C, A> { + self._alias = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> GroupAliaseDeleteCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::DirectoryGroup`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # 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, A> + where C: 'a, A: 'a { + + hub: &'a Directory, + _user_key: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for VerificationCodeGenerateCall<'a, C, A> {} + +impl<'a, C, A> VerificationCodeGenerateCall<'a, C, A> where 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 Err(Error::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::DirectoryUserSecurity.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = res; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Email or immutable Id of the user + /// + /// 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. + pub fn user_key(mut self, new_value: &str) -> VerificationCodeGenerateCall<'a, C, A> { + self._user_key = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> VerificationCodeGenerateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::DirectoryUserSecurity`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # 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, A> + where C: 'a, A: 'a { + + hub: &'a Directory, + _user_key: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for VerificationCodeInvalidateCall<'a, C, A> {} + +impl<'a, C, A> VerificationCodeInvalidateCall<'a, C, A> where 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 Err(Error::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::DirectoryUserSecurity.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = res; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Email or immutable Id of the user + /// + /// 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. + pub fn user_key(mut self, new_value: &str) -> VerificationCodeInvalidateCall<'a, C, A> { + self._user_key = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> VerificationCodeInvalidateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::DirectoryUserSecurity`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # 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, A> + where C: 'a, A: 'a { + + hub: &'a Directory, + _user_key: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for VerificationCodeListCall<'a, C, A> {} + +impl<'a, C, A> VerificationCodeListCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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::DirectoryUserSecurity.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID. + /// + /// 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. + pub fn user_key(mut self, new_value: &str) -> VerificationCodeListCall<'a, C, A> { + self._user_key = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> VerificationCodeListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::DirectoryUserSecurity`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Updates a customer. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *customer* resource. +/// It is not used directly, but through a `CustomerMethods` instance. +/// +/// # 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::Customer; +/// # #[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 = Customer::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.customers().patch(req, "customerKey") +/// .doit(); +/// # } +/// ``` +pub struct CustomerPatchCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Directory, + _request: Customer, + _customer_key: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for CustomerPatchCall<'a, C, A> {} + +impl<'a, C, A> CustomerPatchCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Customer)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.customers.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("customerKey", self._customer_key.to_string())); + for &field in ["alt", "customerKey"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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/customers/{customerKey}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryCustomer.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{customerKey}", "customerKey")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["customerKey"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: Customer) -> CustomerPatchCall<'a, C, A> { + self._request = new_value; + self + } + /// Id of the customer to be updated + /// + /// Sets the *customer 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. + pub fn customer_key(mut self, new_value: &str) -> CustomerPatchCall<'a, C, A> { + self._customer_key = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CustomerPatchCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CustomerPatchCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::DirectoryCustomer`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CustomerPatchCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Retrives a customer. +/// +/// A builder for the *get* method supported by a *customer* resource. +/// It is not used directly, but through a `CustomerMethods` instance. +/// +/// # 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.customers().get("customerKey") +/// .doit(); +/// # } +/// ``` +pub struct CustomerGetCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Directory, + _customer_key: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for CustomerGetCall<'a, C, A> {} + +impl<'a, C, A> CustomerGetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Customer)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.customers.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("customerKey", self._customer_key.to_string())); + for &field in ["alt", "customerKey"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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/customers/{customerKey}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryCustomerReadonly.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{customerKey}", "customerKey")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["customerKey"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Id of the customer to be retrieved + /// + /// Sets the *customer 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. + pub fn customer_key(mut self, new_value: &str) -> CustomerGetCall<'a, C, A> { + self._customer_key = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CustomerGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CustomerGetCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::DirectoryCustomerReadonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CustomerGetCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Updates a customer. +/// +/// A builder for the *update* method supported by a *customer* resource. +/// It is not used directly, but through a `CustomerMethods` instance. +/// +/// # 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::Customer; +/// # #[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 = Customer::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.customers().update(req, "customerKey") +/// .doit(); +/// # } +/// ``` +pub struct CustomerUpdateCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Directory, + _request: Customer, + _customer_key: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for CustomerUpdateCall<'a, C, A> {} + +impl<'a, C, A> CustomerUpdateCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Customer)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.customers.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("customerKey", self._customer_key.to_string())); + for &field in ["alt", "customerKey"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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/customers/{customerKey}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryCustomer.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{customerKey}", "customerKey")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["customerKey"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: Customer) -> CustomerUpdateCall<'a, C, A> { + self._request = new_value; + self + } + /// Id of the customer to be updated + /// + /// Sets the *customer 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. + pub fn customer_key(mut self, new_value: &str) -> CustomerUpdateCall<'a, C, A> { + self._customer_key = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CustomerUpdateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> CustomerUpdateCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::DirectoryCustomer`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CustomerUpdateCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # 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_("invidunt") +/// .org_unit_path("aliquyam") +/// .doit(); +/// # } +/// ``` +pub struct OrgunitListCall<'a, C, A> + where C: '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, A> CallBuilder for OrgunitListCall<'a, C, A> {} + +impl<'a, C, A> OrgunitListCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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::DirectoryOrgunitReadonly.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Immutable id of the Google Apps account + /// + /// 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. + pub fn customer_id(mut self, new_value: &str) -> OrgunitListCall<'a, C, A> { + self._customer_id = new_value.to_string(); + self + } + /// Whether to return all sub-organizations or just immediate children + /// + /// Sets the *type* query property to the given value. + pub fn type_(mut self, new_value: &str) -> OrgunitListCall<'a, C, A> { + self._type_ = Some(new_value.to_string()); + self + } + /// the URL-encoded organization unit's path or its Id + /// + /// Sets the *org unit path* query property to the given value. + pub fn org_unit_path(mut self, new_value: &str) -> OrgunitListCall<'a, C, A> { + self._org_unit_path = Some(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> OrgunitListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::DirectoryOrgunitReadonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # 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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: 'a, A: 'a { + + hub: &'a Directory, + _request: OrgUnit, + _customer_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for OrgunitInsertCall<'a, C, A> {} + +impl<'a, C, A> OrgunitInsertCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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::DirectoryOrgunit.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// Immutable id of the Google Apps account + /// + /// 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. + pub fn customer_id(mut self, new_value: &str) -> OrgunitInsertCall<'a, C, A> { + self._customer_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> OrgunitInsertCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::DirectoryOrgunit`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # 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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: '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, A> CallBuilder for OrgunitUpdateCall<'a, C, A> {} + +impl<'a, C, A> OrgunitUpdateCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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::DirectoryOrgunit.as_ref().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 ["orgUnitPath", "customerId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// Immutable id of the Google Apps account + /// + /// 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. + pub fn customer_id(mut self, new_value: &str) -> OrgunitUpdateCall<'a, C, A> { + self._customer_id = new_value.to_string(); + self + } + /// Full path of the organization unit or its Id + /// + /// 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. + pub fn add_org_unit_path(mut self, new_value: &str) -> OrgunitUpdateCall<'a, C, A> { + self._org_unit_path.push(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> OrgunitUpdateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::DirectoryOrgunit`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # 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, A> + where C: '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, A> CallBuilder for OrgunitDeleteCall<'a, C, A> {} + +impl<'a, C, A> OrgunitDeleteCall<'a, C, A> where 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 Err(Error::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::DirectoryOrgunit.as_ref().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 ["orgUnitPath", "customerId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = res; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Immutable id of the Google Apps account + /// + /// 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. + pub fn customer_id(mut self, new_value: &str) -> OrgunitDeleteCall<'a, C, A> { + self._customer_id = new_value.to_string(); + self + } + /// Full path of the organization unit or its Id + /// + /// 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. + pub fn add_org_unit_path(mut self, new_value: &str) -> OrgunitDeleteCall<'a, C, A> { + self._org_unit_path.push(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> OrgunitDeleteCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::DirectoryOrgunit`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # 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, A> + where C: '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, A> CallBuilder for OrgunitGetCall<'a, C, A> {} + +impl<'a, C, A> OrgunitGetCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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::DirectoryOrgunitReadonly.as_ref().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 ["orgUnitPath", "customerId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Immutable id of the Google Apps account + /// + /// 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. + pub fn customer_id(mut self, new_value: &str) -> OrgunitGetCall<'a, C, A> { + self._customer_id = new_value.to_string(); + self + } + /// Full path of the organization unit or its Id + /// + /// 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. + pub fn add_org_unit_path(mut self, new_value: &str) -> OrgunitGetCall<'a, C, A> { + self._org_unit_path.push(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> OrgunitGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::DirectoryOrgunitReadonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # 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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: '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, A> CallBuilder for OrgunitPatchCall<'a, C, A> {} + +impl<'a, C, A> OrgunitPatchCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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::DirectoryOrgunit.as_ref().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 ["orgUnitPath", "customerId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// Immutable id of the Google Apps account + /// + /// 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. + pub fn customer_id(mut self, new_value: &str) -> OrgunitPatchCall<'a, C, A> { + self._customer_id = new_value.to_string(); + self + } + /// Full path of the organization unit or its Id + /// + /// 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. + pub fn add_org_unit_path(mut self, new_value: &str) -> OrgunitPatchCall<'a, C, A> { + self._org_unit_path.push(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> OrgunitPatchCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::DirectoryOrgunit`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # 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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: 'a, A: 'a { + + hub: &'a Directory, + _request: UserUndelete, + _user_key: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for UserUndeleteCall<'a, C, A> {} + +impl<'a, C, A> UserUndeleteCall<'a, C, A> where 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 Err(Error::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::DirectoryUser.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = res; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// The immutable id of the user + /// + /// 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. + pub fn user_key(mut self, new_value: &str) -> UserUndeleteCall<'a, C, A> { + self._user_key = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserUndeleteCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::DirectoryUser`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # 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, A> + where C: 'a, A: 'a { + + hub: &'a Directory, + _user_key: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for UserPhotoDeleteCall<'a, C, A> {} + +impl<'a, C, A> UserPhotoDeleteCall<'a, C, A> where 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 Err(Error::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::DirectoryUser.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = res; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Email or immutable Id of the user + /// + /// 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. + pub fn user_key(mut self, new_value: &str) -> UserPhotoDeleteCall<'a, C, A> { + self._user_key = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserPhotoDeleteCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::DirectoryUser`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # 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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: 'a, A: 'a { + + hub: &'a Directory, + _request: UserPhoto, + _user_key: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for UserPhotoPatchCall<'a, C, A> {} + +impl<'a, C, A> UserPhotoPatchCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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::DirectoryUser.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// Email or immutable Id of the user + /// + /// 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. + pub fn user_key(mut self, new_value: &str) -> UserPhotoPatchCall<'a, C, A> { + self._user_key = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserPhotoPatchCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::DirectoryUser`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # 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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: 'a, A: 'a { + + hub: &'a Directory, + _request: User, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for UserInsertCall<'a, C, A> {} + +impl<'a, C, A> UserInsertCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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::DirectoryUser.as_ref().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserInsertCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::DirectoryUser`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # 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(); +/// +/// // You can configure optional parameters by calling 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("ea") +/// .doit(); +/// # } +/// ``` +pub struct UserAliaseWatchCall<'a, C, A> + where C: '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, A> CallBuilder for UserAliaseWatchCall<'a, C, A> {} + +impl<'a, C, A> UserAliaseWatchCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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::DirectoryUser.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// Email or immutable Id of the user + /// + /// 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. + pub fn user_key(mut self, new_value: &str) -> UserAliaseWatchCall<'a, C, A> { + self._user_key = new_value.to_string(); + self + } + /// Event on which subscription is intended (if subscribing) + /// + /// Sets the *event* query property to the given value. + pub fn event(mut self, new_value: &str) -> UserAliaseWatchCall<'a, C, A> { + self._event = Some(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserAliaseWatchCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::DirectoryUser`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # 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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: 'a, A: 'a { + + hub: &'a Directory, + _request: UserPhoto, + _user_key: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for UserPhotoUpdateCall<'a, C, A> {} + +impl<'a, C, A> UserPhotoUpdateCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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::DirectoryUser.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// Email or immutable Id of the user + /// + /// 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. + pub fn user_key(mut self, new_value: &str) -> UserPhotoUpdateCall<'a, C, A> { + self._user_key = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserPhotoUpdateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::DirectoryUser`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # 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(); +/// +/// // You can configure optional parameters by calling 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("dolor") +/// .sort_order("dolor") +/// .show_deleted("dolor") +/// .query("et") +/// .projection("consetetur") +/// .page_token("amet.") +/// .order_by("voluptua.") +/// .max_results(-56) +/// .event("gubergren") +/// .domain("justo") +/// .customer("sit") +/// .custom_field_mask("vero") +/// .doit(); +/// # } +/// ``` +pub struct UserWatchCall<'a, C, A> + where C: '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, A> CallBuilder for UserWatchCall<'a, C, A> {} + +impl<'a, C, A> UserWatchCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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::DirectoryUser.as_ref().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// Whether to fetch the ADMIN_VIEW or DOMAIN_PUBLIC view of the user. + /// + /// Sets the *view type* query property to the given value. + pub fn view_type(mut self, new_value: &str) -> UserWatchCall<'a, C, A> { + self._view_type = Some(new_value.to_string()); + self + } + /// Whether to return results in ascending or descending order. + /// + /// Sets the *sort order* query property to the given value. + pub fn sort_order(mut self, new_value: &str) -> UserWatchCall<'a, C, A> { + self._sort_order = Some(new_value.to_string()); + self + } + /// If set to true retrieves the list of deleted users. Default is false + /// + /// Sets the *show deleted* query property to the given value. + pub fn show_deleted(mut self, new_value: &str) -> UserWatchCall<'a, C, A> { + self._show_deleted = Some(new_value.to_string()); + self + } + /// Query string search. Should be of the form "". Complete documentation is at https://developers.google.com/admin-sdk/directory/v1/guides/search-users + /// + /// Sets the *query* query property to the given value. + pub fn query(mut self, new_value: &str) -> UserWatchCall<'a, C, A> { + self._query = Some(new_value.to_string()); + self + } + /// What subset of fields to fetch for this user. + /// + /// Sets the *projection* query property to the given value. + pub fn projection(mut self, new_value: &str) -> UserWatchCall<'a, C, A> { + self._projection = Some(new_value.to_string()); + self + } + /// Token to specify next page in the list + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> UserWatchCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Column to use for sorting results + /// + /// Sets the *order by* query property to the given value. + pub fn order_by(mut self, new_value: &str) -> UserWatchCall<'a, C, A> { + self._order_by = Some(new_value.to_string()); + self + } + /// Maximum number of results to return. Default is 100. Max allowed is 500 + /// + /// Sets the *max results* query property to the given value. + pub fn max_results(mut self, new_value: i32) -> UserWatchCall<'a, C, A> { + self._max_results = Some(new_value); + self + } + /// Event on which subscription is intended (if subscribing) + /// + /// Sets the *event* query property to the given value. + pub fn event(mut self, new_value: &str) -> UserWatchCall<'a, C, A> { + self._event = Some(new_value.to_string()); + self + } + /// 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. + /// + /// Sets the *domain* query property to the given value. + pub fn domain(mut self, new_value: &str) -> UserWatchCall<'a, C, A> { + self._domain = Some(new_value.to_string()); + self + } + /// 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. + /// + /// Sets the *customer* query property to the given value. + pub fn customer(mut self, new_value: &str) -> UserWatchCall<'a, C, A> { + self._customer = Some(new_value.to_string()); + self + } + /// Comma-separated list of schema names. All fields from these schemas are fetched. This should only be set when projection=custom. + /// + /// Sets the *custom field mask* query property to the given value. + pub fn custom_field_mask(mut self, new_value: &str) -> UserWatchCall<'a, C, A> { + self._custom_field_mask = Some(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserWatchCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::DirectoryUser`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # 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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: 'a, A: 'a { + + hub: &'a Directory, + _request: User, + _user_key: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for UserUpdateCall<'a, C, A> {} + +impl<'a, C, A> UserUpdateCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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::DirectoryUser.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// Email or immutable Id of the user. If Id, it should match with id of user object + /// + /// 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. + pub fn user_key(mut self, new_value: &str) -> UserUpdateCall<'a, C, A> { + self._user_key = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserUpdateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::DirectoryUser`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # 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, A> + where C: 'a, A: 'a { + + hub: &'a Directory, + _user_key: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for UserPhotoGetCall<'a, C, A> {} + +impl<'a, C, A> UserPhotoGetCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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::DirectoryUserReadonly.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Email or immutable Id of the user + /// + /// 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. + pub fn user_key(mut self, new_value: &str) -> UserPhotoGetCall<'a, C, A> { + self._user_key = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserPhotoGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::DirectoryUserReadonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # 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("consetetur") +/// .sort_order("sadipscing") +/// .show_deleted("vero") +/// .query("sadipscing") +/// .projection("invidunt") +/// .page_token("consetetur") +/// .order_by("dolore") +/// .max_results(-19) +/// .event("aliquyam") +/// .domain("Lorem") +/// .customer("et") +/// .custom_field_mask("clita") +/// .doit(); +/// # } +/// ``` +pub struct UserListCall<'a, C, A> + where C: '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, A> CallBuilder for UserListCall<'a, C, A> {} + +impl<'a, C, A> UserListCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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::DirectoryUserReadonly.as_ref().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Whether to fetch the ADMIN_VIEW or DOMAIN_PUBLIC view of the user. + /// + /// Sets the *view type* query property to the given value. + pub fn view_type(mut self, new_value: &str) -> UserListCall<'a, C, A> { + self._view_type = Some(new_value.to_string()); + self + } + /// Whether to return results in ascending or descending order. + /// + /// Sets the *sort order* query property to the given value. + pub fn sort_order(mut self, new_value: &str) -> UserListCall<'a, C, A> { + self._sort_order = Some(new_value.to_string()); + self + } + /// If set to true retrieves the list of deleted users. Default is false + /// + /// Sets the *show deleted* query property to the given value. + pub fn show_deleted(mut self, new_value: &str) -> UserListCall<'a, C, A> { + self._show_deleted = Some(new_value.to_string()); + self + } + /// Query string search. Should be of the form "". Complete documentation is at https://developers.google.com/admin-sdk/directory/v1/guides/search-users + /// + /// Sets the *query* query property to the given value. + pub fn query(mut self, new_value: &str) -> UserListCall<'a, C, A> { + self._query = Some(new_value.to_string()); + self + } + /// What subset of fields to fetch for this user. + /// + /// Sets the *projection* query property to the given value. + pub fn projection(mut self, new_value: &str) -> UserListCall<'a, C, A> { + self._projection = Some(new_value.to_string()); + self + } + /// Token to specify next page in the list + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> UserListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Column to use for sorting results + /// + /// Sets the *order by* query property to the given value. + pub fn order_by(mut self, new_value: &str) -> UserListCall<'a, C, A> { + self._order_by = Some(new_value.to_string()); + self + } + /// Maximum number of results to return. Default is 100. Max allowed is 500 + /// + /// Sets the *max results* query property to the given value. + pub fn max_results(mut self, new_value: i32) -> UserListCall<'a, C, A> { + self._max_results = Some(new_value); + self + } + /// Event on which subscription is intended (if subscribing) + /// + /// Sets the *event* query property to the given value. + pub fn event(mut self, new_value: &str) -> UserListCall<'a, C, A> { + self._event = Some(new_value.to_string()); + self + } + /// 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. + /// + /// Sets the *domain* query property to the given value. + pub fn domain(mut self, new_value: &str) -> UserListCall<'a, C, A> { + self._domain = Some(new_value.to_string()); + self + } + /// 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. + /// + /// Sets the *customer* query property to the given value. + pub fn customer(mut self, new_value: &str) -> UserListCall<'a, C, A> { + self._customer = Some(new_value.to_string()); + self + } + /// Comma-separated list of schema names. All fields from these schemas are fetched. This should only be set when projection=custom. + /// + /// Sets the *custom field mask* query property to the given value. + pub fn custom_field_mask(mut self, new_value: &str) -> UserListCall<'a, C, A> { + self._custom_field_mask = Some(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::DirectoryUserReadonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # 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("takimata") +/// .projection("nonumy") +/// .custom_field_mask("kasd") +/// .doit(); +/// # } +/// ``` +pub struct UserGetCall<'a, C, A> + where C: '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, A> CallBuilder for UserGetCall<'a, C, A> {} + +impl<'a, C, A> UserGetCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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::DirectoryUserReadonly.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Email or immutable Id of the user + /// + /// 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. + pub fn user_key(mut self, new_value: &str) -> UserGetCall<'a, C, A> { + self._user_key = new_value.to_string(); + self + } + /// Whether to fetch the ADMIN_VIEW or DOMAIN_PUBLIC view of the user. + /// + /// Sets the *view type* query property to the given value. + pub fn view_type(mut self, new_value: &str) -> UserGetCall<'a, C, A> { + self._view_type = Some(new_value.to_string()); + self + } + /// What subset of fields to fetch for this user. + /// + /// Sets the *projection* query property to the given value. + pub fn projection(mut self, new_value: &str) -> UserGetCall<'a, C, A> { + self._projection = Some(new_value.to_string()); + self + } + /// Comma-separated list of schema names. All fields from these schemas are fetched. This should only be set when projection=custom. + /// + /// Sets the *custom field mask* query property to the given value. + pub fn custom_field_mask(mut self, new_value: &str) -> UserGetCall<'a, C, A> { + self._custom_field_mask = Some(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::DirectoryUserReadonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # 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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: 'a, A: 'a { + + hub: &'a Directory, + _request: Alias, + _user_key: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for UserAliaseInsertCall<'a, C, A> {} + +impl<'a, C, A> UserAliaseInsertCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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::DirectoryUser.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// Email or immutable Id of the user + /// + /// 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. + pub fn user_key(mut self, new_value: &str) -> UserAliaseInsertCall<'a, C, A> { + self._user_key = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserAliaseInsertCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::DirectoryUser`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # 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("At") +/// .doit(); +/// # } +/// ``` +pub struct UserAliaseListCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Directory, + _user_key: String, + _event: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for UserAliaseListCall<'a, C, A> {} + +impl<'a, C, A> UserAliaseListCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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::DirectoryUserAliaReadonly.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Email or immutable Id of the user + /// + /// 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. + pub fn user_key(mut self, new_value: &str) -> UserAliaseListCall<'a, C, A> { + self._user_key = new_value.to_string(); + self + } + /// Event on which subscription is intended (if subscribing) + /// + /// Sets the *event* query property to the given value. + pub fn event(mut self, new_value: &str) -> UserAliaseListCall<'a, C, A> { + self._event = Some(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserAliaseListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::DirectoryUserAliaReadonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # 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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: 'a, A: 'a { + + hub: &'a Directory, + _request: UserMakeAdmin, + _user_key: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for UserMakeAdminCall<'a, C, A> {} + +impl<'a, C, A> UserMakeAdminCall<'a, C, A> where 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 Err(Error::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::DirectoryUser.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = res; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// Email or immutable Id of the user as admin + /// + /// 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. + pub fn user_key(mut self, new_value: &str) -> UserMakeAdminCall<'a, C, A> { + self._user_key = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserMakeAdminCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::DirectoryUser`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # 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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: 'a, A: 'a { + + hub: &'a Directory, + _request: User, + _user_key: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for UserPatchCall<'a, C, A> {} + +impl<'a, C, A> UserPatchCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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::DirectoryUser.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// Email or immutable Id of the user. If Id, it should match with id of user object + /// + /// 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. + pub fn user_key(mut self, new_value: &str) -> UserPatchCall<'a, C, A> { + self._user_key = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserPatchCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::DirectoryUser`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # 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, A> + where C: 'a, A: 'a { + + hub: &'a Directory, + _user_key: String, + _alias: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for UserAliaseDeleteCall<'a, C, A> {} + +impl<'a, C, A> UserAliaseDeleteCall<'a, C, A> where 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 Err(Error::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::DirectoryUser.as_ref().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 ["alias", "userKey"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = res; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Email or immutable Id of the user + /// + /// 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. + pub fn user_key(mut self, new_value: &str) -> UserAliaseDeleteCall<'a, C, A> { + self._user_key = new_value.to_string(); + self + } + /// The alias to be removed + /// + /// 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. + pub fn alias(mut self, new_value: &str) -> UserAliaseDeleteCall<'a, C, A> { + self._alias = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserAliaseDeleteCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::DirectoryUser`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # 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, A> + where C: 'a, A: 'a { + + hub: &'a Directory, + _user_key: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for UserDeleteCall<'a, C, A> {} + +impl<'a, C, A> UserDeleteCall<'a, C, A> where 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 Err(Error::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::DirectoryUser.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = res; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Email or immutable Id of the user + /// + /// 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. + pub fn user_key(mut self, new_value: &str) -> UserDeleteCall<'a, C, A> { + self._user_key = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserDeleteCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::DirectoryUser`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Updates a role. +/// +/// A builder for the *update* method supported by a *role* resource. +/// It is not used directly, but through a `RoleMethods` instance. +/// +/// # 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::Role; +/// # #[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 = Role::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.roles().update(req, "customer", "roleId") +/// .doit(); +/// # } +/// ``` +pub struct RoleUpdateCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Directory, + _request: Role, + _customer: String, + _role_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for RoleUpdateCall<'a, C, A> {} + +impl<'a, C, A> RoleUpdateCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Role)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.roles.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(("roleId", self._role_id.to_string())); + for &field in ["alt", "customer", "roleId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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}/roles/{roleId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryRolemanagement.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{customer}", "customer"), ("{roleId}", "roleId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["roleId", "customer"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: Role) -> RoleUpdateCall<'a, C, A> { + self._request = new_value; + self + } + /// Immutable ID of the Google Apps account. + /// + /// 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. + pub fn customer(mut self, new_value: &str) -> RoleUpdateCall<'a, C, A> { + self._customer = new_value.to_string(); + self + } + /// Immutable ID of the role. + /// + /// Sets the *role id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn role_id(mut self, new_value: &str) -> RoleUpdateCall<'a, C, A> { + self._role_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> RoleUpdateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> RoleUpdateCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::DirectoryRolemanagement`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> RoleUpdateCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Retrieves a role. +/// +/// A builder for the *get* method supported by a *role* resource. +/// It is not used directly, but through a `RoleMethods` instance. +/// +/// # 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.roles().get("customer", "roleId") +/// .doit(); +/// # } +/// ``` +pub struct RoleGetCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Directory, + _customer: String, + _role_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for RoleGetCall<'a, C, A> {} + +impl<'a, C, A> RoleGetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Role)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.roles.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(("roleId", self._role_id.to_string())); + for &field in ["alt", "customer", "roleId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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}/roles/{roleId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryRolemanagementReadonly.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{customer}", "customer"), ("{roleId}", "roleId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["roleId", "customer"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Immutable ID of the Google Apps account. + /// + /// 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. + pub fn customer(mut self, new_value: &str) -> RoleGetCall<'a, C, A> { + self._customer = new_value.to_string(); + self + } + /// Immutable ID of the role. + /// + /// Sets the *role id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn role_id(mut self, new_value: &str) -> RoleGetCall<'a, C, A> { + self._role_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> RoleGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> RoleGetCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::DirectoryRolemanagementReadonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> RoleGetCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Deletes a role. +/// +/// A builder for the *delete* method supported by a *role* resource. +/// It is not used directly, but through a `RoleMethods` instance. +/// +/// # 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.roles().delete("customer", "roleId") +/// .doit(); +/// # } +/// ``` +pub struct RoleDeleteCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Directory, + _customer: String, + _role_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for RoleDeleteCall<'a, C, A> {} + +impl<'a, C, A> RoleDeleteCall<'a, C, A> where 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.roles.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(("roleId", self._role_id.to_string())); + for &field in ["customer", "roleId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::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}/roles/{roleId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryRolemanagement.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{customer}", "customer"), ("{roleId}", "roleId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["roleId", "customer"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = res; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Immutable ID of the Google Apps account. + /// + /// 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. + pub fn customer(mut self, new_value: &str) -> RoleDeleteCall<'a, C, A> { + self._customer = new_value.to_string(); + self + } + /// Immutable ID of the role. + /// + /// Sets the *role id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn role_id(mut self, new_value: &str) -> RoleDeleteCall<'a, C, A> { + self._role_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> RoleDeleteCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> RoleDeleteCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::DirectoryRolemanagement`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> RoleDeleteCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Updates a role. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *role* resource. +/// It is not used directly, but through a `RoleMethods` instance. +/// +/// # 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::Role; +/// # #[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 = Role::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.roles().patch(req, "customer", "roleId") +/// .doit(); +/// # } +/// ``` +pub struct RolePatchCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Directory, + _request: Role, + _customer: String, + _role_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for RolePatchCall<'a, C, A> {} + +impl<'a, C, A> RolePatchCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Role)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.roles.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(("roleId", self._role_id.to_string())); + for &field in ["alt", "customer", "roleId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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}/roles/{roleId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryRolemanagement.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{customer}", "customer"), ("{roleId}", "roleId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["roleId", "customer"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: Role) -> RolePatchCall<'a, C, A> { + self._request = new_value; + self + } + /// Immutable ID of the Google Apps account. + /// + /// 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. + pub fn customer(mut self, new_value: &str) -> RolePatchCall<'a, C, A> { + self._customer = new_value.to_string(); + self + } + /// Immutable ID of the role. + /// + /// Sets the *role id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn role_id(mut self, new_value: &str) -> RolePatchCall<'a, C, A> { + self._role_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> RolePatchCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> RolePatchCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::DirectoryRolemanagement`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> RolePatchCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Creates a role. +/// +/// A builder for the *insert* method supported by a *role* resource. +/// It is not used directly, but through a `RoleMethods` instance. +/// +/// # 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::Role; +/// # #[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 = Role::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.roles().insert(req, "customer") +/// .doit(); +/// # } +/// ``` +pub struct RoleInsertCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Directory, + _request: Role, + _customer: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for RoleInsertCall<'a, C, A> {} + +impl<'a, C, A> RoleInsertCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Role)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.roles.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("customer", self._customer.to_string())); + for &field in ["alt", "customer"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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}/roles".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryRolemanagement.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: Role) -> RoleInsertCall<'a, C, A> { + self._request = new_value; + self + } + /// Immutable ID of the Google Apps account. + /// + /// 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. + pub fn customer(mut self, new_value: &str) -> RoleInsertCall<'a, C, A> { + self._customer = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> RoleInsertCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> RoleInsertCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::DirectoryRolemanagement`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> RoleInsertCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Retrieves a paginated list of all the roles in a domain. +/// +/// A builder for the *list* method supported by a *role* resource. +/// It is not used directly, but through a `RoleMethods` instance. +/// +/// # 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.roles().list("customer") +/// .page_token("gubergren") +/// .max_results(-82) +/// .doit(); +/// # } +/// ``` +pub struct RoleListCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Directory, + _customer: String, + _page_token: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for RoleListCall<'a, C, A> {} + +impl<'a, C, A> RoleListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Roles)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.roles.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + 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())); + } + for &field in ["alt", "customer", "pageToken", "maxResults"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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}/roles".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryRolemanagementReadonly.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Immutable id of the Google Apps account. + /// + /// 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. + pub fn customer(mut self, new_value: &str) -> RoleListCall<'a, C, A> { + self._customer = new_value.to_string(); + self + } + /// Token to specify the next page in the list. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> RoleListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Maximum number of results to return. + /// + /// Sets the *max results* query property to the given value. + pub fn max_results(mut self, new_value: i32) -> RoleListCall<'a, C, A> { + self._max_results = Some(new_value); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> RoleListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> RoleListCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::DirectoryRolemanagementReadonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> RoleListCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Retrieves a paginated list of all privileges for a customer. +/// +/// A builder for the *list* method supported by a *privilege* resource. +/// It is not used directly, but through a `PrivilegeMethods` instance. +/// +/// # 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.privileges().list("customer") +/// .doit(); +/// # } +/// ``` +pub struct PrivilegeListCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Directory, + _customer: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for PrivilegeListCall<'a, C, A> {} + +impl<'a, C, A> PrivilegeListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Privileges)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.privileges.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("customer", self._customer.to_string())); + for &field in ["alt", "customer"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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}/roles/ALL/privileges".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryRolemanagementReadonly.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Immutable ID of the Google Apps account. + /// + /// 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. + pub fn customer(mut self, new_value: &str) -> PrivilegeListCall<'a, C, A> { + self._customer = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PrivilegeListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PrivilegeListCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::DirectoryRolemanagementReadonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PrivilegeListCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # 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("labore") +/// .doit(); +/// # } +/// ``` +pub struct MobiledeviceGetCall<'a, C, A> + where C: '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, A> CallBuilder for MobiledeviceGetCall<'a, C, A> {} + +impl<'a, C, A> MobiledeviceGetCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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::DirectoryDeviceMobileReadonly.as_ref().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 ["resourceId", "customerId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Immutable id of the Google Apps account + /// + /// 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. + pub fn customer_id(mut self, new_value: &str) -> MobiledeviceGetCall<'a, C, A> { + self._customer_id = new_value.to_string(); + self + } + /// Immutable id of Mobile Device + /// + /// 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. + pub fn resource_id(mut self, new_value: &str) -> MobiledeviceGetCall<'a, C, A> { + self._resource_id = new_value.to_string(); + self + } + /// Restrict information returned to a set of selected fields. + /// + /// Sets the *projection* query property to the given value. + pub fn projection(mut self, new_value: &str) -> MobiledeviceGetCall<'a, C, A> { + self._projection = Some(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> MobiledeviceGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::DirectoryDeviceMobileReadonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # 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("aliquyam") +/// .query("dolores") +/// .projection("sit") +/// .page_token("diam") +/// .order_by("ut") +/// .max_results(-70) +/// .doit(); +/// # } +/// ``` +pub struct MobiledeviceListCall<'a, C, A> + where C: '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, A> CallBuilder for MobiledeviceListCall<'a, C, A> {} + +impl<'a, C, A> MobiledeviceListCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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::DirectoryDeviceMobileReadonly.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Immutable id of the Google Apps account + /// + /// 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. + pub fn customer_id(mut self, new_value: &str) -> MobiledeviceListCall<'a, C, A> { + self._customer_id = new_value.to_string(); + self + } + /// Whether to return results in ascending or descending order. Only of use when orderBy is also used + /// + /// Sets the *sort order* query property to the given value. + pub fn sort_order(mut self, new_value: &str) -> MobiledeviceListCall<'a, C, A> { + self._sort_order = Some(new_value.to_string()); + self + } + /// Search string in the format given at http://support.google.com/a/bin/answer.py?hl=en&answer=1408863#search + /// + /// Sets the *query* query property to the given value. + pub fn query(mut self, new_value: &str) -> MobiledeviceListCall<'a, C, A> { + self._query = Some(new_value.to_string()); + self + } + /// Restrict information returned to a set of selected fields. + /// + /// Sets the *projection* query property to the given value. + pub fn projection(mut self, new_value: &str) -> MobiledeviceListCall<'a, C, A> { + self._projection = Some(new_value.to_string()); + self + } + /// Token to specify next page in the list + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> MobiledeviceListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Column to use for sorting results + /// + /// Sets the *order by* query property to the given value. + pub fn order_by(mut self, new_value: &str) -> MobiledeviceListCall<'a, C, A> { + self._order_by = Some(new_value.to_string()); + self + } + /// Maximum number of results to return. Default is 100 + /// + /// Sets the *max results* query property to the given value. + pub fn max_results(mut self, new_value: i32) -> MobiledeviceListCall<'a, C, A> { + self._max_results = Some(new_value); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> MobiledeviceListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::DirectoryDeviceMobileReadonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # 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, A> + where C: '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, A> CallBuilder for MobiledeviceDeleteCall<'a, C, A> {} + +impl<'a, C, A> MobiledeviceDeleteCall<'a, C, A> where 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 Err(Error::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::DirectoryDeviceMobile.as_ref().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 ["resourceId", "customerId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = res; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Immutable id of the Google Apps account + /// + /// 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. + pub fn customer_id(mut self, new_value: &str) -> MobiledeviceDeleteCall<'a, C, A> { + self._customer_id = new_value.to_string(); + self + } + /// Immutable id of Mobile Device + /// + /// 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. + pub fn resource_id(mut self, new_value: &str) -> MobiledeviceDeleteCall<'a, C, A> { + self._resource_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> MobiledeviceDeleteCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::DirectoryDeviceMobile`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # 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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: '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, A> CallBuilder for MobiledeviceActionCall<'a, C, A> {} + +impl<'a, C, A> MobiledeviceActionCall<'a, C, A> where 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 Err(Error::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::DirectoryDeviceMobile.as_ref().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 ["resourceId", "customerId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = res; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// Immutable id of the Google Apps account + /// + /// 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. + pub fn customer_id(mut self, new_value: &str) -> MobiledeviceActionCall<'a, C, A> { + self._customer_id = new_value.to_string(); + self + } + /// Immutable id of Mobile Device + /// + /// 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. + pub fn resource_id(mut self, new_value: &str) -> MobiledeviceActionCall<'a, C, A> { + self._resource_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> MobiledeviceActionCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::DirectoryDeviceMobile`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + /// Get information about an access token issued by a user. /// /// A builder for the *get* method supported by a *token* resource. @@ -3994,500 +17812,10 @@ impl<'a, C, A> TokenDeleteCall<'a, C, A> where C: BorrowMut, A: o } -/// Stop watching resources through this channel +/// Retrieves a list of notifications. /// -/// A builder for the *stop* method supported by a *channel* resource. -/// It is not used directly, but through a `ChannelMethods` instance. -/// -/// # 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(); -/// -/// // You can configure optional parameters by calling 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, A> - where C: 'a, A: 'a { - - hub: &'a Directory, - _request: Channel, - _delegate: Option<&'a mut Delegate>, - _additional_params: HashMap, - _scopes: BTreeMap -} - -impl<'a, C, A> CallBuilder for ChannelStopCall<'a, C, A> {} - -impl<'a, C, A> ChannelStopCall<'a, C, A> where 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 Err(Error::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::DirectoryUser.as_ref().to_string(), ()); - } - - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); - let mut request_value_reader = - { - let mut value = json::value::to_value(&self._request); - remove_json_null_values(&mut value); - let mut dst = io::Cursor::new(Vec::with_capacity(128)); - json::to_writer(&mut dst, &value).unwrap(); - dst - }; - let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); - request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_token }); - request_value_reader.seek(io::SeekFrom::Start(0)).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) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()) - .header(ContentType(json_mime_type.clone())) - .header(ContentLength(request_size as u64)) - .body(&mut request_value_reader); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = res; - - dlg.finished(true); - return Ok(result_value) - } - } - } - } - - - /// - /// Sets the *request* property to the given value. - /// - /// Even though 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, A> { - self._request = new_value; - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> ChannelStopCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. - /// * *fields* (query-string) - Selector specifying which 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, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::DirectoryUser`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing 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, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().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` instance. -/// -/// # 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(); -/// -/// // You can configure optional parameters by calling 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, A> - where C: 'a, A: 'a { - - hub: &'a Directory, - _request: OrgUnit, - _customer_id: String, - _delegate: Option<&'a mut Delegate>, - _additional_params: HashMap, - _scopes: BTreeMap -} - -impl<'a, C, A> CallBuilder for OrgunitInsertCall<'a, C, A> {} - -impl<'a, C, A> OrgunitInsertCall<'a, C, A> where 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 Err(Error::FieldClash(field)); - } - } - for (name, 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::DirectoryOrgunit.as_ref().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() { - if let Some(index) = params.iter().position(|t| &t.0 == param_name) { - indices_for_removal.push(index); - } - } - for &index in indices_for_removal.iter() { - params.remove(index); - } - } - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); - let mut request_value_reader = - { - let mut value = json::value::to_value(&self._request); - remove_json_null_values(&mut value); - let mut dst = io::Cursor::new(Vec::with_capacity(128)); - json::to_writer(&mut dst, &value).unwrap(); - dst - }; - let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); - request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_token }); - request_value_reader.seek(io::SeekFrom::Start(0)).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) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()) - .header(ContentType(json_mime_type.clone())) - .header(ContentLength(request_size as u64)) - .body(&mut request_value_reader); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = { - let mut json_response = String::new(); - res.read_to_string(&mut json_response).unwrap(); - match json::from_str(&json_response) { - Ok(decoded) => (res, decoded), - Err(err) => { - dlg.response_json_decode_error(&json_response, &err); - return Err(Error::JsonDecodeError(json_response, err)); - } - } - }; - - dlg.finished(true); - return Ok(result_value) - } - } - } - } - - - /// - /// Sets the *request* property to the given value. - /// - /// Even though 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, A> { - self._request = new_value; - self - } - /// Immutable id of the Google Apps account - /// - /// 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. - pub fn customer_id(mut self, new_value: &str) -> OrgunitInsertCall<'a, C, A> { - self._customer_id = new_value.to_string(); - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> OrgunitInsertCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. - /// * *fields* (query-string) - Selector specifying which 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, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::DirectoryOrgunit`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing 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, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().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` instance. +/// A builder for the *list* method supported by a *notification* resource. +/// It is not used directly, but through a `NotificationMethods` instance. /// /// # Example /// @@ -4510,2626 +17838,33 @@ impl<'a, C, A> OrgunitInsertCall<'a, C, A> where C: BorrowMut, A: /// // You can configure optional parameters by calling 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_("sea") -/// .org_unit_path("Lorem") +/// let result = hub.notifications().list("customer") +/// .page_token("dolores") +/// .max_results(77) +/// .language("voluptua.") /// .doit(); /// # } /// ``` -pub struct OrgunitListCall<'a, C, A> +pub struct NotificationListCall<'a, C, A> where C: '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, A> CallBuilder for OrgunitListCall<'a, C, A> {} - -impl<'a, C, A> OrgunitListCall<'a, C, A> where 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 Err(Error::FieldClash(field)); - } - } - for (name, 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::DirectoryOrgunitReadonly.as_ref().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() { - if let Some(index) = params.iter().position(|t| &t.0 == param_name) { - indices_for_removal.push(index); - } - } - for &index in indices_for_removal.iter() { - params.remove(index); - } - } - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_token }); - let mut req_result = { - let mut client = &mut *self.hub.client.borrow_mut(); - let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = { - let mut json_response = String::new(); - res.read_to_string(&mut json_response).unwrap(); - match json::from_str(&json_response) { - Ok(decoded) => (res, decoded), - Err(err) => { - dlg.response_json_decode_error(&json_response, &err); - return Err(Error::JsonDecodeError(json_response, err)); - } - } - }; - - dlg.finished(true); - return Ok(result_value) - } - } - } - } - - - /// Immutable id of the Google Apps account - /// - /// 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. - pub fn customer_id(mut self, new_value: &str) -> OrgunitListCall<'a, C, A> { - self._customer_id = new_value.to_string(); - self - } - /// Whether to return all sub-organizations or just immediate children - /// - /// Sets the *type* query property to the given value. - pub fn type_(mut self, new_value: &str) -> OrgunitListCall<'a, C, A> { - self._type_ = Some(new_value.to_string()); - self - } - /// the URL-encoded organization unit's path or its Id - /// - /// Sets the *org unit path* query property to the given value. - pub fn org_unit_path(mut self, new_value: &str) -> OrgunitListCall<'a, C, A> { - self._org_unit_path = Some(new_value.to_string()); - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> OrgunitListCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. - /// * *fields* (query-string) - Selector specifying which 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, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::DirectoryOrgunitReadonly`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing 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, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().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` instance. -/// -/// # 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, A> - where C: '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, A> CallBuilder for OrgunitGetCall<'a, C, A> {} - -impl<'a, C, A> OrgunitGetCall<'a, C, A> where 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 Err(Error::FieldClash(field)); - } - } - for (name, 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::DirectoryOrgunitReadonly.as_ref().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 ["orgUnitPath", "customerId"].iter() { - if let Some(index) = params.iter().position(|t| &t.0 == param_name) { - indices_for_removal.push(index); - } - } - for &index in indices_for_removal.iter() { - params.remove(index); - } - } - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_token }); - let mut req_result = { - let mut client = &mut *self.hub.client.borrow_mut(); - let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = { - let mut json_response = String::new(); - res.read_to_string(&mut json_response).unwrap(); - match json::from_str(&json_response) { - Ok(decoded) => (res, decoded), - Err(err) => { - dlg.response_json_decode_error(&json_response, &err); - return Err(Error::JsonDecodeError(json_response, err)); - } - } - }; - - dlg.finished(true); - return Ok(result_value) - } - } - } - } - - - /// Immutable id of the Google Apps account - /// - /// 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. - pub fn customer_id(mut self, new_value: &str) -> OrgunitGetCall<'a, C, A> { - self._customer_id = new_value.to_string(); - self - } - /// Full path of the organization unit or its Id - /// - /// 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. - pub fn add_org_unit_path(mut self, new_value: &str) -> OrgunitGetCall<'a, C, A> { - self._org_unit_path.push(new_value.to_string()); - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> OrgunitGetCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. - /// * *fields* (query-string) - Selector specifying which 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, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::DirectoryOrgunitReadonly`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing 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, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().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` instance. -/// -/// # 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(); -/// -/// // You can configure optional parameters by calling 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, A> - where C: '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, A> CallBuilder for OrgunitUpdateCall<'a, C, A> {} - -impl<'a, C, A> OrgunitUpdateCall<'a, C, A> where 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 Err(Error::FieldClash(field)); - } - } - for (name, 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::DirectoryOrgunit.as_ref().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 ["orgUnitPath", "customerId"].iter() { - if let Some(index) = params.iter().position(|t| &t.0 == param_name) { - indices_for_removal.push(index); - } - } - for &index in indices_for_removal.iter() { - params.remove(index); - } - } - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); - let mut request_value_reader = - { - let mut value = json::value::to_value(&self._request); - remove_json_null_values(&mut value); - let mut dst = io::Cursor::new(Vec::with_capacity(128)); - json::to_writer(&mut dst, &value).unwrap(); - dst - }; - let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); - request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_token }); - request_value_reader.seek(io::SeekFrom::Start(0)).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) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()) - .header(ContentType(json_mime_type.clone())) - .header(ContentLength(request_size as u64)) - .body(&mut request_value_reader); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = { - let mut json_response = String::new(); - res.read_to_string(&mut json_response).unwrap(); - match json::from_str(&json_response) { - Ok(decoded) => (res, decoded), - Err(err) => { - dlg.response_json_decode_error(&json_response, &err); - return Err(Error::JsonDecodeError(json_response, err)); - } - } - }; - - dlg.finished(true); - return Ok(result_value) - } - } - } - } - - - /// - /// Sets the *request* property to the given value. - /// - /// Even though 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, A> { - self._request = new_value; - self - } - /// Immutable id of the Google Apps account - /// - /// 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. - pub fn customer_id(mut self, new_value: &str) -> OrgunitUpdateCall<'a, C, A> { - self._customer_id = new_value.to_string(); - self - } - /// Full path of the organization unit or its Id - /// - /// 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. - pub fn add_org_unit_path(mut self, new_value: &str) -> OrgunitUpdateCall<'a, C, A> { - self._org_unit_path.push(new_value.to_string()); - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> OrgunitUpdateCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. - /// * *fields* (query-string) - Selector specifying which 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, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::DirectoryOrgunit`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing 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, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().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` instance. -/// -/// # 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, A> - where C: '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, A> CallBuilder for OrgunitDeleteCall<'a, C, A> {} - -impl<'a, C, A> OrgunitDeleteCall<'a, C, A> where 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 Err(Error::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::DirectoryOrgunit.as_ref().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 ["orgUnitPath", "customerId"].iter() { - if let Some(index) = params.iter().position(|t| &t.0 == param_name) { - indices_for_removal.push(index); - } - } - for &index in indices_for_removal.iter() { - params.remove(index); - } - } - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_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) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = res; - - dlg.finished(true); - return Ok(result_value) - } - } - } - } - - - /// Immutable id of the Google Apps account - /// - /// 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. - pub fn customer_id(mut self, new_value: &str) -> OrgunitDeleteCall<'a, C, A> { - self._customer_id = new_value.to_string(); - self - } - /// Full path of the organization unit or its Id - /// - /// 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. - pub fn add_org_unit_path(mut self, new_value: &str) -> OrgunitDeleteCall<'a, C, A> { - self._org_unit_path.push(new_value.to_string()); - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> OrgunitDeleteCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. - /// * *fields* (query-string) - Selector specifying which 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, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::DirectoryOrgunit`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing 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, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().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` instance. -/// -/// # 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(); -/// -/// // You can configure optional parameters by calling 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, A> - where C: '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, A> CallBuilder for OrgunitPatchCall<'a, C, A> {} - -impl<'a, C, A> OrgunitPatchCall<'a, C, A> where 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 Err(Error::FieldClash(field)); - } - } - for (name, 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::DirectoryOrgunit.as_ref().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 ["orgUnitPath", "customerId"].iter() { - if let Some(index) = params.iter().position(|t| &t.0 == param_name) { - indices_for_removal.push(index); - } - } - for &index in indices_for_removal.iter() { - params.remove(index); - } - } - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); - let mut request_value_reader = - { - let mut value = json::value::to_value(&self._request); - remove_json_null_values(&mut value); - let mut dst = io::Cursor::new(Vec::with_capacity(128)); - json::to_writer(&mut dst, &value).unwrap(); - dst - }; - let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); - request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_token }); - request_value_reader.seek(io::SeekFrom::Start(0)).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) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()) - .header(ContentType(json_mime_type.clone())) - .header(ContentLength(request_size as u64)) - .body(&mut request_value_reader); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = { - let mut json_response = String::new(); - res.read_to_string(&mut json_response).unwrap(); - match json::from_str(&json_response) { - Ok(decoded) => (res, decoded), - Err(err) => { - dlg.response_json_decode_error(&json_response, &err); - return Err(Error::JsonDecodeError(json_response, err)); - } - } - }; - - dlg.finished(true); - return Ok(result_value) - } - } - } - } - - - /// - /// Sets the *request* property to the given value. - /// - /// Even though 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, A> { - self._request = new_value; - self - } - /// Immutable id of the Google Apps account - /// - /// 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. - pub fn customer_id(mut self, new_value: &str) -> OrgunitPatchCall<'a, C, A> { - self._customer_id = new_value.to_string(); - self - } - /// Full path of the organization unit or its Id - /// - /// 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. - pub fn add_org_unit_path(mut self, new_value: &str) -> OrgunitPatchCall<'a, C, A> { - self._org_unit_path.push(new_value.to_string()); - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> OrgunitPatchCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. - /// * *fields* (query-string) - Selector specifying which 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, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::DirectoryOrgunit`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing 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, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().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` instance. -/// -/// # 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(); -/// -/// // You can configure optional parameters by calling 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, A> - where C: 'a, A: 'a { - - hub: &'a Directory, - _request: User, - _delegate: Option<&'a mut Delegate>, - _additional_params: HashMap, - _scopes: BTreeMap -} - -impl<'a, C, A> CallBuilder for UserInsertCall<'a, C, A> {} - -impl<'a, C, A> UserInsertCall<'a, C, A> where 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 Err(Error::FieldClash(field)); - } - } - for (name, 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::DirectoryUser.as_ref().to_string(), ()); - } - - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); - let mut request_value_reader = - { - let mut value = json::value::to_value(&self._request); - remove_json_null_values(&mut value); - let mut dst = io::Cursor::new(Vec::with_capacity(128)); - json::to_writer(&mut dst, &value).unwrap(); - dst - }; - let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); - request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_token }); - request_value_reader.seek(io::SeekFrom::Start(0)).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) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()) - .header(ContentType(json_mime_type.clone())) - .header(ContentLength(request_size as u64)) - .body(&mut request_value_reader); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = { - let mut json_response = String::new(); - res.read_to_string(&mut json_response).unwrap(); - match json::from_str(&json_response) { - Ok(decoded) => (res, decoded), - Err(err) => { - dlg.response_json_decode_error(&json_response, &err); - return Err(Error::JsonDecodeError(json_response, err)); - } - } - }; - - dlg.finished(true); - return Ok(result_value) - } - } - } - } - - - /// - /// Sets the *request* property to the given value. - /// - /// Even though 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, A> { - self._request = new_value; - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserInsertCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. - /// * *fields* (query-string) - Selector specifying which 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, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::DirectoryUser`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing 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, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().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` instance. -/// -/// # 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, A> - where C: 'a, A: 'a { - - hub: &'a Directory, - _user_key: String, - _delegate: Option<&'a mut Delegate>, - _additional_params: HashMap, - _scopes: BTreeMap -} - -impl<'a, C, A> CallBuilder for UserPhotoDeleteCall<'a, C, A> {} - -impl<'a, C, A> UserPhotoDeleteCall<'a, C, A> where 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 Err(Error::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::DirectoryUser.as_ref().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() { - if let Some(index) = params.iter().position(|t| &t.0 == param_name) { - indices_for_removal.push(index); - } - } - for &index in indices_for_removal.iter() { - params.remove(index); - } - } - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_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) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = res; - - dlg.finished(true); - return Ok(result_value) - } - } - } - } - - - /// Email or immutable Id of the user - /// - /// 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. - pub fn user_key(mut self, new_value: &str) -> UserPhotoDeleteCall<'a, C, A> { - self._user_key = new_value.to_string(); - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserPhotoDeleteCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. - /// * *fields* (query-string) - Selector specifying which 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, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::DirectoryUser`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing 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, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().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` instance. -/// -/// # 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(); -/// -/// // You can configure optional parameters by calling 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, A> - where C: 'a, A: 'a { - - hub: &'a Directory, - _request: UserUndelete, - _user_key: String, - _delegate: Option<&'a mut Delegate>, - _additional_params: HashMap, - _scopes: BTreeMap -} - -impl<'a, C, A> CallBuilder for UserUndeleteCall<'a, C, A> {} - -impl<'a, C, A> UserUndeleteCall<'a, C, A> where 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 Err(Error::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::DirectoryUser.as_ref().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() { - if let Some(index) = params.iter().position(|t| &t.0 == param_name) { - indices_for_removal.push(index); - } - } - for &index in indices_for_removal.iter() { - params.remove(index); - } - } - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); - let mut request_value_reader = - { - let mut value = json::value::to_value(&self._request); - remove_json_null_values(&mut value); - let mut dst = io::Cursor::new(Vec::with_capacity(128)); - json::to_writer(&mut dst, &value).unwrap(); - dst - }; - let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); - request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_token }); - request_value_reader.seek(io::SeekFrom::Start(0)).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) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()) - .header(ContentType(json_mime_type.clone())) - .header(ContentLength(request_size as u64)) - .body(&mut request_value_reader); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = res; - - dlg.finished(true); - return Ok(result_value) - } - } - } - } - - - /// - /// Sets the *request* property to the given value. - /// - /// Even though 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, A> { - self._request = new_value; - self - } - /// The immutable id of the user - /// - /// 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. - pub fn user_key(mut self, new_value: &str) -> UserUndeleteCall<'a, C, A> { - self._user_key = new_value.to_string(); - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserUndeleteCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. - /// * *fields* (query-string) - Selector specifying which 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, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::DirectoryUser`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing 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, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().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` instance. -/// -/// # 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(); -/// -/// // You can configure optional parameters by calling 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, A> - where C: 'a, A: 'a { - - hub: &'a Directory, - _request: UserMakeAdmin, - _user_key: String, - _delegate: Option<&'a mut Delegate>, - _additional_params: HashMap, - _scopes: BTreeMap -} - -impl<'a, C, A> CallBuilder for UserMakeAdminCall<'a, C, A> {} - -impl<'a, C, A> UserMakeAdminCall<'a, C, A> where 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 Err(Error::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::DirectoryUser.as_ref().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() { - if let Some(index) = params.iter().position(|t| &t.0 == param_name) { - indices_for_removal.push(index); - } - } - for &index in indices_for_removal.iter() { - params.remove(index); - } - } - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); - let mut request_value_reader = - { - let mut value = json::value::to_value(&self._request); - remove_json_null_values(&mut value); - let mut dst = io::Cursor::new(Vec::with_capacity(128)); - json::to_writer(&mut dst, &value).unwrap(); - dst - }; - let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); - request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_token }); - request_value_reader.seek(io::SeekFrom::Start(0)).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) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()) - .header(ContentType(json_mime_type.clone())) - .header(ContentLength(request_size as u64)) - .body(&mut request_value_reader); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = res; - - dlg.finished(true); - return Ok(result_value) - } - } - } - } - - - /// - /// Sets the *request* property to the given value. - /// - /// Even though 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, A> { - self._request = new_value; - self - } - /// Email or immutable Id of the user as admin - /// - /// 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. - pub fn user_key(mut self, new_value: &str) -> UserMakeAdminCall<'a, C, A> { - self._user_key = new_value.to_string(); - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserMakeAdminCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. - /// * *fields* (query-string) - Selector specifying which 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, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::DirectoryUser`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing 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, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().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` instance. -/// -/// # 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(); -/// -/// // You can configure optional parameters by calling 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, A> - where C: 'a, A: 'a { - - hub: &'a Directory, - _request: User, - _user_key: String, - _delegate: Option<&'a mut Delegate>, - _additional_params: HashMap, - _scopes: BTreeMap -} - -impl<'a, C, A> CallBuilder for UserPatchCall<'a, C, A> {} - -impl<'a, C, A> UserPatchCall<'a, C, A> where 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 Err(Error::FieldClash(field)); - } - } - for (name, 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::DirectoryUser.as_ref().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() { - if let Some(index) = params.iter().position(|t| &t.0 == param_name) { - indices_for_removal.push(index); - } - } - for &index in indices_for_removal.iter() { - params.remove(index); - } - } - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); - let mut request_value_reader = - { - let mut value = json::value::to_value(&self._request); - remove_json_null_values(&mut value); - let mut dst = io::Cursor::new(Vec::with_capacity(128)); - json::to_writer(&mut dst, &value).unwrap(); - dst - }; - let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); - request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_token }); - request_value_reader.seek(io::SeekFrom::Start(0)).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) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()) - .header(ContentType(json_mime_type.clone())) - .header(ContentLength(request_size as u64)) - .body(&mut request_value_reader); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = { - let mut json_response = String::new(); - res.read_to_string(&mut json_response).unwrap(); - match json::from_str(&json_response) { - Ok(decoded) => (res, decoded), - Err(err) => { - dlg.response_json_decode_error(&json_response, &err); - return Err(Error::JsonDecodeError(json_response, err)); - } - } - }; - - dlg.finished(true); - return Ok(result_value) - } - } - } - } - - - /// - /// Sets the *request* property to the given value. - /// - /// Even though 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, A> { - self._request = new_value; - self - } - /// Email or immutable Id of the user. If Id, it should match with id of user object - /// - /// 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. - pub fn user_key(mut self, new_value: &str) -> UserPatchCall<'a, C, A> { - self._user_key = new_value.to_string(); - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserPatchCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. - /// * *fields* (query-string) - Selector specifying which 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, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::DirectoryUser`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing 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, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().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` instance. -/// -/// # 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(); -/// -/// // You can configure optional parameters by calling 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("aliquyam") -/// .sort_order("accusam") -/// .show_deleted("Lorem") -/// .query("sea") -/// .projection("et") -/// .page_token("duo") -/// .order_by("et") -/// .max_results(-40) -/// .event("sanctus") -/// .domain("et") -/// .customer("amet") -/// .custom_field_mask("et") -/// .doit(); -/// # } -/// ``` -pub struct UserWatchCall<'a, C, A> - where C: 'a, A: 'a { - - hub: &'a Directory, - _request: Channel, - _view_type: Option, - _sort_order: Option, - _show_deleted: Option, - _query: Option, - _projection: Option, + _customer: String, _page_token: Option, - _order_by: Option, - _max_results: Option, - _event: Option, - _domain: Option, - _customer: Option, - _custom_field_mask: Option, + _max_results: Option, + _language: Option, _delegate: Option<&'a mut Delegate>, _additional_params: HashMap, _scopes: BTreeMap } -impl<'a, C, A> CallBuilder for UserWatchCall<'a, C, A> {} +impl<'a, C, A> CallBuilder for NotificationListCall<'a, C, A> {} -impl<'a, C, A> UserWatchCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { +impl<'a, C, A> NotificationListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { /// Perform the operation you have build so far. - pub fn doit(mut self) -> Result<(hyper::client::Response, Channel)> { + 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; @@ -7137,866 +17872,20 @@ impl<'a, C, A> UserWatchCall<'a, C, A> where C: BorrowMut, A: oau 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 Err(Error::FieldClash(field)); - } - } - for (name, 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::DirectoryUser.as_ref().to_string(), ()); - } - - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); - let mut request_value_reader = - { - let mut value = json::value::to_value(&self._request); - remove_json_null_values(&mut value); - let mut dst = io::Cursor::new(Vec::with_capacity(128)); - json::to_writer(&mut dst, &value).unwrap(); - dst - }; - let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); - request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_token }); - request_value_reader.seek(io::SeekFrom::Start(0)).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) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()) - .header(ContentType(json_mime_type.clone())) - .header(ContentLength(request_size as u64)) - .body(&mut request_value_reader); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = { - let mut json_response = String::new(); - res.read_to_string(&mut json_response).unwrap(); - match json::from_str(&json_response) { - Ok(decoded) => (res, decoded), - Err(err) => { - dlg.response_json_decode_error(&json_response, &err); - return Err(Error::JsonDecodeError(json_response, err)); - } - } - }; - - dlg.finished(true); - return Ok(result_value) - } - } - } - } - - - /// - /// Sets the *request* property to the given value. - /// - /// Even though 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, A> { - self._request = new_value; - self - } - /// Whether to fetch the ADMIN_VIEW or DOMAIN_PUBLIC view of the user. - /// - /// Sets the *view type* query property to the given value. - pub fn view_type(mut self, new_value: &str) -> UserWatchCall<'a, C, A> { - self._view_type = Some(new_value.to_string()); - self - } - /// Whether to return results in ascending or descending order. - /// - /// Sets the *sort order* query property to the given value. - pub fn sort_order(mut self, new_value: &str) -> UserWatchCall<'a, C, A> { - self._sort_order = Some(new_value.to_string()); - self - } - /// If set to true retrieves the list of deleted users. Default is false - /// - /// Sets the *show deleted* query property to the given value. - pub fn show_deleted(mut self, new_value: &str) -> UserWatchCall<'a, C, A> { - self._show_deleted = Some(new_value.to_string()); - self - } - /// Query string search. Should be of the form "". Complete documentation is at https://developers.google.com/admin-sdk/directory/v1/guides/search-users - /// - /// Sets the *query* query property to the given value. - pub fn query(mut self, new_value: &str) -> UserWatchCall<'a, C, A> { - self._query = Some(new_value.to_string()); - self - } - /// What subset of fields to fetch for this user. - /// - /// Sets the *projection* query property to the given value. - pub fn projection(mut self, new_value: &str) -> UserWatchCall<'a, C, A> { - self._projection = Some(new_value.to_string()); - self - } - /// Token to specify next page in the list - /// - /// Sets the *page token* query property to the given value. - pub fn page_token(mut self, new_value: &str) -> UserWatchCall<'a, C, A> { - self._page_token = Some(new_value.to_string()); - self - } - /// Column to use for sorting results - /// - /// Sets the *order by* query property to the given value. - pub fn order_by(mut self, new_value: &str) -> UserWatchCall<'a, C, A> { - self._order_by = Some(new_value.to_string()); - self - } - /// Maximum number of results to return. Default is 100. Max allowed is 500 - /// - /// Sets the *max results* query property to the given value. - pub fn max_results(mut self, new_value: i32) -> UserWatchCall<'a, C, A> { - self._max_results = Some(new_value); - self - } - /// Event on which subscription is intended (if subscribing) - /// - /// Sets the *event* query property to the given value. - pub fn event(mut self, new_value: &str) -> UserWatchCall<'a, C, A> { - self._event = Some(new_value.to_string()); - self - } - /// 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. - /// - /// Sets the *domain* query property to the given value. - pub fn domain(mut self, new_value: &str) -> UserWatchCall<'a, C, A> { - self._domain = Some(new_value.to_string()); - self - } - /// 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. - /// - /// Sets the *customer* query property to the given value. - pub fn customer(mut self, new_value: &str) -> UserWatchCall<'a, C, A> { - self._customer = Some(new_value.to_string()); - self - } - /// Comma-separated list of schema names. All fields from these schemas are fetched. This should only be set when projection=custom. - /// - /// Sets the *custom field mask* query property to the given value. - pub fn custom_field_mask(mut self, new_value: &str) -> UserWatchCall<'a, C, A> { - self._custom_field_mask = Some(new_value.to_string()); - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserWatchCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. - /// * *fields* (query-string) - Selector specifying which 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, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::DirectoryUser`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing 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, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().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` instance. -/// -/// # 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, A> - where C: 'a, A: 'a { - - hub: &'a Directory, - _user_key: String, - _delegate: Option<&'a mut Delegate>, - _additional_params: HashMap, - _scopes: BTreeMap -} - -impl<'a, C, A> CallBuilder for UserDeleteCall<'a, C, A> {} - -impl<'a, C, A> UserDeleteCall<'a, C, A> where 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 Err(Error::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::DirectoryUser.as_ref().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() { - if let Some(index) = params.iter().position(|t| &t.0 == param_name) { - indices_for_removal.push(index); - } - } - for &index in indices_for_removal.iter() { - params.remove(index); - } - } - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_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) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = res; - - dlg.finished(true); - return Ok(result_value) - } - } - } - } - - - /// Email or immutable Id of the user - /// - /// 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. - pub fn user_key(mut self, new_value: &str) -> UserDeleteCall<'a, C, A> { - self._user_key = new_value.to_string(); - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserDeleteCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. - /// * *fields* (query-string) - Selector specifying which 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, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::DirectoryUser`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing 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, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().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` instance. -/// -/// # 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(); -/// -/// // You can configure optional parameters by calling 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, A> - where C: 'a, A: 'a { - - hub: &'a Directory, - _request: UserPhoto, - _user_key: String, - _delegate: Option<&'a mut Delegate>, - _additional_params: HashMap, - _scopes: BTreeMap -} - -impl<'a, C, A> CallBuilder for UserPhotoUpdateCall<'a, C, A> {} - -impl<'a, C, A> UserPhotoUpdateCall<'a, C, A> where 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 Err(Error::FieldClash(field)); - } - } - for (name, 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::DirectoryUser.as_ref().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() { - if let Some(index) = params.iter().position(|t| &t.0 == param_name) { - indices_for_removal.push(index); - } - } - for &index in indices_for_removal.iter() { - params.remove(index); - } - } - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); - let mut request_value_reader = - { - let mut value = json::value::to_value(&self._request); - remove_json_null_values(&mut value); - let mut dst = io::Cursor::new(Vec::with_capacity(128)); - json::to_writer(&mut dst, &value).unwrap(); - dst - }; - let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); - request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_token }); - request_value_reader.seek(io::SeekFrom::Start(0)).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) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()) - .header(ContentType(json_mime_type.clone())) - .header(ContentLength(request_size as u64)) - .body(&mut request_value_reader); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = { - let mut json_response = String::new(); - res.read_to_string(&mut json_response).unwrap(); - match json::from_str(&json_response) { - Ok(decoded) => (res, decoded), - Err(err) => { - dlg.response_json_decode_error(&json_response, &err); - return Err(Error::JsonDecodeError(json_response, err)); - } - } - }; - - dlg.finished(true); - return Ok(result_value) - } - } - } - } - - - /// - /// Sets the *request* property to the given value. - /// - /// Even though 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, A> { - self._request = new_value; - self - } - /// Email or immutable Id of the user - /// - /// 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. - pub fn user_key(mut self, new_value: &str) -> UserPhotoUpdateCall<'a, C, A> { - self._user_key = new_value.to_string(); - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserPhotoUpdateCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. - /// * *fields* (query-string) - Selector specifying which 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, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::DirectoryUser`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing 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, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().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` instance. -/// -/// # 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("sed") -/// .projection("dolor") -/// .custom_field_mask("dolor") -/// .doit(); -/// # } -/// ``` -pub struct UserGetCall<'a, C, A> - where C: '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, A> CallBuilder for UserGetCall<'a, C, A> {} - -impl<'a, C, A> UserGetCall<'a, C, A> where 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", + 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(("userKey", self._user_key.to_string())); - if let Some(value) = self._view_type { - params.push(("viewType", value.to_string())); + 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._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._custom_field_mask { - params.push(("customFieldMask", value.to_string())); + if let Some(value) = self._language { + params.push(("language", value.to_string())); } - for &field in ["alt", "userKey", "viewType", "projection", "customFieldMask"].iter() { + for &field in ["alt", "customer", "pageToken", "maxResults", "language"].iter() { if self._additional_params.contains_key(field) { dlg.finished(false); return Err(Error::FieldClash(field)); @@ -8008,12 +17897,12 @@ impl<'a, C, A> UserGetCall<'a, C, A> where C: BorrowMut, A: oauth params.push(("alt", "json".to_string())); - let mut url = "https://www.googleapis.com/admin/directory/v1/users/{userKey}".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::DirectoryUserReadonly.as_ref().to_string(), ()); + self._scopes.insert(Scope::DirectoryNotification.as_ref().to_string(), ()); } - for &(find_this, param_name) in [("{userKey}", "userKey")].iter() { + 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 { @@ -8025,7 +17914,7 @@ impl<'a, C, A> UserGetCall<'a, C, A> where C: BorrowMut, A: oauth } { let mut indices_for_removal: Vec = Vec::with_capacity(1); - for param_name in ["userKey"].iter() { + for param_name in ["customer"].iter() { if let Some(index) = params.iter().position(|t| &t.0 == param_name) { indices_for_removal.push(index); } @@ -8112,35 +18001,35 @@ impl<'a, C, A> UserGetCall<'a, C, A> where C: BorrowMut, A: oauth } - /// Email or immutable Id of the user + /// The unique ID for the customer's Google account. /// - /// Sets the *user key* path property to the given 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. - pub fn user_key(mut self, new_value: &str) -> UserGetCall<'a, C, A> { - self._user_key = new_value.to_string(); + pub fn customer(mut self, new_value: &str) -> NotificationListCall<'a, C, A> { + self._customer = new_value.to_string(); self } - /// Whether to fetch the ADMIN_VIEW or DOMAIN_PUBLIC view of the user. + /// The token to specify the page of results to retrieve. /// - /// Sets the *view type* query property to the given value. - pub fn view_type(mut self, new_value: &str) -> UserGetCall<'a, C, A> { - self._view_type = Some(new_value.to_string()); + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> NotificationListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); self } - /// What subset of fields to fetch for this user. + /// Maximum number of notifications to return per page. The default is 100. /// - /// Sets the *projection* query property to the given value. - pub fn projection(mut self, new_value: &str) -> UserGetCall<'a, C, A> { - self._projection = Some(new_value.to_string()); + /// Sets the *max results* query property to the given value. + pub fn max_results(mut self, new_value: u32) -> NotificationListCall<'a, C, A> { + self._max_results = Some(new_value); self } - /// Comma-separated list of schema names. All fields from these schemas are fetched. This should only be set when projection=custom. + /// The ISO 639-1 code of the language notifications are returned in. The default is English (en). /// - /// Sets the *custom field mask* query property to the given value. - pub fn custom_field_mask(mut self, new_value: &str) -> UserGetCall<'a, C, A> { - self._custom_field_mask = Some(new_value.to_string()); + /// Sets the *language* query property to the given value. + pub fn language(mut self, new_value: &str) -> NotificationListCall<'a, C, A> { + self._language = Some(new_value.to_string()); self } /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong @@ -8149,7 +18038,7 @@ impl<'a, C, A> UserGetCall<'a, C, A> where C: BorrowMut, A: oauth /// It should be used to handle progress information, and to implement a certain level of resilience. /// /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserGetCall<'a, C, A> { + pub fn delegate(mut self, new_value: &'a mut Delegate) -> NotificationListCall<'a, C, A> { self._delegate = Some(new_value); self } @@ -8170,7 +18059,7 @@ impl<'a, C, A> UserGetCall<'a, C, A> where C: BorrowMut, A: oauth /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. /// * *fields* (query-string) - Selector specifying which 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, A> + pub fn param(mut self, name: T, value: T) -> NotificationListCall<'a, C, A> where T: AsRef { self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); self @@ -8179,7 +18068,7 @@ impl<'a, C, A> UserGetCall<'a, C, A> where C: BorrowMut, A: oauth /// Identifies the authorization scope for the method you are building. /// /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::DirectoryUserReadonly`. + /// `Scope::DirectoryNotification`. /// /// The `scope` will be added to a set of scopes. This is important as one can maintain access /// tokens for more than one scope. @@ -8187,7 +18076,7 @@ impl<'a, C, A> UserGetCall<'a, C, A> where C: BorrowMut, A: oauth /// Usually there is more than one suitable scope to authorize an operation, some of which may /// encompass more rights than others. For example, for listing 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, A> + pub fn add_scope(mut self, scope: T) -> NotificationListCall<'a, C, A> where T: AsRef { self._scopes.insert(scope.as_ref().to_string(), ()); self @@ -8195,10 +18084,10 @@ impl<'a, C, A> UserGetCall<'a, C, A> where C: BorrowMut, A: oauth } -/// Add a alias for the user +/// Updates a notification. /// -/// A builder for the *aliases.insert* method supported by a *user* resource. -/// It is not used directly, but through a `UserMethods` instance. +/// A builder for the *update* method supported by a *notification* resource. +/// It is not used directly, but through a `NotificationMethods` instance. /// /// # Example /// @@ -8208,7 +18097,7 @@ impl<'a, C, A> UserGetCall<'a, C, A> where C: BorrowMut, A: oauth /// # extern crate hyper; /// # extern crate yup_oauth2 as oauth2; /// # extern crate google_admin1_directory as admin1_directory; -/// use admin1_directory::Alias; +/// use admin1_directory::Notification; /// # #[test] fn egal() { /// # use std::default::Default; /// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; @@ -8222,33 +18111,34 @@ impl<'a, C, A> UserGetCall<'a, C, A> where C: BorrowMut, A: oauth /// // As the method needs a request, you would usually fill it with the desired information /// // into the 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(); +/// let mut req = Notification::default(); /// /// // You can configure optional parameters by calling 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") +/// let result = hub.notifications().update(req, "customer", "notificationId") /// .doit(); /// # } /// ``` -pub struct UserAliaseInsertCall<'a, C, A> +pub struct NotificationUpdateCall<'a, C, A> where C: 'a, A: 'a { hub: &'a Directory, - _request: Alias, - _user_key: String, + _request: Notification, + _customer: String, + _notification_id: String, _delegate: Option<&'a mut Delegate>, _additional_params: HashMap, _scopes: BTreeMap } -impl<'a, C, A> CallBuilder for UserAliaseInsertCall<'a, C, A> {} +impl<'a, C, A> CallBuilder for NotificationUpdateCall<'a, C, A> {} -impl<'a, C, A> UserAliaseInsertCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { +impl<'a, C, A> NotificationUpdateCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { /// Perform the operation you have build so far. - pub fn doit(mut self) -> Result<(hyper::client::Response, Alias)> { + 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; @@ -8256,11 +18146,12 @@ impl<'a, C, A> UserAliaseInsertCall<'a, C, A> where C: BorrowMut, 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() { + 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 Err(Error::FieldClash(field)); @@ -8272,620 +18163,12 @@ impl<'a, C, A> UserAliaseInsertCall<'a, C, A> where C: BorrowMut, params.push(("alt", "json".to_string())); - let mut url = "https://www.googleapis.com/admin/directory/v1/users/{userKey}/aliases".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::DirectoryUser.as_ref().to_string(), ()); + self._scopes.insert(Scope::DirectoryNotification.as_ref().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() { - if let Some(index) = params.iter().position(|t| &t.0 == param_name) { - indices_for_removal.push(index); - } - } - for &index in indices_for_removal.iter() { - params.remove(index); - } - } - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); - let mut request_value_reader = - { - let mut value = json::value::to_value(&self._request); - remove_json_null_values(&mut value); - let mut dst = io::Cursor::new(Vec::with_capacity(128)); - json::to_writer(&mut dst, &value).unwrap(); - dst - }; - let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); - request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_token }); - request_value_reader.seek(io::SeekFrom::Start(0)).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) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()) - .header(ContentType(json_mime_type.clone())) - .header(ContentLength(request_size as u64)) - .body(&mut request_value_reader); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = { - let mut json_response = String::new(); - res.read_to_string(&mut json_response).unwrap(); - match json::from_str(&json_response) { - Ok(decoded) => (res, decoded), - Err(err) => { - dlg.response_json_decode_error(&json_response, &err); - return Err(Error::JsonDecodeError(json_response, err)); - } - } - }; - - dlg.finished(true); - return Ok(result_value) - } - } - } - } - - - /// - /// Sets the *request* property to the given value. - /// - /// Even though 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, A> { - self._request = new_value; - self - } - /// Email or immutable Id of the user - /// - /// 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. - pub fn user_key(mut self, new_value: &str) -> UserAliaseInsertCall<'a, C, A> { - self._user_key = new_value.to_string(); - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserAliaseInsertCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. - /// * *fields* (query-string) - Selector specifying which 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, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::DirectoryUser`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing 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, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().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` instance. -/// -/// # 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("et") -/// .sort_order("consetetur") -/// .show_deleted("amet.") -/// .query("voluptua.") -/// .projection("Lorem") -/// .page_token("gubergren") -/// .order_by("justo") -/// .max_results(-52) -/// .event("vero") -/// .domain("diam") -/// .customer("rebum.") -/// .custom_field_mask("consetetur") -/// .doit(); -/// # } -/// ``` -pub struct UserListCall<'a, C, A> - where C: '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, A> CallBuilder for UserListCall<'a, C, A> {} - -impl<'a, C, A> UserListCall<'a, C, A> where 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 Err(Error::FieldClash(field)); - } - } - for (name, 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::DirectoryUserReadonly.as_ref().to_string(), ()); - } - - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_token }); - let mut req_result = { - let mut client = &mut *self.hub.client.borrow_mut(); - let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = { - let mut json_response = String::new(); - res.read_to_string(&mut json_response).unwrap(); - match json::from_str(&json_response) { - Ok(decoded) => (res, decoded), - Err(err) => { - dlg.response_json_decode_error(&json_response, &err); - return Err(Error::JsonDecodeError(json_response, err)); - } - } - }; - - dlg.finished(true); - return Ok(result_value) - } - } - } - } - - - /// Whether to fetch the ADMIN_VIEW or DOMAIN_PUBLIC view of the user. - /// - /// Sets the *view type* query property to the given value. - pub fn view_type(mut self, new_value: &str) -> UserListCall<'a, C, A> { - self._view_type = Some(new_value.to_string()); - self - } - /// Whether to return results in ascending or descending order. - /// - /// Sets the *sort order* query property to the given value. - pub fn sort_order(mut self, new_value: &str) -> UserListCall<'a, C, A> { - self._sort_order = Some(new_value.to_string()); - self - } - /// If set to true retrieves the list of deleted users. Default is false - /// - /// Sets the *show deleted* query property to the given value. - pub fn show_deleted(mut self, new_value: &str) -> UserListCall<'a, C, A> { - self._show_deleted = Some(new_value.to_string()); - self - } - /// Query string search. Should be of the form "". Complete documentation is at https://developers.google.com/admin-sdk/directory/v1/guides/search-users - /// - /// Sets the *query* query property to the given value. - pub fn query(mut self, new_value: &str) -> UserListCall<'a, C, A> { - self._query = Some(new_value.to_string()); - self - } - /// What subset of fields to fetch for this user. - /// - /// Sets the *projection* query property to the given value. - pub fn projection(mut self, new_value: &str) -> UserListCall<'a, C, A> { - self._projection = Some(new_value.to_string()); - self - } - /// Token to specify next page in the list - /// - /// Sets the *page token* query property to the given value. - pub fn page_token(mut self, new_value: &str) -> UserListCall<'a, C, A> { - self._page_token = Some(new_value.to_string()); - self - } - /// Column to use for sorting results - /// - /// Sets the *order by* query property to the given value. - pub fn order_by(mut self, new_value: &str) -> UserListCall<'a, C, A> { - self._order_by = Some(new_value.to_string()); - self - } - /// Maximum number of results to return. Default is 100. Max allowed is 500 - /// - /// Sets the *max results* query property to the given value. - pub fn max_results(mut self, new_value: i32) -> UserListCall<'a, C, A> { - self._max_results = Some(new_value); - self - } - /// Event on which subscription is intended (if subscribing) - /// - /// Sets the *event* query property to the given value. - pub fn event(mut self, new_value: &str) -> UserListCall<'a, C, A> { - self._event = Some(new_value.to_string()); - self - } - /// 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. - /// - /// Sets the *domain* query property to the given value. - pub fn domain(mut self, new_value: &str) -> UserListCall<'a, C, A> { - self._domain = Some(new_value.to_string()); - self - } - /// 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. - /// - /// Sets the *customer* query property to the given value. - pub fn customer(mut self, new_value: &str) -> UserListCall<'a, C, A> { - self._customer = Some(new_value.to_string()); - self - } - /// Comma-separated list of schema names. All fields from these schemas are fetched. This should only be set when projection=custom. - /// - /// Sets the *custom field mask* query property to the given value. - pub fn custom_field_mask(mut self, new_value: &str) -> UserListCall<'a, C, A> { - self._custom_field_mask = Some(new_value.to_string()); - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserListCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. - /// * *fields* (query-string) - Selector specifying which 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, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::DirectoryUserReadonly`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing 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, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().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` instance. -/// -/// # 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, A> - where C: 'a, A: 'a { - - hub: &'a Directory, - _user_key: String, - _alias: String, - _delegate: Option<&'a mut Delegate>, - _additional_params: HashMap, - _scopes: BTreeMap -} - -impl<'a, C, A> CallBuilder for UserAliaseDeleteCall<'a, C, A> {} - -impl<'a, C, A> UserAliaseDeleteCall<'a, C, A> where 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 Err(Error::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::DirectoryUser.as_ref().to_string(), ()); - } - - for &(find_this, param_name) in [("{userKey}", "userKey"), ("{alias}", "alias")].iter() { + 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 { @@ -8897,250 +18180,7 @@ impl<'a, C, A> UserAliaseDeleteCall<'a, C, A> where C: BorrowMut, } { let mut indices_for_removal: Vec = Vec::with_capacity(2); - for param_name in ["alias", "userKey"].iter() { - if let Some(index) = params.iter().position(|t| &t.0 == param_name) { - indices_for_removal.push(index); - } - } - for &index in indices_for_removal.iter() { - params.remove(index); - } - } - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_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) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = res; - - dlg.finished(true); - return Ok(result_value) - } - } - } - } - - - /// Email or immutable Id of the user - /// - /// 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. - pub fn user_key(mut self, new_value: &str) -> UserAliaseDeleteCall<'a, C, A> { - self._user_key = new_value.to_string(); - self - } - /// The alias to be removed - /// - /// 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. - pub fn alias(mut self, new_value: &str) -> UserAliaseDeleteCall<'a, C, A> { - self._alias = new_value.to_string(); - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserAliaseDeleteCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. - /// * *fields* (query-string) - Selector specifying which 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, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::DirectoryUser`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing 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, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().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` instance. -/// -/// # 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(); -/// -/// // You can configure optional parameters by calling 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, A> - where C: 'a, A: 'a { - - hub: &'a Directory, - _request: User, - _user_key: String, - _delegate: Option<&'a mut Delegate>, - _additional_params: HashMap, - _scopes: BTreeMap -} - -impl<'a, C, A> CallBuilder for UserUpdateCall<'a, C, A> {} - -impl<'a, C, A> UserUpdateCall<'a, C, A> where 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 Err(Error::FieldClash(field)); - } - } - for (name, 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::DirectoryUser.as_ref().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 param_name in ["notificationId", "customer"].iter() { if let Some(index) = params.iter().position(|t| &t.0 == param_name) { indices_for_removal.push(index); } @@ -9247,18 +18287,28 @@ impl<'a, C, A> UserUpdateCall<'a, C, A> where C: BorrowMut, A: oa /// /// Even though 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, A> { + pub fn request(mut self, new_value: Notification) -> NotificationUpdateCall<'a, C, A> { self._request = new_value; self } - /// Email or immutable Id of the user. If Id, it should match with id of user object + /// The unique ID for the customer's Google account. /// - /// Sets the *user key* path property to the given 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. - pub fn user_key(mut self, new_value: &str) -> UserUpdateCall<'a, C, A> { - self._user_key = new_value.to_string(); + pub fn customer(mut self, new_value: &str) -> NotificationUpdateCall<'a, C, A> { + self._customer = new_value.to_string(); + self + } + /// The unique ID of the notification. + /// + /// 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. + pub fn notification_id(mut self, new_value: &str) -> NotificationUpdateCall<'a, C, A> { + self._notification_id = new_value.to_string(); self } /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong @@ -9267,7 +18317,7 @@ impl<'a, C, A> UserUpdateCall<'a, C, A> where C: BorrowMut, A: oa /// It should be used to handle progress information, and to implement a certain level of resilience. /// /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserUpdateCall<'a, C, A> { + pub fn delegate(mut self, new_value: &'a mut Delegate) -> NotificationUpdateCall<'a, C, A> { self._delegate = Some(new_value); self } @@ -9288,7 +18338,7 @@ impl<'a, C, A> UserUpdateCall<'a, C, A> where C: BorrowMut, A: oa /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. /// * *fields* (query-string) - Selector specifying which 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, A> + pub fn param(mut self, name: T, value: T) -> NotificationUpdateCall<'a, C, A> where T: AsRef { self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); self @@ -9297,7 +18347,7 @@ impl<'a, C, A> UserUpdateCall<'a, C, A> where C: BorrowMut, A: oa /// Identifies the authorization scope for the method you are building. /// /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::DirectoryUser`. + /// `Scope::DirectoryNotification`. /// /// The `scope` will be added to a set of scopes. This is important as one can maintain access /// tokens for more than one scope. @@ -9305,7 +18355,7 @@ impl<'a, C, A> UserUpdateCall<'a, C, A> where C: BorrowMut, A: oa /// Usually there is more than one suitable scope to authorize an operation, some of which may /// encompass more rights than others. For example, for listing 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, A> + pub fn add_scope(mut self, scope: T) -> NotificationUpdateCall<'a, C, A> where T: AsRef { self._scopes.insert(scope.as_ref().to_string(), ()); self @@ -9313,289 +18363,10 @@ impl<'a, C, A> UserUpdateCall<'a, C, A> where C: BorrowMut, A: oa } -/// Watch for changes in user aliases list +/// Deletes a notification /// -/// A builder for the *aliases.watch* method supported by a *user* resource. -/// It is not used directly, but through a `UserMethods` instance. -/// -/// # 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(); -/// -/// // You can configure optional parameters by calling 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("consetetur") -/// .doit(); -/// # } -/// ``` -pub struct UserAliaseWatchCall<'a, C, A> - where C: '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, A> CallBuilder for UserAliaseWatchCall<'a, C, A> {} - -impl<'a, C, A> UserAliaseWatchCall<'a, C, A> where 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 Err(Error::FieldClash(field)); - } - } - for (name, 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::DirectoryUser.as_ref().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() { - if let Some(index) = params.iter().position(|t| &t.0 == param_name) { - indices_for_removal.push(index); - } - } - for &index in indices_for_removal.iter() { - params.remove(index); - } - } - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); - let mut request_value_reader = - { - let mut value = json::value::to_value(&self._request); - remove_json_null_values(&mut value); - let mut dst = io::Cursor::new(Vec::with_capacity(128)); - json::to_writer(&mut dst, &value).unwrap(); - dst - }; - let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); - request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_token }); - request_value_reader.seek(io::SeekFrom::Start(0)).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) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()) - .header(ContentType(json_mime_type.clone())) - .header(ContentLength(request_size as u64)) - .body(&mut request_value_reader); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = { - let mut json_response = String::new(); - res.read_to_string(&mut json_response).unwrap(); - match json::from_str(&json_response) { - Ok(decoded) => (res, decoded), - Err(err) => { - dlg.response_json_decode_error(&json_response, &err); - return Err(Error::JsonDecodeError(json_response, err)); - } - } - }; - - dlg.finished(true); - return Ok(result_value) - } - } - } - } - - - /// - /// Sets the *request* property to the given value. - /// - /// Even though 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, A> { - self._request = new_value; - self - } - /// Email or immutable Id of the user - /// - /// 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. - pub fn user_key(mut self, new_value: &str) -> UserAliaseWatchCall<'a, C, A> { - self._user_key = new_value.to_string(); - self - } - /// Event on which subscription is intended (if subscribing) - /// - /// Sets the *event* query property to the given value. - pub fn event(mut self, new_value: &str) -> UserAliaseWatchCall<'a, C, A> { - self._event = Some(new_value.to_string()); - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserAliaseWatchCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. - /// * *fields* (query-string) - Selector specifying which 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, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::DirectoryUser`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing 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, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().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` instance. +/// A builder for the *delete* method supported by a *notification* resource. +/// It is not used directly, but through a `NotificationMethods` instance. /// /// # Example /// @@ -9618,29 +18389,28 @@ impl<'a, C, A> UserAliaseWatchCall<'a, C, A> where C: BorrowMut, /// // You can configure optional parameters by calling 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("duo") +/// let result = hub.notifications().delete("customer", "notificationId") /// .doit(); /// # } /// ``` -pub struct UserAliaseListCall<'a, C, A> +pub struct NotificationDeleteCall<'a, C, A> where C: 'a, A: 'a { hub: &'a Directory, - _user_key: String, - _event: Option, + _customer: String, + _notification_id: String, _delegate: Option<&'a mut Delegate>, _additional_params: HashMap, _scopes: BTreeMap } -impl<'a, C, A> CallBuilder for UserAliaseListCall<'a, C, A> {} +impl<'a, C, A> CallBuilder for NotificationDeleteCall<'a, C, A> {} -impl<'a, C, A> UserAliaseListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { +impl<'a, C, A> NotificationDeleteCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { /// Perform the operation you have build so far. - pub fn doit(mut self) -> Result<(hyper::client::Response, Aliases)> { + pub fn doit(mut self) -> Result { use std::io::{Read, Seek}; use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; let mut dd = DefaultDelegate; @@ -9648,257 +18418,249 @@ impl<'a, C, A> UserAliaseListCall<'a, C, A> where C: BorrowMut, A 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 Err(Error::FieldClash(field)); - } - } - for (name, 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::DirectoryUserAliaReadonly.as_ref().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() { - if let Some(index) = params.iter().position(|t| &t.0 == param_name) { - indices_for_removal.push(index); - } - } - for &index in indices_for_removal.iter() { - params.remove(index); - } - } - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_token }); - let mut req_result = { - let mut client = &mut *self.hub.client.borrow_mut(); - let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = { - let mut json_response = String::new(); - res.read_to_string(&mut json_response).unwrap(); - match json::from_str(&json_response) { - Ok(decoded) => (res, decoded), - Err(err) => { - dlg.response_json_decode_error(&json_response, &err); - return Err(Error::JsonDecodeError(json_response, err)); - } - } - }; - - dlg.finished(true); - return Ok(result_value) - } - } - } - } - - - /// Email or immutable Id of the user - /// - /// 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. - pub fn user_key(mut self, new_value: &str) -> UserAliaseListCall<'a, C, A> { - self._user_key = new_value.to_string(); - self - } - /// Event on which subscription is intended (if subscribing) - /// - /// Sets the *event* query property to the given value. - pub fn event(mut self, new_value: &str) -> UserAliaseListCall<'a, C, A> { - self._event = Some(new_value.to_string()); - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserAliaseListCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. - /// * *fields* (query-string) - Selector specifying which 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, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::DirectoryUserAliaReadonly`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing 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, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().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` instance. -/// -/// # 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, A> - where C: 'a, A: 'a { - - hub: &'a Directory, - _user_key: String, - _delegate: Option<&'a mut Delegate>, - _additional_params: HashMap, - _scopes: BTreeMap -} - -impl<'a, C, A> CallBuilder for UserPhotoGetCall<'a, C, A> {} - -impl<'a, C, A> UserPhotoGetCall<'a, C, A> where 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 }); + 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(("userKey", self._user_key.to_string())); - for &field in ["alt", "userKey"].iter() { + 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 Err(Error::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::DirectoryNotification.as_ref().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 ["notificationId", "customer"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = res; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The unique ID for the customer's Google account. The customerId is also returned as part of the Users resource. + /// + /// 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. + pub fn customer(mut self, new_value: &str) -> NotificationDeleteCall<'a, C, A> { + self._customer = new_value.to_string(); + self + } + /// The unique ID of the notification. + /// + /// 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. + pub fn notification_id(mut self, new_value: &str) -> NotificationDeleteCall<'a, C, A> { + self._notification_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> NotificationDeleteCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::DirectoryNotification`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # 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, A> + where C: 'a, A: 'a { + + hub: &'a Directory, + _customer: String, + _notification_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for NotificationGetCall<'a, C, A> {} + +impl<'a, C, A> NotificationGetCall<'a, C, A> where 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 Err(Error::FieldClash(field)); @@ -9910,12 +18672,12 @@ impl<'a, C, A> UserPhotoGetCall<'a, C, A> where C: BorrowMut, A: params.push(("alt", "json".to_string())); - let mut url = "https://www.googleapis.com/admin/directory/v1/users/{userKey}/photos/thumbnail".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::DirectoryUserReadonly.as_ref().to_string(), ()); + self._scopes.insert(Scope::DirectoryNotification.as_ref().to_string(), ()); } - for &(find_this, param_name) in [("{userKey}", "userKey")].iter() { + 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 { @@ -9926,8 +18688,8 @@ impl<'a, C, A> UserPhotoGetCall<'a, C, A> where C: BorrowMut, A: url = url.replace(find_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() { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["notificationId", "customer"].iter() { if let Some(index) = params.iter().position(|t| &t.0 == param_name) { indices_for_removal.push(index); } @@ -10014,14 +18776,24 @@ impl<'a, C, A> UserPhotoGetCall<'a, C, A> where C: BorrowMut, A: } - /// Email or immutable Id of the user + /// The unique ID for the customer's Google account. The customerId is also returned as part of the Users resource. /// - /// Sets the *user key* path property to the given 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. - pub fn user_key(mut self, new_value: &str) -> UserPhotoGetCall<'a, C, A> { - self._user_key = new_value.to_string(); + pub fn customer(mut self, new_value: &str) -> NotificationGetCall<'a, C, A> { + self._customer = new_value.to_string(); + self + } + /// The unique ID of the notification. + /// + /// 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. + pub fn notification_id(mut self, new_value: &str) -> NotificationGetCall<'a, C, A> { + self._notification_id = new_value.to_string(); self } /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong @@ -10030,7 +18802,7 @@ impl<'a, C, A> UserPhotoGetCall<'a, C, A> where C: BorrowMut, A: /// It should be used to handle progress information, and to implement a certain level of resilience. /// /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserPhotoGetCall<'a, C, A> { + pub fn delegate(mut self, new_value: &'a mut Delegate) -> NotificationGetCall<'a, C, A> { self._delegate = Some(new_value); self } @@ -10051,7 +18823,7 @@ impl<'a, C, A> UserPhotoGetCall<'a, C, A> where C: BorrowMut, A: /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. /// * *fields* (query-string) - Selector specifying which 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, A> + pub fn param(mut self, name: T, value: T) -> NotificationGetCall<'a, C, A> where T: AsRef { self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); self @@ -10060,7 +18832,7 @@ impl<'a, C, A> UserPhotoGetCall<'a, C, A> where C: BorrowMut, A: /// Identifies the authorization scope for the method you are building. /// /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::DirectoryUserReadonly`. + /// `Scope::DirectoryNotification`. /// /// The `scope` will be added to a set of scopes. This is important as one can maintain access /// tokens for more than one scope. @@ -10068,7 +18840,7 @@ impl<'a, C, A> UserPhotoGetCall<'a, C, A> where C: BorrowMut, A: /// Usually there is more than one suitable scope to authorize an operation, some of which may /// encompass more rights than others. For example, for listing 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, A> + pub fn add_scope(mut self, scope: T) -> NotificationGetCall<'a, C, A> where T: AsRef { self._scopes.insert(scope.as_ref().to_string(), ()); self @@ -10076,10 +18848,10 @@ impl<'a, C, A> UserPhotoGetCall<'a, C, A> where C: BorrowMut, A: } -/// Add a photo for the user. This method supports patch semantics. +/// Updates a notification. 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` instance. +/// A builder for the *patch* method supported by a *notification* resource. +/// It is not used directly, but through a `NotificationMethods` instance. /// /// # Example /// @@ -10089,7 +18861,7 @@ impl<'a, C, A> UserPhotoGetCall<'a, C, A> where C: BorrowMut, A: /// # extern crate hyper; /// # extern crate yup_oauth2 as oauth2; /// # extern crate google_admin1_directory as admin1_directory; -/// use admin1_directory::UserPhoto; +/// use admin1_directory::Notification; /// # #[test] fn egal() { /// # use std::default::Default; /// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; @@ -10103,33 +18875,34 @@ impl<'a, C, A> UserPhotoGetCall<'a, C, A> where C: BorrowMut, A: /// // As the method needs a request, you would usually fill it with the desired information /// // into the 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(); +/// let mut req = Notification::default(); /// /// // You can configure optional parameters by calling 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") +/// let result = hub.notifications().patch(req, "customer", "notificationId") /// .doit(); /// # } /// ``` -pub struct UserPhotoPatchCall<'a, C, A> +pub struct NotificationPatchCall<'a, C, A> where C: 'a, A: 'a { hub: &'a Directory, - _request: UserPhoto, - _user_key: String, + _request: Notification, + _customer: String, + _notification_id: String, _delegate: Option<&'a mut Delegate>, _additional_params: HashMap, _scopes: BTreeMap } -impl<'a, C, A> CallBuilder for UserPhotoPatchCall<'a, C, A> {} +impl<'a, C, A> CallBuilder for NotificationPatchCall<'a, C, A> {} -impl<'a, C, A> UserPhotoPatchCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { +impl<'a, C, A> NotificationPatchCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { /// Perform the operation you have build so far. - pub fn doit(mut self) -> Result<(hyper::client::Response, UserPhoto)> { + 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; @@ -10137,11 +18910,12 @@ impl<'a, C, A> UserPhotoPatchCall<'a, C, A> where C: BorrowMut, A Some(d) => d, None => &mut dd }; - dlg.begin(MethodInfo { id: "directory.users.photos.patch", + dlg.begin(MethodInfo { id: "directory.notifications.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() { + 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 Err(Error::FieldClash(field)); @@ -10153,12 +18927,12 @@ impl<'a, C, A> UserPhotoPatchCall<'a, C, A> where C: BorrowMut, A params.push(("alt", "json".to_string())); - let mut url = "https://www.googleapis.com/admin/directory/v1/users/{userKey}/photos/thumbnail".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::DirectoryUser.as_ref().to_string(), ()); + self._scopes.insert(Scope::DirectoryNotification.as_ref().to_string(), ()); } - for &(find_this, param_name) in [("{userKey}", "userKey")].iter() { + 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 { @@ -10169,8 +18943,8 @@ impl<'a, C, A> UserPhotoPatchCall<'a, C, A> where C: BorrowMut, A url = url.replace(find_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() { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["notificationId", "customer"].iter() { if let Some(index) = params.iter().position(|t| &t.0 == param_name) { indices_for_removal.push(index); } @@ -10277,18 +19051,28 @@ impl<'a, C, A> UserPhotoPatchCall<'a, C, A> where C: BorrowMut, A /// /// Even though 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, A> { + pub fn request(mut self, new_value: Notification) -> NotificationPatchCall<'a, C, A> { self._request = new_value; self } - /// Email or immutable Id of the user + /// The unique ID for the customer's Google account. /// - /// Sets the *user key* path property to the given 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. - pub fn user_key(mut self, new_value: &str) -> UserPhotoPatchCall<'a, C, A> { - self._user_key = new_value.to_string(); + pub fn customer(mut self, new_value: &str) -> NotificationPatchCall<'a, C, A> { + self._customer = new_value.to_string(); + self + } + /// The unique ID of the notification. + /// + /// 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. + pub fn notification_id(mut self, new_value: &str) -> NotificationPatchCall<'a, C, A> { + self._notification_id = new_value.to_string(); self } /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong @@ -10297,7 +19081,7 @@ impl<'a, C, A> UserPhotoPatchCall<'a, C, A> where C: BorrowMut, A /// It should be used to handle progress information, and to implement a certain level of resilience. /// /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserPhotoPatchCall<'a, C, A> { + pub fn delegate(mut self, new_value: &'a mut Delegate) -> NotificationPatchCall<'a, C, A> { self._delegate = Some(new_value); self } @@ -10318,7 +19102,7 @@ impl<'a, C, A> UserPhotoPatchCall<'a, C, A> where C: BorrowMut, A /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. /// * *fields* (query-string) - Selector specifying which 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, A> + pub fn param(mut self, name: T, value: T) -> NotificationPatchCall<'a, C, A> where T: AsRef { self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); self @@ -10327,7 +19111,7 @@ impl<'a, C, A> UserPhotoPatchCall<'a, C, A> where C: BorrowMut, A /// Identifies the authorization scope for the method you are building. /// /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::DirectoryUser`. + /// `Scope::DirectoryNotification`. /// /// The `scope` will be added to a set of scopes. This is important as one can maintain access /// tokens for more than one scope. @@ -10335,7 +19119,7 @@ impl<'a, C, A> UserPhotoPatchCall<'a, C, A> where C: BorrowMut, A /// Usually there is more than one suitable scope to authorize an operation, some of which may /// encompass more rights than others. For example, for listing 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, A> + pub fn add_scope(mut self, scope: T) -> NotificationPatchCall<'a, C, A> where T: AsRef { self._scopes.insert(scope.as_ref().to_string(), ()); self @@ -10343,10 +19127,10 @@ impl<'a, C, A> UserPhotoPatchCall<'a, C, A> where C: BorrowMut, A } -/// Delete Mobile Device +/// Retrieve all Chrome OS Devices of a customer (paginated) /// -/// A builder for the *delete* method supported by a *mobiledevice* resource. -/// It is not used directly, but through a `MobiledeviceMethods` instance. +/// A builder for the *list* method supported by a *chromeosdevice* resource. +/// It is not used directly, but through a `ChromeosdeviceMethods` instance. /// /// # Example /// @@ -10369,514 +19153,17 @@ impl<'a, C, A> UserPhotoPatchCall<'a, C, A> where C: BorrowMut, A /// // You can configure optional parameters by calling 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, A> - where C: '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, A> CallBuilder for MobiledeviceDeleteCall<'a, C, A> {} - -impl<'a, C, A> MobiledeviceDeleteCall<'a, C, A> where 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 Err(Error::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::DirectoryDeviceMobile.as_ref().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 ["resourceId", "customerId"].iter() { - if let Some(index) = params.iter().position(|t| &t.0 == param_name) { - indices_for_removal.push(index); - } - } - for &index in indices_for_removal.iter() { - params.remove(index); - } - } - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_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) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = res; - - dlg.finished(true); - return Ok(result_value) - } - } - } - } - - - /// Immutable id of the Google Apps account - /// - /// 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. - pub fn customer_id(mut self, new_value: &str) -> MobiledeviceDeleteCall<'a, C, A> { - self._customer_id = new_value.to_string(); - self - } - /// Immutable id of Mobile Device - /// - /// 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. - pub fn resource_id(mut self, new_value: &str) -> MobiledeviceDeleteCall<'a, C, A> { - self._resource_id = new_value.to_string(); - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> MobiledeviceDeleteCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. - /// * *fields* (query-string) - Selector specifying which 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, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::DirectoryDeviceMobile`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing 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, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().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` instance. -/// -/// # 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("nonumy") -/// .doit(); -/// # } -/// ``` -pub struct MobiledeviceGetCall<'a, C, A> - where C: '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, A> CallBuilder for MobiledeviceGetCall<'a, C, A> {} - -impl<'a, C, A> MobiledeviceGetCall<'a, C, A> where 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 Err(Error::FieldClash(field)); - } - } - for (name, 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::DirectoryDeviceMobileReadonly.as_ref().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 ["resourceId", "customerId"].iter() { - if let Some(index) = params.iter().position(|t| &t.0 == param_name) { - indices_for_removal.push(index); - } - } - for &index in indices_for_removal.iter() { - params.remove(index); - } - } - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_token }); - let mut req_result = { - let mut client = &mut *self.hub.client.borrow_mut(); - let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = { - let mut json_response = String::new(); - res.read_to_string(&mut json_response).unwrap(); - match json::from_str(&json_response) { - Ok(decoded) => (res, decoded), - Err(err) => { - dlg.response_json_decode_error(&json_response, &err); - return Err(Error::JsonDecodeError(json_response, err)); - } - } - }; - - dlg.finished(true); - return Ok(result_value) - } - } - } - } - - - /// Immutable id of the Google Apps account - /// - /// 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. - pub fn customer_id(mut self, new_value: &str) -> MobiledeviceGetCall<'a, C, A> { - self._customer_id = new_value.to_string(); - self - } - /// Immutable id of Mobile Device - /// - /// 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. - pub fn resource_id(mut self, new_value: &str) -> MobiledeviceGetCall<'a, C, A> { - self._resource_id = new_value.to_string(); - self - } - /// Restrict information returned to a set of selected fields. - /// - /// Sets the *projection* query property to the given value. - pub fn projection(mut self, new_value: &str) -> MobiledeviceGetCall<'a, C, A> { - self._projection = Some(new_value.to_string()); - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> MobiledeviceGetCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. - /// * *fields* (query-string) - Selector specifying which 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, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::DirectoryDeviceMobileReadonly`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing 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, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().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` instance. -/// -/// # 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("sanctus") -/// .query("takimata") -/// .projection("At") -/// .page_token("labore") +/// let result = hub.chromeosdevices().list("customerId") +/// .sort_order("invidunt") +/// .query("rebum.") +/// .projection("Lorem") +/// .page_token("clita") /// .order_by("invidunt") -/// .max_results(-66) +/// .max_results(-90) /// .doit(); /// # } /// ``` -pub struct MobiledeviceListCall<'a, C, A> +pub struct ChromeosdeviceListCall<'a, C, A> where C: 'a, A: 'a { hub: &'a Directory, @@ -10892,13 +19179,13 @@ pub struct MobiledeviceListCall<'a, C, A> _scopes: BTreeMap } -impl<'a, C, A> CallBuilder for MobiledeviceListCall<'a, C, A> {} +impl<'a, C, A> CallBuilder for ChromeosdeviceListCall<'a, C, A> {} -impl<'a, C, A> MobiledeviceListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { +impl<'a, C, A> ChromeosdeviceListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { /// Perform the operation you have build so far. - pub fn doit(mut self) -> Result<(hyper::client::Response, MobileDevices)> { + 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; @@ -10906,7 +19193,7 @@ impl<'a, C, A> MobiledeviceListCall<'a, C, A> where C: BorrowMut, Some(d) => d, None => &mut dd }; - dlg.begin(MethodInfo { id: "directory.mobiledevices.list", + 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())); @@ -10940,9 +19227,9 @@ impl<'a, C, A> MobiledeviceListCall<'a, C, A> where C: BorrowMut, params.push(("alt", "json".to_string())); - let mut url = "https://www.googleapis.com/admin/directory/v1/customer/{customerId}/devices/mobile".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::DirectoryDeviceMobileReadonly.as_ref().to_string(), ()); + self._scopes.insert(Scope::DirectoryDeviceChromeoReadonly.as_ref().to_string(), ()); } for &(find_this, param_name) in [("{customerId}", "customerId")].iter() { @@ -11050,49 +19337,49 @@ impl<'a, C, A> MobiledeviceListCall<'a, C, A> where C: BorrowMut, /// /// Even though the property as already been set when instantiating this call, /// we provide this method for API completeness. - pub fn customer_id(mut self, new_value: &str) -> MobiledeviceListCall<'a, C, A> { + pub fn customer_id(mut self, new_value: &str) -> ChromeosdeviceListCall<'a, C, A> { self._customer_id = new_value.to_string(); self } /// Whether to return results in ascending or descending order. Only of use when orderBy is also used /// /// Sets the *sort order* query property to the given value. - pub fn sort_order(mut self, new_value: &str) -> MobiledeviceListCall<'a, C, A> { + pub fn sort_order(mut self, new_value: &str) -> ChromeosdeviceListCall<'a, C, A> { self._sort_order = Some(new_value.to_string()); self } - /// Search string in the format given at http://support.google.com/a/bin/answer.py?hl=en&answer=1408863#search + /// Search string in the format given at http://support.google.com/chromeos/a/bin/answer.py?hl=en&answer=1698333 /// /// Sets the *query* query property to the given value. - pub fn query(mut self, new_value: &str) -> MobiledeviceListCall<'a, C, A> { + pub fn query(mut self, new_value: &str) -> ChromeosdeviceListCall<'a, C, A> { self._query = Some(new_value.to_string()); self } /// Restrict information returned to a set of selected fields. /// /// Sets the *projection* query property to the given value. - pub fn projection(mut self, new_value: &str) -> MobiledeviceListCall<'a, C, A> { + pub fn projection(mut self, new_value: &str) -> ChromeosdeviceListCall<'a, C, A> { self._projection = Some(new_value.to_string()); self } /// Token to specify next page in the list /// /// Sets the *page token* query property to the given value. - pub fn page_token(mut self, new_value: &str) -> MobiledeviceListCall<'a, C, A> { + pub fn page_token(mut self, new_value: &str) -> ChromeosdeviceListCall<'a, C, A> { self._page_token = Some(new_value.to_string()); self } /// Column to use for sorting results /// /// Sets the *order by* query property to the given value. - pub fn order_by(mut self, new_value: &str) -> MobiledeviceListCall<'a, C, A> { + pub fn order_by(mut self, new_value: &str) -> ChromeosdeviceListCall<'a, C, A> { self._order_by = Some(new_value.to_string()); self } /// Maximum number of results to return. Default is 100 /// /// Sets the *max results* query property to the given value. - pub fn max_results(mut self, new_value: i32) -> MobiledeviceListCall<'a, C, A> { + pub fn max_results(mut self, new_value: i32) -> ChromeosdeviceListCall<'a, C, A> { self._max_results = Some(new_value); self } @@ -11102,7 +19389,7 @@ impl<'a, C, A> MobiledeviceListCall<'a, C, A> where C: BorrowMut, /// It should be used to handle progress information, and to implement a certain level of resilience. /// /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> MobiledeviceListCall<'a, C, A> { + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ChromeosdeviceListCall<'a, C, A> { self._delegate = Some(new_value); self } @@ -11123,7 +19410,7 @@ impl<'a, C, A> MobiledeviceListCall<'a, C, A> where C: BorrowMut, /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. /// * *fields* (query-string) - Selector specifying which 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, A> + pub fn param(mut self, name: T, value: T) -> ChromeosdeviceListCall<'a, C, A> where T: AsRef { self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); self @@ -11132,7 +19419,7 @@ impl<'a, C, A> MobiledeviceListCall<'a, C, A> where C: BorrowMut, /// Identifies the authorization scope for the method you are building. /// /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::DirectoryDeviceMobileReadonly`. + /// `Scope::DirectoryDeviceChromeoReadonly`. /// /// The `scope` will be added to a set of scopes. This is important as one can maintain access /// tokens for more than one scope. @@ -11140,7 +19427,7 @@ impl<'a, C, A> MobiledeviceListCall<'a, C, A> where C: BorrowMut, /// Usually there is more than one suitable scope to authorize an operation, some of which may /// encompass more rights than others. For example, for listing 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, A> + pub fn add_scope(mut self, scope: T) -> ChromeosdeviceListCall<'a, C, A> where T: AsRef { self._scopes.insert(scope.as_ref().to_string(), ()); self @@ -11148,10 +19435,10 @@ impl<'a, C, A> MobiledeviceListCall<'a, C, A> where C: BorrowMut, } -/// Take action on Mobile Device +/// Update Chrome OS Device. This method supports patch semantics. /// -/// A builder for the *action* method supported by a *mobiledevice* resource. -/// It is not used directly, but through a `MobiledeviceMethods` instance. +/// A builder for the *patch* method supported by a *chromeosdevice* resource. +/// It is not used directly, but through a `ChromeosdeviceMethods` instance. /// /// # Example /// @@ -11161,7 +19448,7 @@ impl<'a, C, A> MobiledeviceListCall<'a, C, A> where C: BorrowMut, /// # extern crate hyper; /// # extern crate yup_oauth2 as oauth2; /// # extern crate google_admin1_directory as admin1_directory; -/// use admin1_directory::MobileDeviceAction; +/// use admin1_directory::ChromeOsDevice; /// # #[test] fn egal() { /// # use std::default::Default; /// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; @@ -11175,34 +19462,36 @@ impl<'a, C, A> MobiledeviceListCall<'a, C, A> where C: BorrowMut, /// // As the method needs a request, you would usually fill it with the desired information /// // into the 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(); +/// let mut req = ChromeOsDevice::default(); /// /// // You can configure optional parameters by calling 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") +/// let result = hub.chromeosdevices().patch(req, "customerId", "deviceId") +/// .projection("et") /// .doit(); /// # } /// ``` -pub struct MobiledeviceActionCall<'a, C, A> +pub struct ChromeosdevicePatchCall<'a, C, A> where C: 'a, A: 'a { hub: &'a Directory, - _request: MobileDeviceAction, + _request: ChromeOsDevice, _customer_id: String, - _resource_id: String, + _device_id: String, + _projection: Option, _delegate: Option<&'a mut Delegate>, _additional_params: HashMap, _scopes: BTreeMap } -impl<'a, C, A> CallBuilder for MobiledeviceActionCall<'a, C, A> {} +impl<'a, C, A> CallBuilder for ChromeosdevicePatchCall<'a, C, A> {} -impl<'a, C, A> MobiledeviceActionCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { +impl<'a, C, A> ChromeosdevicePatchCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { /// Perform the operation you have build so far. - pub fn doit(mut self) -> Result { + 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; @@ -11210,12 +19499,15 @@ impl<'a, C, A> MobiledeviceActionCall<'a, C, A> where C: BorrowMut 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())); + 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(("resourceId", self._resource_id.to_string())); - for &field in ["customerId", "resourceId"].iter() { + 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 Err(Error::FieldClash(field)); @@ -11225,13 +19517,14 @@ impl<'a, C, A> MobiledeviceActionCall<'a, C, A> where C: BorrowMut = None; for &(name, ref value) in params.iter() { if name == param_name { @@ -11243,7 +19536,7 @@ impl<'a, C, A> MobiledeviceActionCall<'a, C, A> where C: BorrowMut = Vec::with_capacity(2); - for param_name in ["resourceId", "customerId"].iter() { + for param_name in ["deviceId", "customerId"].iter() { if let Some(index) = params.iter().position(|t| &t.0 == param_name) { indices_for_removal.push(index); } @@ -11289,7 +19582,7 @@ impl<'a, C, A> MobiledeviceActionCall<'a, C, A> where C: BorrowMut MobiledeviceActionCall<'a, C, A> where C: BorrowMut Err(Error::BadRequest(serr)) } } - let result_value = res; + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; dlg.finished(true); return Ok(result_value) @@ -11340,7 +19643,7 @@ impl<'a, C, A> MobiledeviceActionCall<'a, C, A> where C: BorrowMut MobiledeviceActionCall<'a, C, A> { + pub fn request(mut self, new_value: ChromeOsDevice) -> ChromeosdevicePatchCall<'a, C, A> { self._request = new_value; self } @@ -11350,18 +19653,25 @@ impl<'a, C, A> MobiledeviceActionCall<'a, C, A> where C: BorrowMut MobiledeviceActionCall<'a, C, A> { + pub fn customer_id(mut self, new_value: &str) -> ChromeosdevicePatchCall<'a, C, A> { self._customer_id = new_value.to_string(); self } - /// Immutable id of Mobile Device + /// Immutable id of Chrome OS Device /// - /// Sets the *resource id* path property to the given value. + /// 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. - pub fn resource_id(mut self, new_value: &str) -> MobiledeviceActionCall<'a, C, A> { - self._resource_id = new_value.to_string(); + pub fn device_id(mut self, new_value: &str) -> ChromeosdevicePatchCall<'a, C, A> { + self._device_id = new_value.to_string(); + self + } + /// Restrict information returned to a set of selected fields. + /// + /// Sets the *projection* query property to the given value. + pub fn projection(mut self, new_value: &str) -> ChromeosdevicePatchCall<'a, C, A> { + self._projection = Some(new_value.to_string()); self } /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong @@ -11370,7 +19680,7 @@ impl<'a, C, A> MobiledeviceActionCall<'a, C, A> where C: BorrowMut MobiledeviceActionCall<'a, C, A> { + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ChromeosdevicePatchCall<'a, C, A> { self._delegate = Some(new_value); self } @@ -11391,7 +19701,7 @@ impl<'a, C, A> MobiledeviceActionCall<'a, C, A> where C: BorrowMut(mut self, name: T, value: T) -> MobiledeviceActionCall<'a, C, A> + pub fn param(mut self, name: T, value: T) -> ChromeosdevicePatchCall<'a, C, A> where T: AsRef { self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); self @@ -11400,7 +19710,7 @@ impl<'a, C, A> MobiledeviceActionCall<'a, C, A> where C: BorrowMut MobiledeviceActionCall<'a, C, A> where C: BorrowMut(mut self, scope: T) -> MobiledeviceActionCall<'a, C, A> + pub fn add_scope(mut self, scope: T) -> ChromeosdevicePatchCall<'a, C, A> where T: AsRef { self._scopes.insert(scope.as_ref().to_string(), ()); self @@ -11416,10 +19726,10 @@ impl<'a, C, A> MobiledeviceActionCall<'a, C, A> where C: BorrowMut MobiledeviceActionCall<'a, C, A> where C: BorrowMut MobiledeviceActionCall<'a, C, A> where C: BorrowMut +pub struct ChromeosdeviceUpdateCall<'a, C, A> where C: 'a, A: 'a { hub: &'a Directory, - _request: Member, - _group_key: String, - _member_key: String, + _request: ChromeOsDevice, + _customer_id: String, + _device_id: String, + _projection: Option, _delegate: Option<&'a mut Delegate>, _additional_params: HashMap, _scopes: BTreeMap } -impl<'a, C, A> CallBuilder for MemberUpdateCall<'a, C, A> {} +impl<'a, C, A> CallBuilder for ChromeosdeviceUpdateCall<'a, C, A> {} -impl<'a, C, A> MemberUpdateCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { +impl<'a, C, A> ChromeosdeviceUpdateCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { /// Perform the operation you have build so far. - pub fn doit(mut self) -> Result<(hyper::client::Response, Member)> { + 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; @@ -11478,12 +19790,15 @@ impl<'a, C, A> MemberUpdateCall<'a, C, A> where C: BorrowMut, A: Some(d) => d, None => &mut dd }; - dlg.begin(MethodInfo { id: "directory.members.update", + dlg.begin(MethodInfo { id: "directory.chromeosdevices.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() { + 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 Err(Error::FieldClash(field)); @@ -11495,12 +19810,12 @@ impl<'a, C, A> MemberUpdateCall<'a, C, A> where C: BorrowMut, A: params.push(("alt", "json".to_string())); - let mut url = "https://www.googleapis.com/admin/directory/v1/groups/{groupKey}/members/{memberKey}".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::DirectoryGroup.as_ref().to_string(), ()); + self._scopes.insert(Scope::DirectoryDeviceChromeo.as_ref().to_string(), ()); } - for &(find_this, param_name) in [("{groupKey}", "groupKey"), ("{memberKey}", "memberKey")].iter() { + 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 { @@ -11512,7 +19827,7 @@ impl<'a, C, A> MemberUpdateCall<'a, C, A> where C: BorrowMut, A: } { let mut indices_for_removal: Vec = Vec::with_capacity(2); - for param_name in ["memberKey", "groupKey"].iter() { + for param_name in ["deviceId", "customerId"].iter() { if let Some(index) = params.iter().position(|t| &t.0 == param_name) { indices_for_removal.push(index); } @@ -11619,28 +19934,35 @@ impl<'a, C, A> MemberUpdateCall<'a, C, A> where C: BorrowMut, A: /// /// Even though 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, A> { + pub fn request(mut self, new_value: ChromeOsDevice) -> ChromeosdeviceUpdateCall<'a, C, A> { self._request = new_value; self } - /// Email or immutable Id of the group. If Id, it should match with id of group object + /// Immutable id of the Google Apps account /// - /// Sets the *group key* path property to the given 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. - pub fn group_key(mut self, new_value: &str) -> MemberUpdateCall<'a, C, A> { - self._group_key = new_value.to_string(); + pub fn customer_id(mut self, new_value: &str) -> ChromeosdeviceUpdateCall<'a, C, A> { + self._customer_id = new_value.to_string(); self } - /// Email or immutable Id of the user. If Id, it should match with id of member object + /// Immutable id of Chrome OS Device /// - /// Sets the *member key* path property to the given value. + /// 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. - pub fn member_key(mut self, new_value: &str) -> MemberUpdateCall<'a, C, A> { - self._member_key = new_value.to_string(); + pub fn device_id(mut self, new_value: &str) -> ChromeosdeviceUpdateCall<'a, C, A> { + self._device_id = new_value.to_string(); + self + } + /// Restrict information returned to a set of selected fields. + /// + /// Sets the *projection* query property to the given value. + pub fn projection(mut self, new_value: &str) -> ChromeosdeviceUpdateCall<'a, C, A> { + self._projection = Some(new_value.to_string()); self } /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong @@ -11649,7 +19971,7 @@ impl<'a, C, A> MemberUpdateCall<'a, C, A> where C: BorrowMut, A: /// It should be used to handle progress information, and to implement a certain level of resilience. /// /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> MemberUpdateCall<'a, C, A> { + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ChromeosdeviceUpdateCall<'a, C, A> { self._delegate = Some(new_value); self } @@ -11670,7 +19992,7 @@ impl<'a, C, A> MemberUpdateCall<'a, C, A> where C: BorrowMut, A: /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. /// * *fields* (query-string) - Selector specifying which 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, A> + pub fn param(mut self, name: T, value: T) -> ChromeosdeviceUpdateCall<'a, C, A> where T: AsRef { self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); self @@ -11679,7 +20001,7 @@ impl<'a, C, A> MemberUpdateCall<'a, C, A> where C: BorrowMut, A: /// Identifies the authorization scope for the method you are building. /// /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::DirectoryGroup`. + /// `Scope::DirectoryDeviceChromeo`. /// /// The `scope` will be added to a set of scopes. This is important as one can maintain access /// tokens for more than one scope. @@ -11687,7 +20009,7 @@ impl<'a, C, A> MemberUpdateCall<'a, C, A> where C: BorrowMut, A: /// Usually there is more than one suitable scope to authorize an operation, some of which may /// encompass more rights than others. For example, for listing 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, A> + pub fn add_scope(mut self, scope: T) -> ChromeosdeviceUpdateCall<'a, C, A> where T: AsRef { self._scopes.insert(scope.as_ref().to_string(), ()); self @@ -11695,10 +20017,10 @@ impl<'a, C, A> MemberUpdateCall<'a, C, A> where C: BorrowMut, A: } -/// Retrieve Group Member +/// Retrieve Chrome OS Device /// -/// A builder for the *get* method supported by a *member* resource. -/// It is not used directly, but through a `MemberMethods` instance. +/// A builder for the *get* method supported by a *chromeosdevice* resource. +/// It is not used directly, but through a `ChromeosdeviceMethods` instance. /// /// # Example /// @@ -11721,28 +20043,30 @@ impl<'a, C, A> MemberUpdateCall<'a, C, A> where C: BorrowMut, A: /// // You can configure optional parameters by calling 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") +/// let result = hub.chromeosdevices().get("customerId", "deviceId") +/// .projection("rebum.") /// .doit(); /// # } /// ``` -pub struct MemberGetCall<'a, C, A> +pub struct ChromeosdeviceGetCall<'a, C, A> where C: 'a, A: 'a { hub: &'a Directory, - _group_key: String, - _member_key: String, + _customer_id: String, + _device_id: String, + _projection: Option, _delegate: Option<&'a mut Delegate>, _additional_params: HashMap, _scopes: BTreeMap } -impl<'a, C, A> CallBuilder for MemberGetCall<'a, C, A> {} +impl<'a, C, A> CallBuilder for ChromeosdeviceGetCall<'a, C, A> {} -impl<'a, C, A> MemberGetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { +impl<'a, C, A> ChromeosdeviceGetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { /// Perform the operation you have build so far. - pub fn doit(mut self) -> Result<(hyper::client::Response, Member)> { + 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; @@ -11750,12 +20074,15 @@ impl<'a, C, A> MemberGetCall<'a, C, A> where C: BorrowMut, A: oau Some(d) => d, None => &mut dd }; - dlg.begin(MethodInfo { id: "directory.members.get", + dlg.begin(MethodInfo { id: "directory.chromeosdevices.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() { + 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 Err(Error::FieldClash(field)); @@ -11767,12 +20094,12 @@ impl<'a, C, A> MemberGetCall<'a, C, A> where C: BorrowMut, A: oau params.push(("alt", "json".to_string())); - let mut url = "https://www.googleapis.com/admin/directory/v1/groups/{groupKey}/members/{memberKey}".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::DirectoryGroupMemberReadonly.as_ref().to_string(), ()); + self._scopes.insert(Scope::DirectoryDeviceChromeoReadonly.as_ref().to_string(), ()); } - for &(find_this, param_name) in [("{groupKey}", "groupKey"), ("{memberKey}", "memberKey")].iter() { + 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 { @@ -11784,7 +20111,7 @@ impl<'a, C, A> MemberGetCall<'a, C, A> where C: BorrowMut, A: oau } { let mut indices_for_removal: Vec = Vec::with_capacity(2); - for param_name in ["memberKey", "groupKey"].iter() { + for param_name in ["deviceId", "customerId"].iter() { if let Some(index) = params.iter().position(|t| &t.0 == param_name) { indices_for_removal.push(index); } @@ -11871,24 +20198,31 @@ impl<'a, C, A> MemberGetCall<'a, C, A> where C: BorrowMut, A: oau } - /// Email or immutable Id of the group + /// Immutable id of the Google Apps account /// - /// Sets the *group key* path property to the given 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. - pub fn group_key(mut self, new_value: &str) -> MemberGetCall<'a, C, A> { - self._group_key = new_value.to_string(); + pub fn customer_id(mut self, new_value: &str) -> ChromeosdeviceGetCall<'a, C, A> { + self._customer_id = new_value.to_string(); self } - /// Email or immutable Id of the member + /// Immutable id of Chrome OS Device /// - /// Sets the *member key* path property to the given value. + /// 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. - pub fn member_key(mut self, new_value: &str) -> MemberGetCall<'a, C, A> { - self._member_key = new_value.to_string(); + pub fn device_id(mut self, new_value: &str) -> ChromeosdeviceGetCall<'a, C, A> { + self._device_id = new_value.to_string(); + self + } + /// Restrict information returned to a set of selected fields. + /// + /// Sets the *projection* query property to the given value. + pub fn projection(mut self, new_value: &str) -> ChromeosdeviceGetCall<'a, C, A> { + self._projection = Some(new_value.to_string()); self } /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong @@ -11897,7 +20231,7 @@ impl<'a, C, A> MemberGetCall<'a, C, A> where C: BorrowMut, A: oau /// It should be used to handle progress information, and to implement a certain level of resilience. /// /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> MemberGetCall<'a, C, A> { + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ChromeosdeviceGetCall<'a, C, A> { self._delegate = Some(new_value); self } @@ -11918,7 +20252,7 @@ impl<'a, C, A> MemberGetCall<'a, C, A> where C: BorrowMut, A: oau /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. /// * *fields* (query-string) - Selector specifying which 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, A> + pub fn param(mut self, name: T, value: T) -> ChromeosdeviceGetCall<'a, C, A> where T: AsRef { self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); self @@ -11927,7 +20261,7 @@ impl<'a, C, A> MemberGetCall<'a, C, A> where C: BorrowMut, A: oau /// Identifies the authorization scope for the method you are building. /// /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::DirectoryGroupMemberReadonly`. + /// `Scope::DirectoryDeviceChromeoReadonly`. /// /// The `scope` will be added to a set of scopes. This is important as one can maintain access /// tokens for more than one scope. @@ -11935,7 +20269,7 @@ impl<'a, C, A> MemberGetCall<'a, C, A> where C: BorrowMut, A: oau /// Usually there is more than one suitable scope to authorize an operation, some of which may /// encompass more rights than others. For example, for listing 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, A> + pub fn add_scope(mut self, scope: T) -> ChromeosdeviceGetCall<'a, C, A> where T: AsRef { self._scopes.insert(scope.as_ref().to_string(), ()); self @@ -12489,9 +20823,9 @@ impl<'a, C, A> MemberPatchCall<'a, C, A> where C: BorrowMut, A: o } -/// Remove membership. +/// Update membership of a user in the specified group. /// -/// A builder for the *delete* method supported by a *member* resource. +/// A builder for the *update* method supported by a *member* resource. /// It is not used directly, but through a `MemberMethods` instance. /// /// # Example @@ -12502,6 +20836,7 @@ impl<'a, C, A> MemberPatchCall<'a, C, A> where C: BorrowMut, A: o /// # 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}; @@ -12512,17 +20847,23 @@ impl<'a, C, A> MemberPatchCall<'a, C, A> where C: BorrowMut, A: o /// # 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(); +/// /// // You can configure optional parameters by calling 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") +/// let result = hub.members().update(req, "groupKey", "memberKey") /// .doit(); /// # } /// ``` -pub struct MemberDeleteCall<'a, C, A> +pub struct MemberUpdateCall<'a, C, A> where C: 'a, A: 'a { hub: &'a Directory, + _request: Member, _group_key: String, _member_key: String, _delegate: Option<&'a mut Delegate>, @@ -12530,13 +20871,13 @@ pub struct MemberDeleteCall<'a, C, A> _scopes: BTreeMap } -impl<'a, C, A> CallBuilder for MemberDeleteCall<'a, C, A> {} +impl<'a, C, A> CallBuilder for MemberUpdateCall<'a, C, A> {} -impl<'a, C, A> MemberDeleteCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { +impl<'a, C, A> MemberUpdateCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { /// Perform the operation you have build so far. - pub fn doit(mut self) -> Result { + 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; @@ -12544,12 +20885,12 @@ impl<'a, C, A> MemberDeleteCall<'a, C, A> where C: BorrowMut, A: 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())); + 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 ["groupKey", "memberKey"].iter() { + for &field in ["alt", "groupKey", "memberKey"].iter() { if self._additional_params.contains_key(field) { dlg.finished(false); return Err(Error::FieldClash(field)); @@ -12559,6 +20900,7 @@ impl<'a, C, A> MemberDeleteCall<'a, C, A> where C: BorrowMut, A: 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 { @@ -12592,6 +20934,17 @@ impl<'a, C, A> MemberDeleteCall<'a, C, A> where C: BorrowMut, A: url.push_str(&url::form_urlencoded::serialize(params)); } + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); loop { @@ -12609,11 +20962,15 @@ impl<'a, C, A> MemberDeleteCall<'a, C, A> where C: BorrowMut, A: }; let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); 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) + let mut req = client.borrow_mut().request(hyper::method::Method::Put, &url) .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()); + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); dlg.pre_request(); req.send() @@ -12644,7 +21001,17 @@ impl<'a, C, A> MemberDeleteCall<'a, C, A> where C: BorrowMut, A: Ok(serr) => Err(Error::BadRequest(serr)) } } - let result_value = res; + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; dlg.finished(true); return Ok(result_value) @@ -12654,23 +21021,32 @@ impl<'a, C, A> MemberDeleteCall<'a, C, A> where C: BorrowMut, A: } - /// Email or immutable Id of the group + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// Email or immutable Id of the group. If Id, it should match with id of group object /// /// 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. - pub fn group_key(mut self, new_value: &str) -> MemberDeleteCall<'a, C, A> { + pub fn group_key(mut self, new_value: &str) -> MemberUpdateCall<'a, C, A> { self._group_key = new_value.to_string(); self } - /// Email or immutable Id of the member + /// Email or immutable Id of the user. If Id, it should match with id of member object /// /// 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. - pub fn member_key(mut self, new_value: &str) -> MemberDeleteCall<'a, C, A> { + pub fn member_key(mut self, new_value: &str) -> MemberUpdateCall<'a, C, A> { self._member_key = new_value.to_string(); self } @@ -12680,7 +21056,7 @@ impl<'a, C, A> MemberDeleteCall<'a, C, A> where C: BorrowMut, A: /// It should be used to handle progress information, and to implement a certain level of resilience. /// /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> MemberDeleteCall<'a, C, A> { + pub fn delegate(mut self, new_value: &'a mut Delegate) -> MemberUpdateCall<'a, C, A> { self._delegate = Some(new_value); self } @@ -12701,7 +21077,7 @@ impl<'a, C, A> MemberDeleteCall<'a, C, A> where C: BorrowMut, A: /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. /// * *fields* (query-string) - Selector specifying which 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, A> + pub fn param(mut self, name: T, value: T) -> MemberUpdateCall<'a, C, A> where T: AsRef { self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); self @@ -12718,7 +21094,7 @@ impl<'a, C, A> MemberDeleteCall<'a, C, A> where C: BorrowMut, A: /// Usually there is more than one suitable scope to authorize an operation, some of which may /// encompass more rights than others. For example, for listing 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, A> + pub fn add_scope(mut self, scope: T) -> MemberUpdateCall<'a, C, A> where T: AsRef { self._scopes.insert(scope.as_ref().to_string(), ()); self @@ -12753,9 +21129,9 @@ impl<'a, C, A> MemberDeleteCall<'a, C, A> where C: BorrowMut, A: /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.members().list("groupKey") -/// .roles("gubergren") -/// .page_token("aliquyam") -/// .max_results(-24) +/// .roles("ipsum") +/// .page_token("ut") +/// .max_results(-3) /// .doit(); /// # } /// ``` @@ -12998,10 +21374,10 @@ impl<'a, C, A> MemberListCall<'a, C, A> where C: BorrowMut, A: oa } -/// Retrieves a list of notifications. +/// Retrieve Group Member /// -/// A builder for the *list* method supported by a *notification* resource. -/// It is not used directly, but through a `NotificationMethods` instance. +/// A builder for the *get* method supported by a *member* resource. +/// It is not used directly, but through a `MemberMethods` instance. /// /// # Example /// @@ -13024,33 +21400,28 @@ impl<'a, C, A> MemberListCall<'a, C, A> where C: BorrowMut, A: oa /// // You can configure optional parameters by calling 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("sea") -/// .max_results(16) -/// .language("ipsum") +/// let result = hub.members().get("groupKey", "memberKey") /// .doit(); /// # } /// ``` -pub struct NotificationListCall<'a, C, A> +pub struct MemberGetCall<'a, C, A> where C: 'a, A: 'a { hub: &'a Directory, - _customer: String, - _page_token: Option, - _max_results: Option, - _language: Option, + _group_key: String, + _member_key: String, _delegate: Option<&'a mut Delegate>, _additional_params: HashMap, _scopes: BTreeMap } -impl<'a, C, A> CallBuilder for NotificationListCall<'a, C, A> {} +impl<'a, C, A> CallBuilder for MemberGetCall<'a, C, A> {} -impl<'a, C, A> NotificationListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { +impl<'a, C, A> MemberGetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { /// Perform the operation you have build so far. - pub fn doit(mut self) -> Result<(hyper::client::Response, Notifications)> { + 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; @@ -13058,20 +21429,12 @@ impl<'a, C, A> NotificationListCall<'a, C, A> where C: BorrowMut, Some(d) => d, None => &mut dd }; - dlg.begin(MethodInfo { id: "directory.notifications.list", + dlg.begin(MethodInfo { id: "directory.members.get", 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() { + 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 Err(Error::FieldClash(field)); @@ -13083,12 +21446,12 @@ impl<'a, C, A> NotificationListCall<'a, C, A> where C: BorrowMut, params.push(("alt", "json".to_string())); - let mut url = "https://www.googleapis.com/admin/directory/v1/customer/{customer}/notifications".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::DirectoryNotification.as_ref().to_string(), ()); + self._scopes.insert(Scope::DirectoryGroupMemberReadonly.as_ref().to_string(), ()); } - for &(find_this, param_name) in [("{customer}", "customer")].iter() { + 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 { @@ -13099,8 +21462,8 @@ impl<'a, C, A> NotificationListCall<'a, C, A> where C: BorrowMut, url = url.replace(find_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() { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["memberKey", "groupKey"].iter() { if let Some(index) = params.iter().position(|t| &t.0 == param_name) { indices_for_removal.push(index); } @@ -13187,35 +21550,24 @@ impl<'a, C, A> NotificationListCall<'a, C, A> where C: BorrowMut, } - /// The unique ID for the customer's Google account. + /// Email or immutable Id of the group /// - /// Sets the *customer* path property to the given 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. - pub fn customer(mut self, new_value: &str) -> NotificationListCall<'a, C, A> { - self._customer = new_value.to_string(); + pub fn group_key(mut self, new_value: &str) -> MemberGetCall<'a, C, A> { + self._group_key = new_value.to_string(); self } - /// The token to specify the page of results to retrieve. + /// Email or immutable Id of the member /// - /// Sets the *page token* query property to the given value. - pub fn page_token(mut self, new_value: &str) -> NotificationListCall<'a, C, A> { - self._page_token = Some(new_value.to_string()); - self - } - /// Maximum number of notifications to return per page. The default is 100. + /// Sets the *member key* path property to the given value. /// - /// Sets the *max results* query property to the given value. - pub fn max_results(mut self, new_value: u32) -> NotificationListCall<'a, C, A> { - self._max_results = Some(new_value); - self - } - /// The ISO 639-1 code of the language notifications are returned in. The default is English (en). - /// - /// Sets the *language* query property to the given value. - pub fn language(mut self, new_value: &str) -> NotificationListCall<'a, C, A> { - self._language = Some(new_value.to_string()); + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn member_key(mut self, new_value: &str) -> MemberGetCall<'a, C, A> { + self._member_key = new_value.to_string(); self } /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong @@ -13224,7 +21576,7 @@ impl<'a, C, A> NotificationListCall<'a, C, A> where C: BorrowMut, /// It should be used to handle progress information, and to implement a certain level of resilience. /// /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> NotificationListCall<'a, C, A> { + pub fn delegate(mut self, new_value: &'a mut Delegate) -> MemberGetCall<'a, C, A> { self._delegate = Some(new_value); self } @@ -13245,7 +21597,7 @@ impl<'a, C, A> NotificationListCall<'a, C, A> where C: BorrowMut, /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. /// * *fields* (query-string) - Selector specifying which 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, A> + pub fn param(mut self, name: T, value: T) -> MemberGetCall<'a, C, A> where T: AsRef { self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); self @@ -13254,7 +21606,7 @@ impl<'a, C, A> NotificationListCall<'a, C, A> where C: BorrowMut, /// Identifies the authorization scope for the method you are building. /// /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::DirectoryNotification`. + /// `Scope::DirectoryGroupMemberReadonly`. /// /// The `scope` will be added to a set of scopes. This is important as one can maintain access /// tokens for more than one scope. @@ -13262,7 +21614,7 @@ impl<'a, C, A> NotificationListCall<'a, C, A> where C: BorrowMut, /// Usually there is more than one suitable scope to authorize an operation, some of which may /// encompass more rights than others. For example, for listing 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, A> + pub fn add_scope(mut self, scope: T) -> MemberGetCall<'a, C, A> where T: AsRef { self._scopes.insert(scope.as_ref().to_string(), ()); self @@ -13270,10 +21622,10 @@ impl<'a, C, A> NotificationListCall<'a, C, A> where C: BorrowMut, } -/// Deletes a notification +/// Remove membership. /// -/// A builder for the *delete* method supported by a *notification* resource. -/// It is not used directly, but through a `NotificationMethods` instance. +/// A builder for the *delete* method supported by a *member* resource. +/// It is not used directly, but through a `MemberMethods` instance. /// /// # Example /// @@ -13296,24 +21648,24 @@ impl<'a, C, A> NotificationListCall<'a, C, A> where C: BorrowMut, /// // You can configure optional parameters by calling 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") +/// let result = hub.members().delete("groupKey", "memberKey") /// .doit(); /// # } /// ``` -pub struct NotificationDeleteCall<'a, C, A> +pub struct MemberDeleteCall<'a, C, A> where C: 'a, A: 'a { hub: &'a Directory, - _customer: String, - _notification_id: String, + _group_key: String, + _member_key: String, _delegate: Option<&'a mut Delegate>, _additional_params: HashMap, _scopes: BTreeMap } -impl<'a, C, A> CallBuilder for NotificationDeleteCall<'a, C, A> {} +impl<'a, C, A> CallBuilder for MemberDeleteCall<'a, C, A> {} -impl<'a, C, A> NotificationDeleteCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { +impl<'a, C, A> MemberDeleteCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { /// Perform the operation you have build so far. @@ -13325,12 +21677,12 @@ impl<'a, C, A> NotificationDeleteCall<'a, C, A> where C: BorrowMut d, None => &mut dd }; - dlg.begin(MethodInfo { id: "directory.notifications.delete", + 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(("customer", self._customer.to_string())); - params.push(("notificationId", self._notification_id.to_string())); - for &field in ["customer", "notificationId"].iter() { + 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 Err(Error::FieldClash(field)); @@ -13341,12 +21693,12 @@ impl<'a, C, A> NotificationDeleteCall<'a, C, A> where C: BorrowMut = None; for &(name, ref value) in params.iter() { if name == param_name { @@ -13358,7 +21710,7 @@ impl<'a, C, A> NotificationDeleteCall<'a, C, A> where C: BorrowMut = Vec::with_capacity(2); - for param_name in ["notificationId", "customer"].iter() { + for param_name in ["memberKey", "groupKey"].iter() { if let Some(index) = params.iter().position(|t| &t.0 == param_name) { indices_for_removal.push(index); } @@ -13435,24 +21787,24 @@ impl<'a, C, A> NotificationDeleteCall<'a, C, A> where C: BorrowMut NotificationDeleteCall<'a, C, A> { - self._customer = new_value.to_string(); + pub fn group_key(mut self, new_value: &str) -> MemberDeleteCall<'a, C, A> { + self._group_key = new_value.to_string(); self } - /// The unique ID of the notification. + /// Email or immutable Id of the member /// - /// Sets the *notification id* path property to the given value. + /// 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. - pub fn notification_id(mut self, new_value: &str) -> NotificationDeleteCall<'a, C, A> { - self._notification_id = new_value.to_string(); + pub fn member_key(mut self, new_value: &str) -> MemberDeleteCall<'a, C, A> { + self._member_key = new_value.to_string(); self } /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong @@ -13461,7 +21813,7 @@ impl<'a, C, A> NotificationDeleteCall<'a, C, A> where C: BorrowMut NotificationDeleteCall<'a, C, A> { + pub fn delegate(mut self, new_value: &'a mut Delegate) -> MemberDeleteCall<'a, C, A> { self._delegate = Some(new_value); self } @@ -13482,7 +21834,7 @@ impl<'a, C, A> NotificationDeleteCall<'a, C, A> where C: BorrowMut(mut self, name: T, value: T) -> NotificationDeleteCall<'a, C, A> + pub fn param(mut self, name: T, value: T) -> MemberDeleteCall<'a, C, A> where T: AsRef { self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); self @@ -13491,7 +21843,7 @@ impl<'a, C, A> NotificationDeleteCall<'a, C, A> where C: BorrowMut NotificationDeleteCall<'a, C, A> where C: BorrowMut(mut self, scope: T) -> NotificationDeleteCall<'a, C, A> + pub fn add_scope(mut self, scope: T) -> MemberDeleteCall<'a, C, A> where T: AsRef { self._scopes.insert(scope.as_ref().to_string(), ()); self @@ -13507,568 +21859,10 @@ impl<'a, C, A> NotificationDeleteCall<'a, C, A> where C: BorrowMut::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(); -/// -/// // You can configure optional parameters by calling 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, A> - where C: '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, A> CallBuilder for NotificationPatchCall<'a, C, A> {} - -impl<'a, C, A> NotificationPatchCall<'a, C, A> where 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 Err(Error::FieldClash(field)); - } - } - for (name, 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::DirectoryNotification.as_ref().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 ["notificationId", "customer"].iter() { - if let Some(index) = params.iter().position(|t| &t.0 == param_name) { - indices_for_removal.push(index); - } - } - for &index in indices_for_removal.iter() { - params.remove(index); - } - } - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); - let mut request_value_reader = - { - let mut value = json::value::to_value(&self._request); - remove_json_null_values(&mut value); - let mut dst = io::Cursor::new(Vec::with_capacity(128)); - json::to_writer(&mut dst, &value).unwrap(); - dst - }; - let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); - request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_token }); - request_value_reader.seek(io::SeekFrom::Start(0)).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) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()) - .header(ContentType(json_mime_type.clone())) - .header(ContentLength(request_size as u64)) - .body(&mut request_value_reader); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = { - let mut json_response = String::new(); - res.read_to_string(&mut json_response).unwrap(); - match json::from_str(&json_response) { - Ok(decoded) => (res, decoded), - Err(err) => { - dlg.response_json_decode_error(&json_response, &err); - return Err(Error::JsonDecodeError(json_response, err)); - } - } - }; - - dlg.finished(true); - return Ok(result_value) - } - } - } - } - - - /// - /// Sets the *request* property to the given value. - /// - /// Even though 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, A> { - self._request = new_value; - self - } - /// The unique ID for the customer's Google account. - /// - /// 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. - pub fn customer(mut self, new_value: &str) -> NotificationPatchCall<'a, C, A> { - self._customer = new_value.to_string(); - self - } - /// The unique ID of the notification. - /// - /// 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. - pub fn notification_id(mut self, new_value: &str) -> NotificationPatchCall<'a, C, A> { - self._notification_id = new_value.to_string(); - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> NotificationPatchCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. - /// * *fields* (query-string) - Selector specifying which 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, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::DirectoryNotification`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing 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, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().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` instance. -/// -/// # 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(); -/// -/// // You can configure optional parameters by calling 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, A> - where C: '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, A> CallBuilder for NotificationUpdateCall<'a, C, A> {} - -impl<'a, C, A> NotificationUpdateCall<'a, C, A> where 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 Err(Error::FieldClash(field)); - } - } - for (name, 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::DirectoryNotification.as_ref().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 ["notificationId", "customer"].iter() { - if let Some(index) = params.iter().position(|t| &t.0 == param_name) { - indices_for_removal.push(index); - } - } - for &index in indices_for_removal.iter() { - params.remove(index); - } - } - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); - let mut request_value_reader = - { - let mut value = json::value::to_value(&self._request); - remove_json_null_values(&mut value); - let mut dst = io::Cursor::new(Vec::with_capacity(128)); - json::to_writer(&mut dst, &value).unwrap(); - dst - }; - let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); - request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_token }); - request_value_reader.seek(io::SeekFrom::Start(0)).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) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()) - .header(ContentType(json_mime_type.clone())) - .header(ContentLength(request_size as u64)) - .body(&mut request_value_reader); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = { - let mut json_response = String::new(); - res.read_to_string(&mut json_response).unwrap(); - match json::from_str(&json_response) { - Ok(decoded) => (res, decoded), - Err(err) => { - dlg.response_json_decode_error(&json_response, &err); - return Err(Error::JsonDecodeError(json_response, err)); - } - } - }; - - dlg.finished(true); - return Ok(result_value) - } - } - } - } - - - /// - /// Sets the *request* property to the given value. - /// - /// Even though 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, A> { - self._request = new_value; - self - } - /// The unique ID for the customer's Google account. - /// - /// 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. - pub fn customer(mut self, new_value: &str) -> NotificationUpdateCall<'a, C, A> { - self._customer = new_value.to_string(); - self - } - /// The unique ID of the notification. - /// - /// 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. - pub fn notification_id(mut self, new_value: &str) -> NotificationUpdateCall<'a, C, A> { - self._notification_id = new_value.to_string(); - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> NotificationUpdateCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. - /// * *fields* (query-string) - Selector specifying which 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, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::DirectoryNotification`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing 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, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().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` instance. +/// A builder for the *get* method supported by a *asp* resource. +/// It is not used directly, but through a `AspMethods` instance. /// /// # Example /// @@ -14091,28 +21885,28 @@ impl<'a, C, A> NotificationUpdateCall<'a, C, A> where C: BorrowMut +pub struct AspGetCall<'a, C, A> where C: 'a, A: 'a { hub: &'a Directory, - _customer: String, - _notification_id: String, + _user_key: String, + _code_id: i32, _delegate: Option<&'a mut Delegate>, _additional_params: HashMap, _scopes: BTreeMap } -impl<'a, C, A> CallBuilder for NotificationGetCall<'a, C, A> {} +impl<'a, C, A> CallBuilder for AspGetCall<'a, C, A> {} -impl<'a, C, A> NotificationGetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { +impl<'a, C, A> AspGetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { /// Perform the operation you have build so far. - pub fn doit(mut self) -> Result<(hyper::client::Response, Notification)> { + 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; @@ -14120,1408 +21914,12 @@ impl<'a, C, A> NotificationGetCall<'a, C, A> where C: BorrowMut, Some(d) => d, None => &mut dd }; - dlg.begin(MethodInfo { id: "directory.notifications.get", + 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(("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 Err(Error::FieldClash(field)); - } - } - for (name, 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::DirectoryNotification.as_ref().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 ["notificationId", "customer"].iter() { - if let Some(index) = params.iter().position(|t| &t.0 == param_name) { - indices_for_removal.push(index); - } - } - for &index in indices_for_removal.iter() { - params.remove(index); - } - } - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_token }); - let mut req_result = { - let mut client = &mut *self.hub.client.borrow_mut(); - let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = { - let mut json_response = String::new(); - res.read_to_string(&mut json_response).unwrap(); - match json::from_str(&json_response) { - Ok(decoded) => (res, decoded), - Err(err) => { - dlg.response_json_decode_error(&json_response, &err); - return Err(Error::JsonDecodeError(json_response, err)); - } - } - }; - - dlg.finished(true); - return Ok(result_value) - } - } - } - } - - - /// The unique ID for the customer's Google account. The customerId is also returned as part of the Users resource. - /// - /// 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. - pub fn customer(mut self, new_value: &str) -> NotificationGetCall<'a, C, A> { - self._customer = new_value.to_string(); - self - } - /// The unique ID of the notification. - /// - /// 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. - pub fn notification_id(mut self, new_value: &str) -> NotificationGetCall<'a, C, A> { - self._notification_id = new_value.to_string(); - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> NotificationGetCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. - /// * *fields* (query-string) - Selector specifying which 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, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::DirectoryNotification`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing 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, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().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` instance. -/// -/// # 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("clita") -/// .query("diam") -/// .projection("justo") -/// .page_token("est") -/// .order_by("clita") -/// .max_results(-37) -/// .doit(); -/// # } -/// ``` -pub struct ChromeosdeviceListCall<'a, C, A> - where C: '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, A> CallBuilder for ChromeosdeviceListCall<'a, C, A> {} - -impl<'a, C, A> ChromeosdeviceListCall<'a, C, A> where 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 Err(Error::FieldClash(field)); - } - } - for (name, 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_ref().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() { - if let Some(index) = params.iter().position(|t| &t.0 == param_name) { - indices_for_removal.push(index); - } - } - for &index in indices_for_removal.iter() { - params.remove(index); - } - } - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_token }); - let mut req_result = { - let mut client = &mut *self.hub.client.borrow_mut(); - let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = { - let mut json_response = String::new(); - res.read_to_string(&mut json_response).unwrap(); - match json::from_str(&json_response) { - Ok(decoded) => (res, decoded), - Err(err) => { - dlg.response_json_decode_error(&json_response, &err); - return Err(Error::JsonDecodeError(json_response, err)); - } - } - }; - - dlg.finished(true); - return Ok(result_value) - } - } - } - } - - - /// Immutable id of the Google Apps account - /// - /// 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. - pub fn customer_id(mut self, new_value: &str) -> ChromeosdeviceListCall<'a, C, A> { - self._customer_id = new_value.to_string(); - self - } - /// Whether to return results in ascending or descending order. Only of use when orderBy is also used - /// - /// Sets the *sort order* query property to the given value. - pub fn sort_order(mut self, new_value: &str) -> ChromeosdeviceListCall<'a, C, A> { - self._sort_order = Some(new_value.to_string()); - self - } - /// Search string in the format given at http://support.google.com/chromeos/a/bin/answer.py?hl=en&answer=1698333 - /// - /// Sets the *query* query property to the given value. - pub fn query(mut self, new_value: &str) -> ChromeosdeviceListCall<'a, C, A> { - self._query = Some(new_value.to_string()); - self - } - /// Restrict information returned to a set of selected fields. - /// - /// Sets the *projection* query property to the given value. - pub fn projection(mut self, new_value: &str) -> ChromeosdeviceListCall<'a, C, A> { - self._projection = Some(new_value.to_string()); - self - } - /// Token to specify next page in the list - /// - /// Sets the *page token* query property to the given value. - pub fn page_token(mut self, new_value: &str) -> ChromeosdeviceListCall<'a, C, A> { - self._page_token = Some(new_value.to_string()); - self - } - /// Column to use for sorting results - /// - /// Sets the *order by* query property to the given value. - pub fn order_by(mut self, new_value: &str) -> ChromeosdeviceListCall<'a, C, A> { - self._order_by = Some(new_value.to_string()); - self - } - /// Maximum number of results to return. Default is 100 - /// - /// Sets the *max results* query property to the given value. - pub fn max_results(mut self, new_value: i32) -> ChromeosdeviceListCall<'a, C, A> { - self._max_results = Some(new_value); - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> ChromeosdeviceListCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. - /// * *fields* (query-string) - Selector specifying which 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, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::DirectoryDeviceChromeoReadonly`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing 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, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().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` instance. -/// -/// # 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(); -/// -/// // You can configure optional parameters by calling 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("eos") -/// .doit(); -/// # } -/// ``` -pub struct ChromeosdevicePatchCall<'a, C, A> - where C: '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, A> CallBuilder for ChromeosdevicePatchCall<'a, C, A> {} - -impl<'a, C, A> ChromeosdevicePatchCall<'a, C, A> where 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 Err(Error::FieldClash(field)); - } - } - for (name, 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_ref().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 ["deviceId", "customerId"].iter() { - if let Some(index) = params.iter().position(|t| &t.0 == param_name) { - indices_for_removal.push(index); - } - } - for &index in indices_for_removal.iter() { - params.remove(index); - } - } - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); - let mut request_value_reader = - { - let mut value = json::value::to_value(&self._request); - remove_json_null_values(&mut value); - let mut dst = io::Cursor::new(Vec::with_capacity(128)); - json::to_writer(&mut dst, &value).unwrap(); - dst - }; - let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); - request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_token }); - request_value_reader.seek(io::SeekFrom::Start(0)).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) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()) - .header(ContentType(json_mime_type.clone())) - .header(ContentLength(request_size as u64)) - .body(&mut request_value_reader); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = { - let mut json_response = String::new(); - res.read_to_string(&mut json_response).unwrap(); - match json::from_str(&json_response) { - Ok(decoded) => (res, decoded), - Err(err) => { - dlg.response_json_decode_error(&json_response, &err); - return Err(Error::JsonDecodeError(json_response, err)); - } - } - }; - - dlg.finished(true); - return Ok(result_value) - } - } - } - } - - - /// - /// Sets the *request* property to the given value. - /// - /// Even though 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, A> { - self._request = new_value; - self - } - /// Immutable id of the Google Apps account - /// - /// 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. - pub fn customer_id(mut self, new_value: &str) -> ChromeosdevicePatchCall<'a, C, A> { - self._customer_id = new_value.to_string(); - self - } - /// Immutable id of Chrome OS Device - /// - /// 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. - pub fn device_id(mut self, new_value: &str) -> ChromeosdevicePatchCall<'a, C, A> { - self._device_id = new_value.to_string(); - self - } - /// Restrict information returned to a set of selected fields. - /// - /// Sets the *projection* query property to the given value. - pub fn projection(mut self, new_value: &str) -> ChromeosdevicePatchCall<'a, C, A> { - self._projection = Some(new_value.to_string()); - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> ChromeosdevicePatchCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. - /// * *fields* (query-string) - Selector specifying which 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, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::DirectoryDeviceChromeo`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing 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, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().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` instance. -/// -/// # 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("sed") -/// .doit(); -/// # } -/// ``` -pub struct ChromeosdeviceGetCall<'a, C, A> - where C: '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, A> CallBuilder for ChromeosdeviceGetCall<'a, C, A> {} - -impl<'a, C, A> ChromeosdeviceGetCall<'a, C, A> where 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 Err(Error::FieldClash(field)); - } - } - for (name, 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_ref().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 ["deviceId", "customerId"].iter() { - if let Some(index) = params.iter().position(|t| &t.0 == param_name) { - indices_for_removal.push(index); - } - } - for &index in indices_for_removal.iter() { - params.remove(index); - } - } - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_token }); - let mut req_result = { - let mut client = &mut *self.hub.client.borrow_mut(); - let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = { - let mut json_response = String::new(); - res.read_to_string(&mut json_response).unwrap(); - match json::from_str(&json_response) { - Ok(decoded) => (res, decoded), - Err(err) => { - dlg.response_json_decode_error(&json_response, &err); - return Err(Error::JsonDecodeError(json_response, err)); - } - } - }; - - dlg.finished(true); - return Ok(result_value) - } - } - } - } - - - /// Immutable id of the Google Apps account - /// - /// 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. - pub fn customer_id(mut self, new_value: &str) -> ChromeosdeviceGetCall<'a, C, A> { - self._customer_id = new_value.to_string(); - self - } - /// Immutable id of Chrome OS Device - /// - /// 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. - pub fn device_id(mut self, new_value: &str) -> ChromeosdeviceGetCall<'a, C, A> { - self._device_id = new_value.to_string(); - self - } - /// Restrict information returned to a set of selected fields. - /// - /// Sets the *projection* query property to the given value. - pub fn projection(mut self, new_value: &str) -> ChromeosdeviceGetCall<'a, C, A> { - self._projection = Some(new_value.to_string()); - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> ChromeosdeviceGetCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. - /// * *fields* (query-string) - Selector specifying which 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, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::DirectoryDeviceChromeoReadonly`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing 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, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().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` instance. -/// -/// # 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(); -/// -/// // You can configure optional parameters by calling 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("ea") -/// .doit(); -/// # } -/// ``` -pub struct ChromeosdeviceUpdateCall<'a, C, A> - where C: '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, A> CallBuilder for ChromeosdeviceUpdateCall<'a, C, A> {} - -impl<'a, C, A> ChromeosdeviceUpdateCall<'a, C, A> where 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 Err(Error::FieldClash(field)); - } - } - for (name, 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_ref().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 ["deviceId", "customerId"].iter() { - if let Some(index) = params.iter().position(|t| &t.0 == param_name) { - indices_for_removal.push(index); - } - } - for &index in indices_for_removal.iter() { - params.remove(index); - } - } - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); - let mut request_value_reader = - { - let mut value = json::value::to_value(&self._request); - remove_json_null_values(&mut value); - let mut dst = io::Cursor::new(Vec::with_capacity(128)); - json::to_writer(&mut dst, &value).unwrap(); - dst - }; - let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); - request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_token }); - request_value_reader.seek(io::SeekFrom::Start(0)).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) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()) - .header(ContentType(json_mime_type.clone())) - .header(ContentLength(request_size as u64)) - .body(&mut request_value_reader); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = { - let mut json_response = String::new(); - res.read_to_string(&mut json_response).unwrap(); - match json::from_str(&json_response) { - Ok(decoded) => (res, decoded), - Err(err) => { - dlg.response_json_decode_error(&json_response, &err); - return Err(Error::JsonDecodeError(json_response, err)); - } - } - }; - - dlg.finished(true); - return Ok(result_value) - } - } - } - } - - - /// - /// Sets the *request* property to the given value. - /// - /// Even though 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, A> { - self._request = new_value; - self - } - /// Immutable id of the Google Apps account - /// - /// 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. - pub fn customer_id(mut self, new_value: &str) -> ChromeosdeviceUpdateCall<'a, C, A> { - self._customer_id = new_value.to_string(); - self - } - /// Immutable id of Chrome OS Device - /// - /// 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. - pub fn device_id(mut self, new_value: &str) -> ChromeosdeviceUpdateCall<'a, C, A> { - self._device_id = new_value.to_string(); - self - } - /// Restrict information returned to a set of selected fields. - /// - /// Sets the *projection* query property to the given value. - pub fn projection(mut self, new_value: &str) -> ChromeosdeviceUpdateCall<'a, C, A> { - self._projection = Some(new_value.to_string()); - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> ChromeosdeviceUpdateCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. - /// * *fields* (query-string) - Selector specifying which 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, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::DirectoryDeviceChromeo`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing 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, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().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` instance. -/// -/// # 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, A> - where C: 'a, A: 'a { - - hub: &'a Directory, - _user_key: String, - _delegate: Option<&'a mut Delegate>, - _additional_params: HashMap, - _scopes: BTreeMap -} - -impl<'a, C, A> CallBuilder for VerificationCodeGenerateCall<'a, C, A> {} - -impl<'a, C, A> VerificationCodeGenerateCall<'a, C, A> where 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() { + 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 Err(Error::FieldClash(field)); @@ -15531,13 +21929,14 @@ impl<'a, C, A> VerificationCodeGenerateCall<'a, C, A> where C: BorrowMut = None; for &(name, ref value) in params.iter() { if name == param_name { @@ -15548,459 +21947,8 @@ impl<'a, C, A> VerificationCodeGenerateCall<'a, C, A> where C: BorrowMut = Vec::with_capacity(1); - for param_name in ["userKey"].iter() { - if let Some(index) = params.iter().position(|t| &t.0 == param_name) { - indices_for_removal.push(index); - } - } - for &index in indices_for_removal.iter() { - params.remove(index); - } - } - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_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) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = res; - - dlg.finished(true); - return Ok(result_value) - } - } - } - } - - - /// Email or immutable Id of the user - /// - /// 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. - pub fn user_key(mut self, new_value: &str) -> VerificationCodeGenerateCall<'a, C, A> { - self._user_key = new_value.to_string(); - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> VerificationCodeGenerateCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. - /// * *fields* (query-string) - Selector specifying which 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, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::DirectoryUserSecurity`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing 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, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().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` instance. -/// -/// # 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, A> - where C: 'a, A: 'a { - - hub: &'a Directory, - _user_key: String, - _delegate: Option<&'a mut Delegate>, - _additional_params: HashMap, - _scopes: BTreeMap -} - -impl<'a, C, A> CallBuilder for VerificationCodeInvalidateCall<'a, C, A> {} - -impl<'a, C, A> VerificationCodeInvalidateCall<'a, C, A> where 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 Err(Error::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::DirectoryUserSecurity.as_ref().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() { - if let Some(index) = params.iter().position(|t| &t.0 == param_name) { - indices_for_removal.push(index); - } - } - for &index in indices_for_removal.iter() { - params.remove(index); - } - } - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_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) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = res; - - dlg.finished(true); - return Ok(result_value) - } - } - } - } - - - /// Email or immutable Id of the user - /// - /// 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. - pub fn user_key(mut self, new_value: &str) -> VerificationCodeInvalidateCall<'a, C, A> { - self._user_key = new_value.to_string(); - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> VerificationCodeInvalidateCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. - /// * *fields* (query-string) - Selector specifying which 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, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::DirectoryUserSecurity`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing 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, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().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` instance. -/// -/// # 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, A> - where C: 'a, A: 'a { - - hub: &'a Directory, - _user_key: String, - _delegate: Option<&'a mut Delegate>, - _additional_params: HashMap, - _scopes: BTreeMap -} - -impl<'a, C, A> CallBuilder for VerificationCodeListCall<'a, C, A> {} - -impl<'a, C, A> VerificationCodeListCall<'a, C, A> where 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 Err(Error::FieldClash(field)); - } - } - for (name, 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::DirectoryUserSecurity.as_ref().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() { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["codeId", "userKey"].iter() { if let Some(index) = params.iter().position(|t| &t.0 == param_name) { indices_for_removal.push(index); } @@ -16093,17 +22041,27 @@ impl<'a, C, A> VerificationCodeListCall<'a, C, A> where C: BorrowMut VerificationCodeListCall<'a, C, A> { + pub fn user_key(mut self, new_value: &str) -> AspGetCall<'a, C, A> { self._user_key = new_value.to_string(); self } + /// The unique ID of the ASP. + /// + /// 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. + pub fn code_id(mut self, new_value: i32) -> AspGetCall<'a, C, A> { + self._code_id = new_value; + self + } /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong /// while executing the actual API request. /// /// It should be used to handle progress information, and to implement a certain level of resilience. /// /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> VerificationCodeListCall<'a, C, A> { + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AspGetCall<'a, C, A> { self._delegate = Some(new_value); self } @@ -16124,7 +22082,7 @@ impl<'a, C, A> VerificationCodeListCall<'a, C, A> where C: BorrowMut(mut self, name: T, value: T) -> VerificationCodeListCall<'a, C, A> + pub fn param(mut self, name: T, value: T) -> AspGetCall<'a, C, A> where T: AsRef { self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); self @@ -16141,2239 +22099,7 @@ impl<'a, C, A> VerificationCodeListCall<'a, C, A> where C: BorrowMut(mut self, scope: T) -> VerificationCodeListCall<'a, C, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().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` instance. -/// -/// # 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, A> - where C: 'a, A: 'a { - - hub: &'a Directory, - _group_key: String, - _delegate: Option<&'a mut Delegate>, - _additional_params: HashMap, - _scopes: BTreeMap -} - -impl<'a, C, A> CallBuilder for GroupGetCall<'a, C, A> {} - -impl<'a, C, A> GroupGetCall<'a, C, A> where 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 Err(Error::FieldClash(field)); - } - } - for (name, 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::DirectoryGroupReadonly.as_ref().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() { - if let Some(index) = params.iter().position(|t| &t.0 == param_name) { - indices_for_removal.push(index); - } - } - for &index in indices_for_removal.iter() { - params.remove(index); - } - } - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_token }); - let mut req_result = { - let mut client = &mut *self.hub.client.borrow_mut(); - let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = { - let mut json_response = String::new(); - res.read_to_string(&mut json_response).unwrap(); - match json::from_str(&json_response) { - Ok(decoded) => (res, decoded), - Err(err) => { - dlg.response_json_decode_error(&json_response, &err); - return Err(Error::JsonDecodeError(json_response, err)); - } - } - }; - - dlg.finished(true); - return Ok(result_value) - } - } - } - } - - - /// Email or immutable Id of the group - /// - /// 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. - pub fn group_key(mut self, new_value: &str) -> GroupGetCall<'a, C, A> { - self._group_key = new_value.to_string(); - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> GroupGetCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. - /// * *fields* (query-string) - Selector specifying which 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, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::DirectoryGroupReadonly`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing 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, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().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` instance. -/// -/// # 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("invidunt") -/// .page_token("rebum.") -/// .max_results(-51) -/// .domain("clita") -/// .customer("invidunt") -/// .doit(); -/// # } -/// ``` -pub struct GroupListCall<'a, C, A> - where C: '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, A> CallBuilder for GroupListCall<'a, C, A> {} - -impl<'a, C, A> GroupListCall<'a, C, A> where 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 Err(Error::FieldClash(field)); - } - } - for (name, 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::DirectoryGroupReadonly.as_ref().to_string(), ()); - } - - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_token }); - let mut req_result = { - let mut client = &mut *self.hub.client.borrow_mut(); - let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = { - let mut json_response = String::new(); - res.read_to_string(&mut json_response).unwrap(); - match json::from_str(&json_response) { - Ok(decoded) => (res, decoded), - Err(err) => { - dlg.response_json_decode_error(&json_response, &err); - return Err(Error::JsonDecodeError(json_response, err)); - } - } - }; - - dlg.finished(true); - return Ok(result_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 - /// - /// Sets the *user key* query property to the given value. - pub fn user_key(mut self, new_value: &str) -> GroupListCall<'a, C, A> { - self._user_key = Some(new_value.to_string()); - self - } - /// Token to specify next page in the list - /// - /// Sets the *page token* query property to the given value. - pub fn page_token(mut self, new_value: &str) -> GroupListCall<'a, C, A> { - self._page_token = Some(new_value.to_string()); - self - } - /// Maximum number of results to return. Default is 200 - /// - /// Sets the *max results* query property to the given value. - pub fn max_results(mut self, new_value: i32) -> GroupListCall<'a, C, A> { - self._max_results = Some(new_value); - self - } - /// 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. - /// - /// Sets the *domain* query property to the given value. - pub fn domain(mut self, new_value: &str) -> GroupListCall<'a, C, A> { - self._domain = Some(new_value.to_string()); - self - } - /// 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. - /// - /// Sets the *customer* query property to the given value. - pub fn customer(mut self, new_value: &str) -> GroupListCall<'a, C, A> { - self._customer = Some(new_value.to_string()); - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> GroupListCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. - /// * *fields* (query-string) - Selector specifying which 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, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::DirectoryGroupReadonly`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing 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, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().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` instance. -/// -/// # 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, A> - where C: 'a, A: 'a { - - hub: &'a Directory, - _group_key: String, - _delegate: Option<&'a mut Delegate>, - _additional_params: HashMap, - _scopes: BTreeMap -} - -impl<'a, C, A> CallBuilder for GroupAliaseListCall<'a, C, A> {} - -impl<'a, C, A> GroupAliaseListCall<'a, C, A> where 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 Err(Error::FieldClash(field)); - } - } - for (name, 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::DirectoryGroupReadonly.as_ref().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() { - if let Some(index) = params.iter().position(|t| &t.0 == param_name) { - indices_for_removal.push(index); - } - } - for &index in indices_for_removal.iter() { - params.remove(index); - } - } - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_token }); - let mut req_result = { - let mut client = &mut *self.hub.client.borrow_mut(); - let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = { - let mut json_response = String::new(); - res.read_to_string(&mut json_response).unwrap(); - match json::from_str(&json_response) { - Ok(decoded) => (res, decoded), - Err(err) => { - dlg.response_json_decode_error(&json_response, &err); - return Err(Error::JsonDecodeError(json_response, err)); - } - } - }; - - dlg.finished(true); - return Ok(result_value) - } - } - } - } - - - /// Email or immutable Id of the group - /// - /// 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. - pub fn group_key(mut self, new_value: &str) -> GroupAliaseListCall<'a, C, A> { - self._group_key = new_value.to_string(); - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> GroupAliaseListCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. - /// * *fields* (query-string) - Selector specifying which 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, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::DirectoryGroupReadonly`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing 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, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().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` instance. -/// -/// # 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(); -/// -/// // You can configure optional parameters by calling 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, A> - where C: 'a, A: 'a { - - hub: &'a Directory, - _request: Group, - _group_key: String, - _delegate: Option<&'a mut Delegate>, - _additional_params: HashMap, - _scopes: BTreeMap -} - -impl<'a, C, A> CallBuilder for GroupPatchCall<'a, C, A> {} - -impl<'a, C, A> GroupPatchCall<'a, C, A> where 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 Err(Error::FieldClash(field)); - } - } - for (name, 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::DirectoryGroup.as_ref().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() { - if let Some(index) = params.iter().position(|t| &t.0 == param_name) { - indices_for_removal.push(index); - } - } - for &index in indices_for_removal.iter() { - params.remove(index); - } - } - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); - let mut request_value_reader = - { - let mut value = json::value::to_value(&self._request); - remove_json_null_values(&mut value); - let mut dst = io::Cursor::new(Vec::with_capacity(128)); - json::to_writer(&mut dst, &value).unwrap(); - dst - }; - let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); - request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_token }); - request_value_reader.seek(io::SeekFrom::Start(0)).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) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()) - .header(ContentType(json_mime_type.clone())) - .header(ContentLength(request_size as u64)) - .body(&mut request_value_reader); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = { - let mut json_response = String::new(); - res.read_to_string(&mut json_response).unwrap(); - match json::from_str(&json_response) { - Ok(decoded) => (res, decoded), - Err(err) => { - dlg.response_json_decode_error(&json_response, &err); - return Err(Error::JsonDecodeError(json_response, err)); - } - } - }; - - dlg.finished(true); - return Ok(result_value) - } - } - } - } - - - /// - /// Sets the *request* property to the given value. - /// - /// Even though 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, A> { - self._request = new_value; - self - } - /// Email or immutable Id of the group. If Id, it should match with id of group object - /// - /// 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. - pub fn group_key(mut self, new_value: &str) -> GroupPatchCall<'a, C, A> { - self._group_key = new_value.to_string(); - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> GroupPatchCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. - /// * *fields* (query-string) - Selector specifying which 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, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::DirectoryGroup`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing 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, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().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` instance. -/// -/// # 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(); -/// -/// // You can configure optional parameters by calling 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, A> - where C: 'a, A: 'a { - - hub: &'a Directory, - _request: Group, - _group_key: String, - _delegate: Option<&'a mut Delegate>, - _additional_params: HashMap, - _scopes: BTreeMap -} - -impl<'a, C, A> CallBuilder for GroupUpdateCall<'a, C, A> {} - -impl<'a, C, A> GroupUpdateCall<'a, C, A> where 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 Err(Error::FieldClash(field)); - } - } - for (name, 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::DirectoryGroup.as_ref().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() { - if let Some(index) = params.iter().position(|t| &t.0 == param_name) { - indices_for_removal.push(index); - } - } - for &index in indices_for_removal.iter() { - params.remove(index); - } - } - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); - let mut request_value_reader = - { - let mut value = json::value::to_value(&self._request); - remove_json_null_values(&mut value); - let mut dst = io::Cursor::new(Vec::with_capacity(128)); - json::to_writer(&mut dst, &value).unwrap(); - dst - }; - let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); - request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_token }); - request_value_reader.seek(io::SeekFrom::Start(0)).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) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()) - .header(ContentType(json_mime_type.clone())) - .header(ContentLength(request_size as u64)) - .body(&mut request_value_reader); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = { - let mut json_response = String::new(); - res.read_to_string(&mut json_response).unwrap(); - match json::from_str(&json_response) { - Ok(decoded) => (res, decoded), - Err(err) => { - dlg.response_json_decode_error(&json_response, &err); - return Err(Error::JsonDecodeError(json_response, err)); - } - } - }; - - dlg.finished(true); - return Ok(result_value) - } - } - } - } - - - /// - /// Sets the *request* property to the given value. - /// - /// Even though 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, A> { - self._request = new_value; - self - } - /// Email or immutable Id of the group. If Id, it should match with id of group object - /// - /// 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. - pub fn group_key(mut self, new_value: &str) -> GroupUpdateCall<'a, C, A> { - self._group_key = new_value.to_string(); - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> GroupUpdateCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. - /// * *fields* (query-string) - Selector specifying which 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, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::DirectoryGroup`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing 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, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().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` instance. -/// -/// # 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, A> - where C: 'a, A: 'a { - - hub: &'a Directory, - _group_key: String, - _delegate: Option<&'a mut Delegate>, - _additional_params: HashMap, - _scopes: BTreeMap -} - -impl<'a, C, A> CallBuilder for GroupDeleteCall<'a, C, A> {} - -impl<'a, C, A> GroupDeleteCall<'a, C, A> where 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 Err(Error::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::DirectoryGroup.as_ref().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() { - if let Some(index) = params.iter().position(|t| &t.0 == param_name) { - indices_for_removal.push(index); - } - } - for &index in indices_for_removal.iter() { - params.remove(index); - } - } - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_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) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = res; - - dlg.finished(true); - return Ok(result_value) - } - } - } - } - - - /// Email or immutable Id of the group - /// - /// 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. - pub fn group_key(mut self, new_value: &str) -> GroupDeleteCall<'a, C, A> { - self._group_key = new_value.to_string(); - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> GroupDeleteCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. - /// * *fields* (query-string) - Selector specifying which 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, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::DirectoryGroup`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing 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, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().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` instance. -/// -/// # 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(); -/// -/// // You can configure optional parameters by calling 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, A> - where C: 'a, A: 'a { - - hub: &'a Directory, - _request: Alias, - _group_key: String, - _delegate: Option<&'a mut Delegate>, - _additional_params: HashMap, - _scopes: BTreeMap -} - -impl<'a, C, A> CallBuilder for GroupAliaseInsertCall<'a, C, A> {} - -impl<'a, C, A> GroupAliaseInsertCall<'a, C, A> where 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 Err(Error::FieldClash(field)); - } - } - for (name, 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::DirectoryGroup.as_ref().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() { - if let Some(index) = params.iter().position(|t| &t.0 == param_name) { - indices_for_removal.push(index); - } - } - for &index in indices_for_removal.iter() { - params.remove(index); - } - } - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); - let mut request_value_reader = - { - let mut value = json::value::to_value(&self._request); - remove_json_null_values(&mut value); - let mut dst = io::Cursor::new(Vec::with_capacity(128)); - json::to_writer(&mut dst, &value).unwrap(); - dst - }; - let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); - request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_token }); - request_value_reader.seek(io::SeekFrom::Start(0)).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) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()) - .header(ContentType(json_mime_type.clone())) - .header(ContentLength(request_size as u64)) - .body(&mut request_value_reader); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = { - let mut json_response = String::new(); - res.read_to_string(&mut json_response).unwrap(); - match json::from_str(&json_response) { - Ok(decoded) => (res, decoded), - Err(err) => { - dlg.response_json_decode_error(&json_response, &err); - return Err(Error::JsonDecodeError(json_response, err)); - } - } - }; - - dlg.finished(true); - return Ok(result_value) - } - } - } - } - - - /// - /// Sets the *request* property to the given value. - /// - /// Even though 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, A> { - self._request = new_value; - self - } - /// Email or immutable Id of the group - /// - /// 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. - pub fn group_key(mut self, new_value: &str) -> GroupAliaseInsertCall<'a, C, A> { - self._group_key = new_value.to_string(); - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> GroupAliaseInsertCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. - /// * *fields* (query-string) - Selector specifying which 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, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::DirectoryGroup`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing 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, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().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` instance. -/// -/// # 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, A> - where C: 'a, A: 'a { - - hub: &'a Directory, - _group_key: String, - _alias: String, - _delegate: Option<&'a mut Delegate>, - _additional_params: HashMap, - _scopes: BTreeMap -} - -impl<'a, C, A> CallBuilder for GroupAliaseDeleteCall<'a, C, A> {} - -impl<'a, C, A> GroupAliaseDeleteCall<'a, C, A> where 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 Err(Error::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::DirectoryGroup.as_ref().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 ["alias", "groupKey"].iter() { - if let Some(index) = params.iter().position(|t| &t.0 == param_name) { - indices_for_removal.push(index); - } - } - for &index in indices_for_removal.iter() { - params.remove(index); - } - } - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_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) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = res; - - dlg.finished(true); - return Ok(result_value) - } - } - } - } - - - /// Email or immutable Id of the group - /// - /// 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. - pub fn group_key(mut self, new_value: &str) -> GroupAliaseDeleteCall<'a, C, A> { - self._group_key = new_value.to_string(); - self - } - /// The alias to be removed - /// - /// 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. - pub fn alias(mut self, new_value: &str) -> GroupAliaseDeleteCall<'a, C, A> { - self._alias = new_value.to_string(); - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> GroupAliaseDeleteCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. - /// * *fields* (query-string) - Selector specifying which 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, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::DirectoryGroup`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing 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, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().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` instance. -/// -/// # 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(); -/// -/// // You can configure optional parameters by calling 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, A> - where C: 'a, A: 'a { - - hub: &'a Directory, - _request: Group, - _delegate: Option<&'a mut Delegate>, - _additional_params: HashMap, - _scopes: BTreeMap -} - -impl<'a, C, A> CallBuilder for GroupInsertCall<'a, C, A> {} - -impl<'a, C, A> GroupInsertCall<'a, C, A> where 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 Err(Error::FieldClash(field)); - } - } - for (name, 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::DirectoryGroup.as_ref().to_string(), ()); - } - - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); - let mut request_value_reader = - { - let mut value = json::value::to_value(&self._request); - remove_json_null_values(&mut value); - let mut dst = io::Cursor::new(Vec::with_capacity(128)); - json::to_writer(&mut dst, &value).unwrap(); - dst - }; - let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); - request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_token }); - request_value_reader.seek(io::SeekFrom::Start(0)).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) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()) - .header(ContentType(json_mime_type.clone())) - .header(ContentLength(request_size as u64)) - .body(&mut request_value_reader); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = { - let mut json_response = String::new(); - res.read_to_string(&mut json_response).unwrap(); - match json::from_str(&json_response) { - Ok(decoded) => (res, decoded), - Err(err) => { - dlg.response_json_decode_error(&json_response, &err); - return Err(Error::JsonDecodeError(json_response, err)); - } - } - }; - - dlg.finished(true); - return Ok(result_value) - } - } - } - } - - - /// - /// Sets the *request* property to the given value. - /// - /// Even though 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, A> { - self._request = new_value; - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> GroupInsertCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. - /// * *fields* (query-string) - Selector specifying which 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, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::DirectoryGroup`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing 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, A> + pub fn add_scope(mut self, scope: T) -> AspGetCall<'a, C, A> where T: AsRef { self._scopes.insert(scope.as_ref().to_string(), ()); self @@ -18407,7 +22133,7 @@ impl<'a, C, A> GroupInsertCall<'a, C, A> where C: BorrowMut, A: o /// // You can configure optional parameters by calling 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", -91) +/// let result = hub.asps().delete("userKey", -85) /// .doit(); /// # } /// ``` @@ -18854,10 +22580,10 @@ impl<'a, C, A> AspListCall<'a, C, A> where C: BorrowMut, A: oauth } -/// Get information about an ASP issued by a user. +/// Lists the domains of the customer. /// -/// A builder for the *get* method supported by a *asp* resource. -/// It is not used directly, but through a `AspMethods` instance. +/// A builder for the *list* method supported by a *domain* resource. +/// It is not used directly, but through a `DomainMethods` instance. /// /// # Example /// @@ -18880,28 +22606,27 @@ impl<'a, C, A> AspListCall<'a, C, A> where C: BorrowMut, A: oauth /// // You can configure optional parameters by calling 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", -50) +/// let result = hub.domains().list("customer") /// .doit(); /// # } /// ``` -pub struct AspGetCall<'a, C, A> +pub struct DomainListCall<'a, C, A> where C: 'a, A: 'a { hub: &'a Directory, - _user_key: String, - _code_id: i32, + _customer: String, _delegate: Option<&'a mut Delegate>, _additional_params: HashMap, _scopes: BTreeMap } -impl<'a, C, A> CallBuilder for AspGetCall<'a, C, A> {} +impl<'a, C, A> CallBuilder for DomainListCall<'a, C, A> {} -impl<'a, C, A> AspGetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { +impl<'a, C, A> DomainListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { /// Perform the operation you have build so far. - pub fn doit(mut self) -> Result<(hyper::client::Response, Asp)> { + pub fn doit(mut self) -> Result<(hyper::client::Response, Domains2)> { use std::io::{Read, Seek}; use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; let mut dd = DefaultDelegate; @@ -18909,258 +22634,11 @@ impl<'a, C, A> AspGetCall<'a, C, A> where C: BorrowMut, A: oauth2 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 Err(Error::FieldClash(field)); - } - } - for (name, 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::DirectoryUserSecurity.as_ref().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 ["codeId", "userKey"].iter() { - if let Some(index) = params.iter().position(|t| &t.0 == param_name) { - indices_for_removal.push(index); - } - } - for &index in indices_for_removal.iter() { - params.remove(index); - } - } - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_token }); - let mut req_result = { - let mut client = &mut *self.hub.client.borrow_mut(); - let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = { - let mut json_response = String::new(); - res.read_to_string(&mut json_response).unwrap(); - match json::from_str(&json_response) { - Ok(decoded) => (res, decoded), - Err(err) => { - dlg.response_json_decode_error(&json_response, &err); - return Err(Error::JsonDecodeError(json_response, err)); - } - } - }; - - dlg.finished(true); - return Ok(result_value) - } - } - } - } - - - /// Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID. - /// - /// 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. - pub fn user_key(mut self, new_value: &str) -> AspGetCall<'a, C, A> { - self._user_key = new_value.to_string(); - self - } - /// The unique ID of the ASP. - /// - /// 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. - pub fn code_id(mut self, new_value: i32) -> AspGetCall<'a, C, A> { - self._code_id = new_value; - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> AspGetCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. - /// * *fields* (query-string) - Selector specifying which 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, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::DirectoryUserSecurity`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing 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, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().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` instance. -/// -/// # 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, A> - where C: 'a, A: 'a { - - hub: &'a Directory, - _customer_id: String, - _delegate: Option<&'a mut Delegate>, - _additional_params: HashMap, - _scopes: BTreeMap -} - -impl<'a, C, A> CallBuilder for SchemaListCall<'a, C, A> {} - -impl<'a, C, A> SchemaListCall<'a, C, A> where 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", + dlg.begin(MethodInfo { id: "directory.domains.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() { + params.push(("customer", self._customer.to_string())); + for &field in ["alt", "customer"].iter() { if self._additional_params.contains_key(field) { dlg.finished(false); return Err(Error::FieldClash(field)); @@ -19172,12 +22650,12 @@ impl<'a, C, A> SchemaListCall<'a, C, A> where C: BorrowMut, A: oa params.push(("alt", "json".to_string())); - let mut url = "https://www.googleapis.com/admin/directory/v1/customer/{customerId}/schemas".to_string(); + let mut url = "https://www.googleapis.com/admin/directory/v1/customer/{customer}/domains".to_string(); if self._scopes.len() == 0 { - self._scopes.insert(Scope::DirectoryUserschemaReadonly.as_ref().to_string(), ()); + self._scopes.insert(Scope::DirectoryDomainReadonly.as_ref().to_string(), ()); } - for &(find_this, param_name) in [("{customerId}", "customerId")].iter() { + 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 { @@ -19189,7 +22667,7 @@ impl<'a, C, A> SchemaListCall<'a, C, A> where C: BorrowMut, A: oa } { let mut indices_for_removal: Vec = Vec::with_capacity(1); - for param_name in ["customerId"].iter() { + for param_name in ["customer"].iter() { if let Some(index) = params.iter().position(|t| &t.0 == param_name) { indices_for_removal.push(index); } @@ -19276,14 +22754,14 @@ impl<'a, C, A> SchemaListCall<'a, C, A> where C: BorrowMut, A: oa } - /// Immutable id of the Google Apps account + /// Immutable id of the Google Apps account. /// - /// Sets the *customer id* path property to the given 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. - pub fn customer_id(mut self, new_value: &str) -> SchemaListCall<'a, C, A> { - self._customer_id = new_value.to_string(); + pub fn customer(mut self, new_value: &str) -> DomainListCall<'a, C, A> { + self._customer = new_value.to_string(); self } /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong @@ -19292,7 +22770,7 @@ impl<'a, C, A> SchemaListCall<'a, C, A> where C: BorrowMut, A: oa /// It should be used to handle progress information, and to implement a certain level of resilience. /// /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> SchemaListCall<'a, C, A> { + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DomainListCall<'a, C, A> { self._delegate = Some(new_value); self } @@ -19313,7 +22791,7 @@ impl<'a, C, A> SchemaListCall<'a, C, A> where C: BorrowMut, A: oa /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. /// * *fields* (query-string) - Selector specifying which 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, A> + pub fn param(mut self, name: T, value: T) -> DomainListCall<'a, C, A> where T: AsRef { self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); self @@ -19322,7 +22800,7 @@ impl<'a, C, A> SchemaListCall<'a, C, A> where C: BorrowMut, A: oa /// Identifies the authorization scope for the method you are building. /// /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::DirectoryUserschemaReadonly`. + /// `Scope::DirectoryDomainReadonly`. /// /// The `scope` will be added to a set of scopes. This is important as one can maintain access /// tokens for more than one scope. @@ -19330,7 +22808,1759 @@ impl<'a, C, A> SchemaListCall<'a, C, A> where C: BorrowMut, A: oa /// Usually there is more than one suitable scope to authorize an operation, some of which may /// encompass more rights than others. For example, for listing 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, A> + pub fn add_scope(mut self, scope: T) -> DomainListCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Retrives a domain of the customer. +/// +/// A builder for the *get* method supported by a *domain* resource. +/// It is not used directly, but through a `DomainMethods` instance. +/// +/// # 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.domains().get("customer", "domainName") +/// .doit(); +/// # } +/// ``` +pub struct DomainGetCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Directory, + _customer: String, + _domain_name: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for DomainGetCall<'a, C, A> {} + +impl<'a, C, A> DomainGetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Domains)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.domains.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(("domainName", self._domain_name.to_string())); + for &field in ["alt", "customer", "domainName"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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}/domains/{domainName}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDomainReadonly.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{customer}", "customer"), ("{domainName}", "domainName")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["domainName", "customer"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Immutable id of the Google Apps account. + /// + /// 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. + pub fn customer(mut self, new_value: &str) -> DomainGetCall<'a, C, A> { + self._customer = new_value.to_string(); + self + } + /// Name of domain to be retrieved + /// + /// Sets the *domain 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 domain_name(mut self, new_value: &str) -> DomainGetCall<'a, C, A> { + self._domain_name = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DomainGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> DomainGetCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::DirectoryDomainReadonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DomainGetCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Inserts a domain of the customer. +/// +/// A builder for the *insert* method supported by a *domain* resource. +/// It is not used directly, but through a `DomainMethods` instance. +/// +/// # 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::Domains; +/// # #[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 = Domains::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.domains().insert(req, "customer") +/// .doit(); +/// # } +/// ``` +pub struct DomainInsertCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Directory, + _request: Domains, + _customer: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for DomainInsertCall<'a, C, A> {} + +impl<'a, C, A> DomainInsertCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Domains)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.domains.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("customer", self._customer.to_string())); + for &field in ["alt", "customer"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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}/domains".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDomain.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: Domains) -> DomainInsertCall<'a, C, A> { + self._request = new_value; + self + } + /// Immutable id of the Google Apps account. + /// + /// 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. + pub fn customer(mut self, new_value: &str) -> DomainInsertCall<'a, C, A> { + self._customer = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DomainInsertCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> DomainInsertCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::DirectoryDomain`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DomainInsertCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Deletes a domain of the customer. +/// +/// A builder for the *delete* method supported by a *domain* resource. +/// It is not used directly, but through a `DomainMethods` instance. +/// +/// # 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.domains().delete("customer", "domainName") +/// .doit(); +/// # } +/// ``` +pub struct DomainDeleteCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Directory, + _customer: String, + _domain_name: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for DomainDeleteCall<'a, C, A> {} + +impl<'a, C, A> DomainDeleteCall<'a, C, A> where 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.domains.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(("domainName", self._domain_name.to_string())); + for &field in ["customer", "domainName"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::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}/domains/{domainName}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDomain.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{customer}", "customer"), ("{domainName}", "domainName")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["domainName", "customer"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = res; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Immutable id of the Google Apps account. + /// + /// 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. + pub fn customer(mut self, new_value: &str) -> DomainDeleteCall<'a, C, A> { + self._customer = new_value.to_string(); + self + } + /// Name of domain to be deleted + /// + /// Sets the *domain 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 domain_name(mut self, new_value: &str) -> DomainDeleteCall<'a, C, A> { + self._domain_name = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DomainDeleteCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> DomainDeleteCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::DirectoryDomain`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DomainDeleteCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Inserts a Domain alias of the customer. +/// +/// A builder for the *insert* method supported by a *domainAliase* resource. +/// It is not used directly, but through a `DomainAliaseMethods` instance. +/// +/// # 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::DomainAlias; +/// # #[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 = DomainAlias::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.domain_aliases().insert(req, "customer") +/// .doit(); +/// # } +/// ``` +pub struct DomainAliaseInsertCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Directory, + _request: DomainAlias, + _customer: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for DomainAliaseInsertCall<'a, C, A> {} + +impl<'a, C, A> DomainAliaseInsertCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, DomainAlias)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.domainAliases.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("customer", self._customer.to_string())); + for &field in ["alt", "customer"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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}/domainaliases".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDomain.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: DomainAlias) -> DomainAliaseInsertCall<'a, C, A> { + self._request = new_value; + self + } + /// Immutable id of the Google Apps account. + /// + /// 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. + pub fn customer(mut self, new_value: &str) -> DomainAliaseInsertCall<'a, C, A> { + self._customer = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DomainAliaseInsertCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> DomainAliaseInsertCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::DirectoryDomain`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DomainAliaseInsertCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Retrieves a domain alias of the customer. +/// +/// A builder for the *get* method supported by a *domainAliase* resource. +/// It is not used directly, but through a `DomainAliaseMethods` instance. +/// +/// # 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.domain_aliases().get("customer", "domainAliasName") +/// .doit(); +/// # } +/// ``` +pub struct DomainAliaseGetCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Directory, + _customer: String, + _domain_alias_name: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for DomainAliaseGetCall<'a, C, A> {} + +impl<'a, C, A> DomainAliaseGetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, DomainAlias)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.domainAliases.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(("domainAliasName", self._domain_alias_name.to_string())); + for &field in ["alt", "customer", "domainAliasName"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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}/domainaliases/{domainAliasName}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDomainReadonly.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{customer}", "customer"), ("{domainAliasName}", "domainAliasName")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["domainAliasName", "customer"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Immutable id of the Google Apps account. + /// + /// 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. + pub fn customer(mut self, new_value: &str) -> DomainAliaseGetCall<'a, C, A> { + self._customer = new_value.to_string(); + self + } + /// Name of domain alias to be retrieved. + /// + /// Sets the *domain alias 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 domain_alias_name(mut self, new_value: &str) -> DomainAliaseGetCall<'a, C, A> { + self._domain_alias_name = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DomainAliaseGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> DomainAliaseGetCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::DirectoryDomainReadonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DomainAliaseGetCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Lists the domain aliases of the customer. +/// +/// A builder for the *list* method supported by a *domainAliase* resource. +/// It is not used directly, but through a `DomainAliaseMethods` instance. +/// +/// # 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.domain_aliases().list("customer") +/// .parent_domain_name("nonumy") +/// .doit(); +/// # } +/// ``` +pub struct DomainAliaseListCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Directory, + _customer: String, + _parent_domain_name: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for DomainAliaseListCall<'a, C, A> {} + +impl<'a, C, A> DomainAliaseListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, DomainAliases)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.domainAliases.list", + 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())); + if let Some(value) = self._parent_domain_name { + params.push(("parentDomainName", value.to_string())); + } + for &field in ["alt", "customer", "parentDomainName"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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}/domainaliases".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDomainReadonly.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Immutable id of the Google Apps account. + /// + /// 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. + pub fn customer(mut self, new_value: &str) -> DomainAliaseListCall<'a, C, A> { + self._customer = new_value.to_string(); + self + } + /// Name of the parent domain for which domain aliases are to be fetched. + /// + /// Sets the *parent domain name* query property to the given value. + pub fn parent_domain_name(mut self, new_value: &str) -> DomainAliaseListCall<'a, C, A> { + self._parent_domain_name = Some(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DomainAliaseListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> DomainAliaseListCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::DirectoryDomainReadonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DomainAliaseListCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Deletes a Domain Alias of the customer. +/// +/// A builder for the *delete* method supported by a *domainAliase* resource. +/// It is not used directly, but through a `DomainAliaseMethods` instance. +/// +/// # 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.domain_aliases().delete("customer", "domainAliasName") +/// .doit(); +/// # } +/// ``` +pub struct DomainAliaseDeleteCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Directory, + _customer: String, + _domain_alias_name: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for DomainAliaseDeleteCall<'a, C, A> {} + +impl<'a, C, A> DomainAliaseDeleteCall<'a, C, A> where 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.domainAliases.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(("domainAliasName", self._domain_alias_name.to_string())); + for &field in ["customer", "domainAliasName"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::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}/domainaliases/{domainAliasName}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryDomain.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{customer}", "customer"), ("{domainAliasName}", "domainAliasName")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["domainAliasName", "customer"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = res; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Immutable id of the Google Apps account. + /// + /// 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. + pub fn customer(mut self, new_value: &str) -> DomainAliaseDeleteCall<'a, C, A> { + self._customer = new_value.to_string(); + self + } + /// Name of domain alias to be retrieved. + /// + /// Sets the *domain alias 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 domain_alias_name(mut self, new_value: &str) -> DomainAliaseDeleteCall<'a, C, A> { + self._domain_alias_name = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DomainAliaseDeleteCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> DomainAliaseDeleteCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::DirectoryDomain`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DomainAliaseDeleteCall<'a, C, A> where T: AsRef { self._scopes.insert(scope.as_ref().to_string(), ()); self @@ -19586,789 +24816,6 @@ impl<'a, C, A> SchemaGetCall<'a, C, A> where C: BorrowMut, A: oau } -/// 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` instance. -/// -/// # 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(); -/// -/// // You can configure optional parameters by calling 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, A> - where C: '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, A> CallBuilder for SchemaPatchCall<'a, C, A> {} - -impl<'a, C, A> SchemaPatchCall<'a, C, A> where 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 Err(Error::FieldClash(field)); - } - } - for (name, 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::DirectoryUserschema.as_ref().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 ["schemaKey", "customerId"].iter() { - if let Some(index) = params.iter().position(|t| &t.0 == param_name) { - indices_for_removal.push(index); - } - } - for &index in indices_for_removal.iter() { - params.remove(index); - } - } - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); - let mut request_value_reader = - { - let mut value = json::value::to_value(&self._request); - remove_json_null_values(&mut value); - let mut dst = io::Cursor::new(Vec::with_capacity(128)); - json::to_writer(&mut dst, &value).unwrap(); - dst - }; - let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); - request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_token }); - request_value_reader.seek(io::SeekFrom::Start(0)).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) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()) - .header(ContentType(json_mime_type.clone())) - .header(ContentLength(request_size as u64)) - .body(&mut request_value_reader); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = { - let mut json_response = String::new(); - res.read_to_string(&mut json_response).unwrap(); - match json::from_str(&json_response) { - Ok(decoded) => (res, decoded), - Err(err) => { - dlg.response_json_decode_error(&json_response, &err); - return Err(Error::JsonDecodeError(json_response, err)); - } - } - }; - - dlg.finished(true); - return Ok(result_value) - } - } - } - } - - - /// - /// Sets the *request* property to the given value. - /// - /// Even though 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, A> { - self._request = new_value; - self - } - /// Immutable id of the Google Apps account - /// - /// 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. - pub fn customer_id(mut self, new_value: &str) -> SchemaPatchCall<'a, C, A> { - self._customer_id = new_value.to_string(); - self - } - /// Name or immutable Id of the schema. - /// - /// 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. - pub fn schema_key(mut self, new_value: &str) -> SchemaPatchCall<'a, C, A> { - self._schema_key = new_value.to_string(); - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> SchemaPatchCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. - /// * *fields* (query-string) - Selector specifying which 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, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::DirectoryUserschema`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing 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, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().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` instance. -/// -/// # 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(); -/// -/// // You can configure optional parameters by calling 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, A> - where C: 'a, A: 'a { - - hub: &'a Directory, - _request: Schema, - _customer_id: String, - _delegate: Option<&'a mut Delegate>, - _additional_params: HashMap, - _scopes: BTreeMap -} - -impl<'a, C, A> CallBuilder for SchemaInsertCall<'a, C, A> {} - -impl<'a, C, A> SchemaInsertCall<'a, C, A> where 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 Err(Error::FieldClash(field)); - } - } - for (name, 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::DirectoryUserschema.as_ref().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() { - if let Some(index) = params.iter().position(|t| &t.0 == param_name) { - indices_for_removal.push(index); - } - } - for &index in indices_for_removal.iter() { - params.remove(index); - } - } - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); - let mut request_value_reader = - { - let mut value = json::value::to_value(&self._request); - remove_json_null_values(&mut value); - let mut dst = io::Cursor::new(Vec::with_capacity(128)); - json::to_writer(&mut dst, &value).unwrap(); - dst - }; - let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); - request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_token }); - request_value_reader.seek(io::SeekFrom::Start(0)).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) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()) - .header(ContentType(json_mime_type.clone())) - .header(ContentLength(request_size as u64)) - .body(&mut request_value_reader); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = { - let mut json_response = String::new(); - res.read_to_string(&mut json_response).unwrap(); - match json::from_str(&json_response) { - Ok(decoded) => (res, decoded), - Err(err) => { - dlg.response_json_decode_error(&json_response, &err); - return Err(Error::JsonDecodeError(json_response, err)); - } - } - }; - - dlg.finished(true); - return Ok(result_value) - } - } - } - } - - - /// - /// Sets the *request* property to the given value. - /// - /// Even though 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, A> { - self._request = new_value; - self - } - /// Immutable id of the Google Apps account - /// - /// 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. - pub fn customer_id(mut self, new_value: &str) -> SchemaInsertCall<'a, C, A> { - self._customer_id = new_value.to_string(); - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> SchemaInsertCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. - /// * *fields* (query-string) - Selector specifying which 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, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::DirectoryUserschema`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing 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, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().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` instance. -/// -/// # 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, A> - where C: '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, A> CallBuilder for SchemaDeleteCall<'a, C, A> {} - -impl<'a, C, A> SchemaDeleteCall<'a, C, A> where 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 Err(Error::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::DirectoryUserschema.as_ref().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 ["schemaKey", "customerId"].iter() { - if let Some(index) = params.iter().position(|t| &t.0 == param_name) { - indices_for_removal.push(index); - } - } - for &index in indices_for_removal.iter() { - params.remove(index); - } - } - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_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) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = res; - - dlg.finished(true); - return Ok(result_value) - } - } - } - } - - - /// Immutable id of the Google Apps account - /// - /// 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. - pub fn customer_id(mut self, new_value: &str) -> SchemaDeleteCall<'a, C, A> { - self._customer_id = new_value.to_string(); - self - } - /// Name or immutable Id of the schema - /// - /// 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. - pub fn schema_key(mut self, new_value: &str) -> SchemaDeleteCall<'a, C, A> { - self._schema_key = new_value.to_string(); - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> SchemaDeleteCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. - /// * *fields* (query-string) - Selector specifying which 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, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::DirectoryUserschema`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing 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, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().to_string(), ()); - self - } -} - - /// Update schema /// /// A builder for the *update* method supported by a *schema* resource. @@ -20648,3 +25095,2281 @@ impl<'a, C, A> SchemaUpdateCall<'a, C, A> where C: BorrowMut, A: } +/// 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` instance. +/// +/// # 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, A> + where C: 'a, A: 'a { + + hub: &'a Directory, + _customer_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for SchemaListCall<'a, C, A> {} + +impl<'a, C, A> SchemaListCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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::DirectoryUserschemaReadonly.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Immutable id of the Google Apps account + /// + /// 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. + pub fn customer_id(mut self, new_value: &str) -> SchemaListCall<'a, C, A> { + self._customer_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> SchemaListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::DirectoryUserschemaReadonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # 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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: '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, A> CallBuilder for SchemaPatchCall<'a, C, A> {} + +impl<'a, C, A> SchemaPatchCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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::DirectoryUserschema.as_ref().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 ["schemaKey", "customerId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// Immutable id of the Google Apps account + /// + /// 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. + pub fn customer_id(mut self, new_value: &str) -> SchemaPatchCall<'a, C, A> { + self._customer_id = new_value.to_string(); + self + } + /// Name or immutable Id of the schema. + /// + /// 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. + pub fn schema_key(mut self, new_value: &str) -> SchemaPatchCall<'a, C, A> { + self._schema_key = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> SchemaPatchCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::DirectoryUserschema`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # 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, A> + where C: '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, A> CallBuilder for SchemaDeleteCall<'a, C, A> {} + +impl<'a, C, A> SchemaDeleteCall<'a, C, A> where 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 Err(Error::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::DirectoryUserschema.as_ref().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 ["schemaKey", "customerId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = res; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Immutable id of the Google Apps account + /// + /// 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. + pub fn customer_id(mut self, new_value: &str) -> SchemaDeleteCall<'a, C, A> { + self._customer_id = new_value.to_string(); + self + } + /// Name or immutable Id of the schema + /// + /// 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. + pub fn schema_key(mut self, new_value: &str) -> SchemaDeleteCall<'a, C, A> { + self._schema_key = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> SchemaDeleteCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::DirectoryUserschema`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # 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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: 'a, A: 'a { + + hub: &'a Directory, + _request: Schema, + _customer_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for SchemaInsertCall<'a, C, A> {} + +impl<'a, C, A> SchemaInsertCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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::DirectoryUserschema.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// Immutable id of the Google Apps account + /// + /// 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. + pub fn customer_id(mut self, new_value: &str) -> SchemaInsertCall<'a, C, A> { + self._customer_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> SchemaInsertCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::DirectoryUserschema`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # 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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: 'a, A: 'a { + + hub: &'a Directory, + _request: Channel, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ChannelStopCall<'a, C, A> {} + +impl<'a, C, A> ChannelStopCall<'a, C, A> where 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 Err(Error::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::DirectoryUser.as_ref().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = res; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ChannelStopCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::DirectoryUser`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Creates a role assignment. +/// +/// A builder for the *insert* method supported by a *roleAssignment* resource. +/// It is not used directly, but through a `RoleAssignmentMethods` instance. +/// +/// # 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::RoleAssignment; +/// # #[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 = RoleAssignment::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.role_assignments().insert(req, "customer") +/// .doit(); +/// # } +/// ``` +pub struct RoleAssignmentInsertCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Directory, + _request: RoleAssignment, + _customer: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for RoleAssignmentInsertCall<'a, C, A> {} + +impl<'a, C, A> RoleAssignmentInsertCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, RoleAssignment)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.roleAssignments.insert", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("customer", self._customer.to_string())); + for &field in ["alt", "customer"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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}/roleassignments".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryRolemanagement.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: RoleAssignment) -> RoleAssignmentInsertCall<'a, C, A> { + self._request = new_value; + self + } + /// Immutable ID of the Google Apps account. + /// + /// 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. + pub fn customer(mut self, new_value: &str) -> RoleAssignmentInsertCall<'a, C, A> { + self._customer = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> RoleAssignmentInsertCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> RoleAssignmentInsertCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::DirectoryRolemanagement`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> RoleAssignmentInsertCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Retrieve a role assignment. +/// +/// A builder for the *get* method supported by a *roleAssignment* resource. +/// It is not used directly, but through a `RoleAssignmentMethods` instance. +/// +/// # 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.role_assignments().get("customer", "roleAssignmentId") +/// .doit(); +/// # } +/// ``` +pub struct RoleAssignmentGetCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Directory, + _customer: String, + _role_assignment_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for RoleAssignmentGetCall<'a, C, A> {} + +impl<'a, C, A> RoleAssignmentGetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, RoleAssignment)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.roleAssignments.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(("roleAssignmentId", self._role_assignment_id.to_string())); + for &field in ["alt", "customer", "roleAssignmentId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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}/roleassignments/{roleAssignmentId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryRolemanagementReadonly.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{customer}", "customer"), ("{roleAssignmentId}", "roleAssignmentId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["roleAssignmentId", "customer"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Immutable ID of the Google Apps account. + /// + /// 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. + pub fn customer(mut self, new_value: &str) -> RoleAssignmentGetCall<'a, C, A> { + self._customer = new_value.to_string(); + self + } + /// Immutable ID of the role assignment. + /// + /// Sets the *role assignment id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn role_assignment_id(mut self, new_value: &str) -> RoleAssignmentGetCall<'a, C, A> { + self._role_assignment_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> RoleAssignmentGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> RoleAssignmentGetCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::DirectoryRolemanagementReadonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> RoleAssignmentGetCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Deletes a role assignment. +/// +/// A builder for the *delete* method supported by a *roleAssignment* resource. +/// It is not used directly, but through a `RoleAssignmentMethods` instance. +/// +/// # 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.role_assignments().delete("customer", "roleAssignmentId") +/// .doit(); +/// # } +/// ``` +pub struct RoleAssignmentDeleteCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Directory, + _customer: String, + _role_assignment_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for RoleAssignmentDeleteCall<'a, C, A> {} + +impl<'a, C, A> RoleAssignmentDeleteCall<'a, C, A> where 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.roleAssignments.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(("roleAssignmentId", self._role_assignment_id.to_string())); + for &field in ["customer", "roleAssignmentId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::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}/roleassignments/{roleAssignmentId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryRolemanagement.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{customer}", "customer"), ("{roleAssignmentId}", "roleAssignmentId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["roleAssignmentId", "customer"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = res; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Immutable ID of the Google Apps account. + /// + /// 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. + pub fn customer(mut self, new_value: &str) -> RoleAssignmentDeleteCall<'a, C, A> { + self._customer = new_value.to_string(); + self + } + /// Immutable ID of the role assignment. + /// + /// Sets the *role assignment id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn role_assignment_id(mut self, new_value: &str) -> RoleAssignmentDeleteCall<'a, C, A> { + self._role_assignment_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> RoleAssignmentDeleteCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> RoleAssignmentDeleteCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::DirectoryRolemanagement`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> RoleAssignmentDeleteCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Retrieves a paginated list of all roleAssignments. +/// +/// A builder for the *list* method supported by a *roleAssignment* resource. +/// It is not used directly, but through a `RoleAssignmentMethods` instance. +/// +/// # 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.role_assignments().list("customer") +/// .user_key("dolor") +/// .role_id("aliquyam") +/// .page_token("elitr") +/// .max_results(-16) +/// .doit(); +/// # } +/// ``` +pub struct RoleAssignmentListCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Directory, + _customer: String, + _user_key: Option, + _role_id: Option, + _page_token: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for RoleAssignmentListCall<'a, C, A> {} + +impl<'a, C, A> RoleAssignmentListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, RoleAssignments)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.roleAssignments.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + params.push(("customer", self._customer.to_string())); + if let Some(value) = self._user_key { + params.push(("userKey", value.to_string())); + } + if let Some(value) = self._role_id { + params.push(("roleId", 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", "customer", "userKey", "roleId", "pageToken", "maxResults"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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}/roleassignments".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::DirectoryRolemanagementReadonly.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Immutable ID of the Google Apps account. + /// + /// 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. + pub fn customer(mut self, new_value: &str) -> RoleAssignmentListCall<'a, C, A> { + self._customer = new_value.to_string(); + self + } + /// The user's primary email address, alias email address, or unique user ID. If included in the request, returns role assignments only for this user. + /// + /// Sets the *user key* query property to the given value. + pub fn user_key(mut self, new_value: &str) -> RoleAssignmentListCall<'a, C, A> { + self._user_key = Some(new_value.to_string()); + self + } + /// Immutable ID of a role. If included in the request, returns only role assignments containing this role ID. + /// + /// Sets the *role id* query property to the given value. + pub fn role_id(mut self, new_value: &str) -> RoleAssignmentListCall<'a, C, A> { + self._role_id = Some(new_value.to_string()); + self + } + /// Token to specify the next page in the list. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> RoleAssignmentListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Maximum number of results to return. + /// + /// Sets the *max results* query property to the given value. + pub fn max_results(mut self, new_value: i32) -> RoleAssignmentListCall<'a, C, A> { + self._max_results = Some(new_value); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> RoleAssignmentListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> RoleAssignmentListCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::DirectoryRolemanagementReadonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> RoleAssignmentListCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + diff --git a/gen/admin1_reports-cli/Cargo.toml b/gen/admin1_reports-cli/Cargo.toml index baa5a2d4f0..ad11c68b2d 100644 --- a/gen/admin1_reports-cli/Cargo.toml +++ b/gen/admin1_reports-cli/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-admin1_reports-cli" -version = "0.3.2+20150429" +version = "0.3.2+20150907" 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-cli" diff --git a/gen/admin1_reports-cli/README.md b/gen/admin1_reports-cli/README.md index 4351d0af63..bbee7cd5b7 100644 --- a/gen/admin1_reports-cli/README.md +++ b/gen/admin1_reports-cli/README.md @@ -24,7 +24,7 @@ Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/ma # Usage -This documentation was generated from the *reports* API at revision *20150429*. The CLI is at version *0.3.2*. +This documentation was generated from the *reports* API at revision *20150907*. The CLI is at version *0.3.2*. ```bash admin1-reports [options] diff --git a/gen/admin1_reports-cli/mkdocs.yml b/gen/admin1_reports-cli/mkdocs.yml index 5fdb7f3310..d681d09f00 100644 --- a/gen/admin1_reports-cli/mkdocs.yml +++ b/gen/admin1_reports-cli/mkdocs.yml @@ -1,4 +1,4 @@ -site_name: reports v0.3.2+20150429 +site_name: reports v0.3.2+20150907 site_url: http://byron.github.io/google-apis-rs/google-admin1_reports-cli site_description: Write integrating applications with bcore diff --git a/gen/admin1_reports-cli/src/main.rs b/gen/admin1_reports-cli/src/main.rs index 60cc18da35..1fe4a97fac 100644 --- a/gen/admin1_reports-cli/src/main.rs +++ b/gen/admin1_reports-cli/src/main.rs @@ -735,7 +735,7 @@ fn main() { let mut app = App::new("admin1-reports") .author("Sebastian Thiel ") - .version("0.3.2+20150429") + .version("0.3.2+20150907") .about("Allows the administrators of Google Apps customers to fetch reports about the usage, collaboration, security and risk for their users.") .after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_admin1_reports_cli") .arg(Arg::with_name("url") diff --git a/gen/admin1_reports/Cargo.toml b/gen/admin1_reports/Cargo.toml index 5494a27fcd..0422b7328a 100644 --- a/gen/admin1_reports/Cargo.toml +++ b/gen/admin1_reports/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-admin1_reports" -version = "0.1.9+20150429" +version = "0.1.9+20150907" 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" diff --git a/gen/admin1_reports/README.md b/gen/admin1_reports/README.md index 3c181cb4b5..b9e4646164 100644 --- a/gen/admin1_reports/README.md +++ b/gen/admin1_reports/README.md @@ -5,7 +5,7 @@ DO NOT EDIT ! --> 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.9+20150429*, where *20150429* is the exact revision of the *admin:reports_v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +This documentation was generated from *reports* crate version *0.1.9+20150907*, where *20150907* is the exact revision of the *admin:reports_v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. Everything else about the *reports* *v1_reports* API can be found at the [official documentation site](https://developers.google.com/admin-sdk/reports/). diff --git a/gen/admin1_reports/src/lib.rs b/gen/admin1_reports/src/lib.rs index 83c8c2a66f..096027878a 100644 --- a/gen/admin1_reports/src/lib.rs +++ b/gen/admin1_reports/src/lib.rs @@ -2,7 +2,7 @@ // This file was generated automatically from 'src/mako/api/lib.rs.mako' // DO NOT EDIT ! -//! This documentation was generated from *reports* crate version *0.1.9+20150429*, where *20150429* is the exact revision of the *admin:reports_v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +//! This documentation was generated from *reports* crate version *0.1.9+20150907*, where *20150907* is the exact revision of the *admin:reports_v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. //! //! Everything else about the *reports* *v1_reports* API can be found at the //! [official documentation site](https://developers.google.com/admin-sdk/reports/). diff --git a/gen/admin2_email_migration/src/lib.rs.in b/gen/admin2_email_migration/src/lib.rs.in index abda685634..d6a77d0ba5 100644 --- a/gen/admin2_email_migration/src/lib.rs.in +++ b/gen/admin2_email_migration/src/lib.rs.in @@ -551,10 +551,10 @@ impl<'a, C, A> MailInsertCall<'a, C, A> where C: BorrowMut, A: oa self.doit(stream, mime_type, "simple") } /// Upload media in a resumable fashion. - /// Even if the upload fails or is interrupted, it can be resumed for a + /// Even if the upload fails or is interrupted, it can be resumed for a /// certain amount of time as the server maintains state temporarily. /// - /// The delegate will be asked for an `upload_url()`, and if not provided, will be asked to store an upload URL + /// The delegate will be asked for an `upload_url()`, and if not provided, will be asked to store an upload URL /// that was provided by the server, using `store_upload_url(...)`. The upload will be done in chunks, the delegate /// may specify the `chunk_size()` and may cancel the operation before each chunk is uploaded, using /// `cancel_chunk_upload(...)`. diff --git a/gen/adsense1d4-cli/Cargo.toml b/gen/adsense1d4-cli/Cargo.toml index 5093cfcdbb..a3febc10f1 100644 --- a/gen/adsense1d4-cli/Cargo.toml +++ b/gen/adsense1d4-cli/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-adsense1d4-cli" -version = "0.3.2+20150719" +version = "0.3.2+20151013" 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-cli" diff --git a/gen/adsense1d4-cli/README.md b/gen/adsense1d4-cli/README.md index dd34b0a0f6..e2b9c4baa0 100644 --- a/gen/adsense1d4-cli/README.md +++ b/gen/adsense1d4-cli/README.md @@ -24,7 +24,7 @@ Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/ma # Usage -This documentation was generated from the *AdSense* API at revision *20150719*. The CLI is at version *0.3.2*. +This documentation was generated from the *AdSense* API at revision *20151013*. The CLI is at version *0.3.2*. ```bash adsense1d4 [options] diff --git a/gen/adsense1d4-cli/mkdocs.yml b/gen/adsense1d4-cli/mkdocs.yml index 48e4ff30a3..b368f110e7 100644 --- a/gen/adsense1d4-cli/mkdocs.yml +++ b/gen/adsense1d4-cli/mkdocs.yml @@ -1,4 +1,4 @@ -site_name: AdSense v0.3.2+20150719 +site_name: AdSense v0.3.2+20151013 site_url: http://byron.github.io/google-apis-rs/google-adsense1d4-cli site_description: Write integrating applications with bcore diff --git a/gen/adsense1d4-cli/src/main.rs b/gen/adsense1d4-cli/src/main.rs index 1a12d8f2ea..1802d2bce7 100644 --- a/gen/adsense1d4-cli/src/main.rs +++ b/gen/adsense1d4-cli/src/main.rs @@ -3480,7 +3480,7 @@ fn main() { let mut app = App::new("adsense1d4") .author("Sebastian Thiel ") - .version("0.3.2+20150719") + .version("0.3.2+20151013") .about("Gives AdSense publishers access to their inventory and the ability to generate reports") .after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_adsense1d4_cli") .arg(Arg::with_name("url") diff --git a/gen/adsense1d4/Cargo.toml b/gen/adsense1d4/Cargo.toml index cf142bc6c5..af23816bfa 100644 --- a/gen/adsense1d4/Cargo.toml +++ b/gen/adsense1d4/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-adsense1d4" -version = "0.1.9+20150719" +version = "0.1.9+20151013" 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" diff --git a/gen/adsense1d4/README.md b/gen/adsense1d4/README.md index 5c13ce5af4..f1770a4d8b 100644 --- a/gen/adsense1d4/README.md +++ b/gen/adsense1d4/README.md @@ -5,7 +5,7 @@ DO NOT EDIT ! --> The `google-adsense1d4` library allows access to all features of the *Google AdSense* service. -This documentation was generated from *AdSense* crate version *0.1.9+20150719*, where *20150719* is the exact revision of the *adsense:v1.4* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +This documentation was generated from *AdSense* crate version *0.1.9+20151013*, where *20151013* is the exact revision of the *adsense:v1.4* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. Everything else about the *AdSense* *v1d4* API can be found at the [official documentation site](https://developers.google.com/adsense/management/). diff --git a/gen/adsense1d4/src/lib.rs b/gen/adsense1d4/src/lib.rs index 2861c66feb..b220b005c9 100644 --- a/gen/adsense1d4/src/lib.rs +++ b/gen/adsense1d4/src/lib.rs @@ -2,7 +2,7 @@ // This file was generated automatically from 'src/mako/api/lib.rs.mako' // DO NOT EDIT ! -//! This documentation was generated from *AdSense* crate version *0.1.9+20150719*, where *20150719* is the exact revision of the *adsense:v1.4* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +//! This documentation was generated from *AdSense* crate version *0.1.9+20151013*, where *20151013* is the exact revision of the *adsense:v1.4* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. //! //! Everything else about the *AdSense* *v1d4* API can be found at the //! [official documentation site](https://developers.google.com/adsense/management/). diff --git a/gen/adsense1d4/src/lib.rs.in b/gen/adsense1d4/src/lib.rs.in index a7fe8b7224..4758e69db1 100644 --- a/gen/adsense1d4/src/lib.rs.in +++ b/gen/adsense1d4/src/lib.rs.in @@ -252,6 +252,8 @@ pub struct Account { pub name: Option, /// AdSense timezone of this account. pub timezone: Option, + /// no description provided + pub creation_time: Option, /// Unique identifier of this account. pub id: Option, /// Sub accounts of the this account. diff --git a/gen/adsensehost4d1-cli/Cargo.toml b/gen/adsensehost4d1-cli/Cargo.toml index 8895af05e0..f858f8efa8 100644 --- a/gen/adsensehost4d1-cli/Cargo.toml +++ b/gen/adsensehost4d1-cli/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-adsensehost4d1-cli" -version = "0.3.2+20150719" +version = "0.3.2+20151013" 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-cli" diff --git a/gen/adsensehost4d1-cli/README.md b/gen/adsensehost4d1-cli/README.md index 9b16d4d7e9..0e0f60b2fb 100644 --- a/gen/adsensehost4d1-cli/README.md +++ b/gen/adsensehost4d1-cli/README.md @@ -24,7 +24,7 @@ Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/ma # Usage -This documentation was generated from the *AdSense Host* API at revision *20150719*. The CLI is at version *0.3.2*. +This documentation was generated from the *AdSense Host* API at revision *20151013*. The CLI is at version *0.3.2*. ```bash adsensehost4d1 [options] diff --git a/gen/adsensehost4d1-cli/mkdocs.yml b/gen/adsensehost4d1-cli/mkdocs.yml index 8d188e2e46..b15ee327f7 100644 --- a/gen/adsensehost4d1-cli/mkdocs.yml +++ b/gen/adsensehost4d1-cli/mkdocs.yml @@ -1,4 +1,4 @@ -site_name: AdSense Host v0.3.2+20150719 +site_name: AdSense Host v0.3.2+20151013 site_url: http://byron.github.io/google-apis-rs/google-adsensehost4d1-cli site_description: Write integrating applications with bcore diff --git a/gen/adsensehost4d1-cli/src/main.rs b/gen/adsensehost4d1-cli/src/main.rs index 9e49854d93..189f96f79c 100644 --- a/gen/adsensehost4d1-cli/src/main.rs +++ b/gen/adsensehost4d1-cli/src/main.rs @@ -2761,7 +2761,7 @@ fn main() { let mut app = App::new("adsensehost4d1") .author("Sebastian Thiel ") - .version("0.3.2+20150719") + .version("0.3.2+20151013") .about("Gives AdSense Hosts access to report generation, ad code generation, and publisher management capabilities.") .after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_adsensehost4d1_cli") .arg(Arg::with_name("url") diff --git a/gen/adsensehost4d1/Cargo.toml b/gen/adsensehost4d1/Cargo.toml index 22db79393f..bb895c905c 100644 --- a/gen/adsensehost4d1/Cargo.toml +++ b/gen/adsensehost4d1/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-adsensehost4d1" -version = "0.1.9+20150719" +version = "0.1.9+20151013" 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" diff --git a/gen/adsensehost4d1/README.md b/gen/adsensehost4d1/README.md index 30f7f9fa2d..6c2ecac89a 100644 --- a/gen/adsensehost4d1/README.md +++ b/gen/adsensehost4d1/README.md @@ -5,7 +5,7 @@ DO NOT EDIT ! --> 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.9+20150719*, where *20150719* is the exact revision of the *adsensehost:v4.1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +This documentation was generated from *AdSense Host* crate version *0.1.9+20151013*, where *20151013* is the exact revision of the *adsensehost:v4.1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. Everything else about the *AdSense Host* *v4d1* API can be found at the [official documentation site](https://developers.google.com/adsense/host/). diff --git a/gen/adsensehost4d1/src/lib.rs b/gen/adsensehost4d1/src/lib.rs index 2997fdf885..b741b80bc2 100644 --- a/gen/adsensehost4d1/src/lib.rs +++ b/gen/adsensehost4d1/src/lib.rs @@ -2,7 +2,7 @@ // This file was generated automatically from 'src/mako/api/lib.rs.mako' // DO NOT EDIT ! -//! This documentation was generated from *AdSense Host* crate version *0.1.9+20150719*, where *20150719* is the exact revision of the *adsensehost:v4.1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +//! This documentation was generated from *AdSense Host* crate version *0.1.9+20151013*, where *20151013* is the exact revision of the *adsensehost:v4.1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. //! //! Everything else about the *AdSense Host* *v4d1* API can be found at the //! [official documentation site](https://developers.google.com/adsense/host/). diff --git a/gen/analytics3-cli/Cargo.toml b/gen/analytics3-cli/Cargo.toml index 7a9d7185e7..b454bfdd04 100644 --- a/gen/analytics3-cli/Cargo.toml +++ b/gen/analytics3-cli/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-analytics3-cli" -version = "0.3.2+20150417" +version = "0.3.2+20150901" 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-cli" diff --git a/gen/analytics3-cli/README.md b/gen/analytics3-cli/README.md index 171b90f6c3..64297fa1c1 100644 --- a/gen/analytics3-cli/README.md +++ b/gen/analytics3-cli/README.md @@ -24,7 +24,7 @@ Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/ma # Usage -This documentation was generated from the *analytics* API at revision *20150417*. The CLI is at version *0.3.2*. +This documentation was generated from the *analytics* API at revision *20150901*. The CLI is at version *0.3.2*. ```bash analytics3 [options] diff --git a/gen/analytics3-cli/mkdocs.yml b/gen/analytics3-cli/mkdocs.yml index ed38668783..c71b01028f 100644 --- a/gen/analytics3-cli/mkdocs.yml +++ b/gen/analytics3-cli/mkdocs.yml @@ -1,4 +1,4 @@ -site_name: analytics v0.3.2+20150417 +site_name: analytics v0.3.2+20150901 site_url: http://byron.github.io/google-apis-rs/google-analytics3-cli site_description: Write integrating applications with bcore diff --git a/gen/analytics3-cli/src/main.rs b/gen/analytics3-cli/src/main.rs index 547109b232..4ddb2a265b 100644 --- a/gen/analytics3-cli/src/main.rs +++ b/gen/analytics3-cli/src/main.rs @@ -9223,7 +9223,7 @@ fn main() { let mut app = App::new("analytics3") .author("Sebastian Thiel ") - .version("0.3.2+20150417") + .version("0.3.2+20150901") .about("View and manage your Google Analytics data") .after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_analytics3_cli") .arg(Arg::with_name("url") diff --git a/gen/analytics3/Cargo.toml b/gen/analytics3/Cargo.toml index 0c75a1658f..44fefd915e 100644 --- a/gen/analytics3/Cargo.toml +++ b/gen/analytics3/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-analytics3" -version = "0.1.9+20150417" +version = "0.1.9+20150901" 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" diff --git a/gen/analytics3/README.md b/gen/analytics3/README.md index 404d9b017c..2b45357eb6 100644 --- a/gen/analytics3/README.md +++ b/gen/analytics3/README.md @@ -5,7 +5,7 @@ DO NOT EDIT ! --> The `google-analytics3` library allows access to all features of the *Google analytics* service. -This documentation was generated from *analytics* crate version *0.1.9+20150417*, where *20150417* is the exact revision of the *analytics:v3* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +This documentation was generated from *analytics* crate version *0.1.9+20150901*, where *20150901* is the exact revision of the *analytics:v3* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. Everything else about the *analytics* *v3* API can be found at the [official documentation site](https://developers.google.com/analytics/). diff --git a/gen/analytics3/src/lib.rs b/gen/analytics3/src/lib.rs index 09def7ef2f..e919b3d2aa 100644 --- a/gen/analytics3/src/lib.rs +++ b/gen/analytics3/src/lib.rs @@ -2,7 +2,7 @@ // This file was generated automatically from 'src/mako/api/lib.rs.mako' // DO NOT EDIT ! -//! This documentation was generated from *analytics* crate version *0.1.9+20150417*, where *20150417* is the exact revision of the *analytics:v3* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +//! This documentation was generated from *analytics* crate version *0.1.9+20150901*, where *20150901* is the exact revision of the *analytics:v3* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. //! //! Everything else about the *analytics* *v3* API can be found at the //! [official documentation site](https://developers.google.com/analytics/). diff --git a/gen/analytics3/src/lib.rs.in b/gen/analytics3/src/lib.rs.in index 38a6334145..09116d0cd6 100644 --- a/gen/analytics3/src/lib.rs.in +++ b/gen/analytics3/src/lib.rs.in @@ -1573,7 +1573,7 @@ impl Part for FilterSearchAndReplaceDetails {} 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. + /// A floating-point number in (0, 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(rename="trafficCoverage")] pub traffic_coverage: Option, /// Notes about this experiment. @@ -1586,7 +1586,7 @@ pub struct Experiment { /// Internal ID for the web property to which this experiment belongs. This field is read-only. #[serde(rename="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. + /// A floating-point number in (0, 1). Specifies the necessary confidence level to choose a winner. This field may not be changed for an experiments whose status is ENDED. #[serde(rename="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. @@ -1861,7 +1861,7 @@ pub struct FilterExpression { /// - Custom dimension /// - CUSTOM_DIMENSION (See accompanying field index), pub field: Option, - /// 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. + /// Match type for this filter. Possible values are BEGINS_WITH, EQUAL, ENDS_WITH, CONTAINS, or MATCHES. GEO_DOMAIN, GEO_IP_ADDRESS, PAGE_REQUEST_URI, or PAGE_HOSTNAME filters can use any match type; all other filters must use MATCHES. #[serde(rename="matchType")] pub match_type: Option, /// The Index of the custom dimension. Set only if the field is a is CUSTOM_DIMENSION. @@ -2676,7 +2676,7 @@ pub struct Profile { /// The query parameters that are excluded from this view (profile). #[serde(rename="excludeQueryParameters")] pub exclude_query_parameters: Option, - /// The currency type associated with this view (profile). The supported values are: + /// The currency type associated with this view (profile), defaults to USD. 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. @@ -14349,10 +14349,10 @@ impl<'a, C, A> ManagementUploadUploadDataCall<'a, C, A> where C: BorrowMut"] description = "A complete library to interact with Android Enterprise (protocol v1)" repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/androidenterprise1-cli" diff --git a/gen/androidenterprise1-cli/README.md b/gen/androidenterprise1-cli/README.md index b83c59ecb7..784f8f34d2 100644 --- a/gen/androidenterprise1-cli/README.md +++ b/gen/androidenterprise1-cli/README.md @@ -24,7 +24,7 @@ Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/ma # Usage -This documentation was generated from the *Android Enterprise* API at revision *20150715*. The CLI is at version *0.3.2*. +This documentation was generated from the *Android Enterprise* API at revision *20150922*. The CLI is at version *0.3.2*. ```bash androidenterprise1 [options] @@ -52,6 +52,7 @@ androidenterprise1 [options] get [-p ]... [-o ] insert (-r )... [-p ]... [-o ] list [-p ]... [-o ] + send-test-push-notification [-p ]... [-o ] set-account (-r )... [-p ]... [-o ] unenroll [-p ]... entitlements @@ -83,8 +84,10 @@ androidenterprise1 [options] users generate-token [-p ]... [-o ] get [-p ]... [-o ] + get-available-product-set [-p ]... [-o ] list [-p ]... [-o ] revoke-token [-p ]... + set-available-product-set (-r )... [-p ]... [-o ] androidenterprise1 --help Configuration: diff --git a/gen/androidenterprise1-cli/mkdocs.yml b/gen/androidenterprise1-cli/mkdocs.yml index af32768162..09018b6ea2 100644 --- a/gen/androidenterprise1-cli/mkdocs.yml +++ b/gen/androidenterprise1-cli/mkdocs.yml @@ -1,4 +1,4 @@ -site_name: Android Enterprise v0.3.2+20150715 +site_name: Android Enterprise v0.3.2+20150922 site_url: http://byron.github.io/google-apis-rs/google-androidenterprise1-cli site_description: Write integrating applications with bcore @@ -29,6 +29,7 @@ pages: - ['enterprises_get.md', 'Enterprises', 'Get'] - ['enterprises_insert.md', 'Enterprises', 'Insert'] - ['enterprises_list.md', 'Enterprises', 'List'] +- ['enterprises_send-test-push-notification.md', 'Enterprises', 'Send Test Push Notification'] - ['enterprises_set-account.md', 'Enterprises', 'Set Account'] - ['enterprises_unenroll.md', 'Enterprises', 'Unenroll'] - ['entitlements_delete.md', 'Entitlements', 'Delete'] @@ -53,8 +54,10 @@ pages: - ['products_update-permissions.md', 'Products', 'Update Permissions'] - ['users_generate-token.md', 'Users', 'Generate Token'] - ['users_get.md', 'Users', 'Get'] +- ['users_get-available-product-set.md', 'Users', 'Get Available Product Set'] - ['users_list.md', 'Users', 'List'] - ['users_revoke-token.md', 'Users', 'Revoke Token'] +- ['users_set-available-product-set.md', 'Users', 'Set Available Product Set'] theme: readthedocs diff --git a/gen/androidenterprise1-cli/src/main.rs b/gen/androidenterprise1-cli/src/main.rs index fa0074c1b9..5bfb44be9f 100644 --- a/gen/androidenterprise1-cli/src/main.rs +++ b/gen/androidenterprise1-cli/src/main.rs @@ -1348,6 +1348,58 @@ impl<'n, 'a> Engine<'n, 'a> { } } + fn _enterprises_send_test_push_notification(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.enterprises().send_test_push_notification(opt.value_of("enterprise-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + fn _enterprises_set_account(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) -> Result<(), DoitError> { @@ -2832,6 +2884,58 @@ impl<'n, 'a> Engine<'n, 'a> { } } + fn _users_get_available_product_set(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.users().get_available_product_set(opt.value_of("enterprise-id").unwrap_or(""), opt.value_of("user-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + fn _users_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) -> Result<(), DoitError> { let mut call = self.hub.users().list(opt.value_of("enterprise-id").unwrap_or(""), opt.value_of("email").unwrap_or("")); @@ -2928,6 +3032,92 @@ impl<'n, 'a> Engine<'n, 'a> { } } + fn _users_set_available_product_set(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "product-id" => Some(("productId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["kind", "product-id"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::ProductSet = json::value::from_value(object).unwrap(); + let mut call = self.hub.users().set_available_product_set(request, opt.value_of("enterprise-id").unwrap_or(""), opt.value_of("user-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + fn _doit(&self, dry_run: bool) -> Result, Option> { let mut err = InvalidOptionsError::new(); let mut call_result: Result<(), DoitError> = Ok(()); @@ -3019,6 +3209,9 @@ impl<'n, 'a> Engine<'n, 'a> { ("list", Some(opt)) => { call_result = self._enterprises_list(opt, dry_run, &mut err); }, + ("send-test-push-notification", Some(opt)) => { + call_result = self._enterprises_send_test_push_notification(opt, dry_run, &mut err); + }, ("set-account", Some(opt)) => { call_result = self._enterprises_set_account(opt, dry_run, &mut err); }, @@ -3147,12 +3340,18 @@ impl<'n, 'a> Engine<'n, 'a> { ("get", Some(opt)) => { call_result = self._users_get(opt, dry_run, &mut err); }, + ("get-available-product-set", Some(opt)) => { + call_result = self._users_get_available_product_set(opt, dry_run, &mut err); + }, ("list", Some(opt)) => { call_result = self._users_list(opt, dry_run, &mut err); }, ("revoke-token", Some(opt)) => { call_result = self._users_revoke_token(opt, dry_run, &mut err); }, + ("set-available-product-set", Some(opt)) => { + call_result = self._users_set_available_product_set(opt, dry_run, &mut err); + }, _ => { err.issues.push(CLIError::MissingMethodError("users".to_string())); writeln!(io::stderr(), "{}\n", opt.usage()).ok(); @@ -3724,7 +3923,7 @@ fn main() { ]), ]), - ("enterprises", "methods: 'delete', 'enroll', 'get', 'insert', 'list', 'set-account' and 'unenroll'", vec![ + ("enterprises", "methods: 'delete', 'enroll', 'get', 'insert', 'list', 'send-test-push-notification', 'set-account' and 'unenroll'", vec![ ("delete", Some(r##"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."##), "Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/enterprises_delete", @@ -3835,6 +4034,28 @@ fn main() { Some(false), Some(true)), + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("send-test-push-notification", + Some(r##"Sends a test push notification to validate the MDM integration with the Google Cloud Pub/Sub service for this enterprise."##), + "Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/enterprises_send-test-push-notification", + vec![ + (Some(r##"enterprise-id"##), + None, + Some(r##"The ID of the enterprise."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + (Some(r##"out"##), Some(r##"o"##), Some(r##"Specify the file into which to write the program's output"##), @@ -4551,7 +4772,7 @@ fn main() { ]), ]), - ("users", "methods: 'generate-token', 'get', 'list' and 'revoke-token'", vec![ + ("users", "methods: 'generate-token', 'get', 'get-available-product-set', 'list', 'revoke-token' and 'set-available-product-set'", vec![ ("generate-token", Some(r##"Generates a token (activation code) to allow this user to configure their work account in the Android Setup Wizard. Revokes any previously generated token."##), "Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/users_generate-token", @@ -4602,6 +4823,34 @@ fn main() { Some(false), Some(true)), + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("get-available-product-set", + Some(r##"Retrieves the set of products a user is entitled to access."##), + "Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/users_get-available-product-set", + vec![ + (Some(r##"enterprise-id"##), + None, + Some(r##"The ID of the enterprise."##), + Some(true), + Some(false)), + + (Some(r##"user-id"##), + None, + Some(r##"The ID of the user."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + (Some(r##"out"##), Some(r##"o"##), Some(r##"Specify the file into which to write the program's output"##), @@ -4658,13 +4907,47 @@ fn main() { Some(false), Some(true)), ]), + ("set-available-product-set", + Some(r##"Modifies the set of products a user is entitled to access."##), + "Details at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli/users_set-available-product-set", + vec![ + (Some(r##"enterprise-id"##), + None, + Some(r##"The ID of the enterprise."##), + Some(true), + Some(false)), + + (Some(r##"user-id"##), + None, + Some(r##"The ID of the user."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), ]), ]; let mut app = App::new("androidenterprise1") .author("Sebastian Thiel ") - .version("0.3.2+20150715") + .version("0.3.2+20150922") .about("Allows MDMs/EMMs and enterprises to manage the deployment of apps to Android for Work users.") .after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_androidenterprise1_cli") .arg(Arg::with_name("url") diff --git a/gen/androidenterprise1/Cargo.toml b/gen/androidenterprise1/Cargo.toml index f427206c56..938cf9a9a1 100644 --- a/gen/androidenterprise1/Cargo.toml +++ b/gen/androidenterprise1/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-androidenterprise1" -version = "0.1.9+20150715" +version = "0.1.9+20150922" 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" diff --git a/gen/androidenterprise1/README.md b/gen/androidenterprise1/README.md index 368fe5d941..37626b55c6 100644 --- a/gen/androidenterprise1/README.md +++ b/gen/androidenterprise1/README.md @@ -5,7 +5,7 @@ DO NOT EDIT ! --> 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.9+20150715*, where *20150715* is the exact revision of the *androidenterprise:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +This documentation was generated from *Android Enterprise* crate version *0.1.9+20150922*, where *20150922* is the exact revision of the *androidenterprise:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. Everything else about the *Android Enterprise* *v1* API can be found at the [official documentation site](https://developers.google.com/play/enterprise). @@ -20,7 +20,7 @@ Handle the following *Resources* with ease from the central [hub](http://byron.g * [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) + * [*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), [*send test push notification*](http://byron.github.io/google-apis-rs/google_androidenterprise1/struct.EnterpriseSendTestPushNotificationCall.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 @@ -34,7 +34,7 @@ Handle the following *Resources* with ease from the central [hub](http://byron.g * [products](http://byron.github.io/google-apis-rs/google_androidenterprise1/struct.Product.html) * [*approve*](http://byron.github.io/google-apis-rs/google_androidenterprise1/struct.ProductApproveCall.html), [*generate approval url*](http://byron.github.io/google-apis-rs/google_androidenterprise1/struct.ProductGenerateApprovalUrlCall.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) + * [*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), [*get available product set*](http://byron.github.io/google-apis-rs/google_androidenterprise1/struct.UserGetAvailableProductSetCall.html), [*list*](http://byron.github.io/google-apis-rs/google_androidenterprise1/struct.UserListCall.html), [*revoke token*](http://byron.github.io/google-apis-rs/google_androidenterprise1/struct.UserRevokeTokenCall.html) and [*set available product set*](http://byron.github.io/google-apis-rs/google_androidenterprise1/struct.UserSetAvailableProductSetCall.html) @@ -67,13 +67,15 @@ 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() +let r = hub.users().revoke_token(...).doit() +let r = hub.collectionviewers().update(...).doit() +let r = hub.collectionviewers().patch(...).doit() +let r = hub.users().list(...).doit() +let r = hub.collectionviewers().get(...).doit() +let r = hub.users().set_available_product_set(...).doit() +let r = hub.users().generate_token(...).doit() +let r = hub.users().get_available_product_set(...).doit() +let r = hub.users().get(...).doit() ``` The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` @@ -98,7 +100,7 @@ google-androidenterprise1 = "*" extern crate hyper; extern crate yup_oauth2 as oauth2; extern crate google_androidenterprise1 as androidenterprise1; -use androidenterprise1::Enterprise; +use androidenterprise1::User; use androidenterprise1::{Result, Error}; use std::default::Default; use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; @@ -119,12 +121,12 @@ 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(); +let mut req = User::default(); // You can configure optional parameters by calling 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") +let result = hub.collectionviewers().update(req, "enterpriseId", "collectionId", "userId") .doit(); match result { diff --git a/gen/androidenterprise1/src/lib.rs b/gen/androidenterprise1/src/lib.rs index a23b849944..e5b841b40f 100644 --- a/gen/androidenterprise1/src/lib.rs +++ b/gen/androidenterprise1/src/lib.rs @@ -2,7 +2,7 @@ // This file was generated automatically from 'src/mako/api/lib.rs.mako' // DO NOT EDIT ! -//! This documentation was generated from *Android Enterprise* crate version *0.1.9+20150715*, where *20150715* is the exact revision of the *androidenterprise:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +//! This documentation was generated from *Android Enterprise* crate version *0.1.9+20150922*, where *20150922* is the exact revision of the *androidenterprise:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. //! //! Everything else about the *Android Enterprise* *v1* API can be found at the //! [official documentation site](https://developers.google.com/play/enterprise). @@ -18,7 +18,7 @@ //! * [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) +//! * [*delete*](struct.EnterpriseDeleteCall.html), [*enroll*](struct.EnterpriseEnrollCall.html), [*get*](struct.EnterpriseGetCall.html), [*insert*](struct.EnterpriseInsertCall.html), [*list*](struct.EnterpriseListCall.html), [*send test push notification*](struct.EnterpriseSendTestPushNotificationCall.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 @@ -32,7 +32,7 @@ //! * [products](struct.Product.html) //! * [*approve*](struct.ProductApproveCall.html), [*generate approval url*](struct.ProductGenerateApprovalUrlCall.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) +//! * [*generate token*](struct.UserGenerateTokenCall.html), [*get*](struct.UserGetCall.html), [*get available product set*](struct.UserGetAvailableProductSetCall.html), [*list*](struct.UserListCall.html), [*revoke token*](struct.UserRevokeTokenCall.html) and [*set available product set*](struct.UserSetAvailableProductSetCall.html) //! //! //! @@ -67,13 +67,15 @@ //! 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() +//! let r = hub.users().revoke_token(...).doit() +//! let r = hub.collectionviewers().update(...).doit() +//! let r = hub.collectionviewers().patch(...).doit() +//! let r = hub.users().list(...).doit() +//! let r = hub.collectionviewers().get(...).doit() +//! let r = hub.users().set_available_product_set(...).doit() +//! let r = hub.users().generate_token(...).doit() +//! let r = hub.users().get_available_product_set(...).doit() +//! let r = hub.users().get(...).doit() //! ``` //! //! The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` @@ -98,7 +100,7 @@ //! extern crate hyper; //! extern crate yup_oauth2 as oauth2; //! extern crate google_androidenterprise1 as androidenterprise1; -//! use androidenterprise1::Enterprise; +//! use androidenterprise1::User; //! use androidenterprise1::{Result, Error}; //! # #[test] fn egal() { //! use std::default::Default; @@ -120,12 +122,12 @@ //! // As the method needs a request, you would usually fill it with the desired information //! // into the 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(); +//! let mut req = User::default(); //! //! // You can configure optional parameters by calling 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") +//! let result = hub.collectionviewers().update(req, "enterpriseId", "collectionId", "userId") //! .doit(); //! //! match result { diff --git a/gen/androidenterprise1/src/lib.rs.in b/gen/androidenterprise1/src/lib.rs.in index e8b9ce7e7c..510080e0a9 100644 --- a/gen/androidenterprise1/src/lib.rs.in +++ b/gen/androidenterprise1/src/lib.rs.in @@ -69,7 +69,7 @@ impl Default for Scope { /// extern crate hyper; /// extern crate yup_oauth2 as oauth2; /// extern crate google_androidenterprise1 as androidenterprise1; -/// use androidenterprise1::Enterprise; +/// use androidenterprise1::User; /// use androidenterprise1::{Result, Error}; /// # #[test] fn egal() { /// use std::default::Default; @@ -91,12 +91,12 @@ impl Default for Scope { /// // As the method needs a request, you would usually fill it with the desired information /// // into the 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(); +/// let mut req = User::default(); /// /// // You can configure optional parameters by calling 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") +/// let result = hub.collectionviewers().update(req, "enterpriseId", "collectionId", "userId") /// .doit(); /// /// match result { @@ -185,52 +185,6 @@ impl<'a, C, A> AndroidEnterprise // ############ // 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, Serialize, Deserialize)] -pub struct AppRestrictionsSchema { - /// The set of restrictions that make up this schema. - pub restrictions: Option>, -} - -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, Serialize, Deserialize)] -pub struct AppRestrictionsSchemaRestriction { - /// The type of the restriction. - #[serde(rename="restrictionType")] - pub restriction_type: Option, - /// A longer description of the restriction, giving more detail of what it affects. - pub description: Option, - /// The unique key that the product uses to identify the restriction, e.g. "com.google.android.gm.fieldname". - pub key: Option, - /// The name of the restriction. - pub title: Option, - /// For choice or multiselect restrictions, the list of possible entries' human-readable names. - pub entry: Option>, - /// The default value of the restriction. - #[serde(rename="defaultValue")] - pub default_value: Option, - /// For choice or multiselect restrictions, the list of possible entries' machine-readable values. - #[serde(rename="entryValue")] - pub entry_value: Option>, -} - -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. @@ -257,24 +211,47 @@ pub struct AppRestrictionsSchemaRestrictionRestrictionValue { impl Part for AppRestrictionsSchemaRestrictionRestrictionValue {} -/// The matching enterprise resources. +/// 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*). /// -/// * [list enterprises](struct.EnterpriseListCall.html) (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 EnterprisesListResponse { - /// Identifies what kind of resource this is. Value: the fixed string "androidenterprise#enterprisesListResponse". +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(rename="installState")] + pub install_state: Option, + /// The version of the installed product. Guaranteed to be set only if the install state is "installed". + #[serde(rename="versionCode")] + pub version_code: Option, + /// Identifies what kind of resource this is. Value: the fixed string "androidenterprise#install". pub kind: Option, - /// An enterprise. - pub enterprise: Option>, + /// The ID of the product that the install is for, e.g. "app:com.google.android.gm". + #[serde(rename="productId")] + pub product_id: Option, } -impl ResponseResult for EnterprisesListResponse {} +impl RequestValue for Install {} +impl Resource for Install {} +impl ResponseResult for Install {} /// 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. @@ -334,205 +311,27 @@ pub struct InstallsListResponse { impl ResponseResult for InstallsListResponse {} -/// The user resources for the collection. +/// A set of products. /// /// # Activities /// /// This type is used in activities, which are methods you may call on this type or where 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) +/// * [set available product set users](struct.UserSetAvailableProductSetCall.html) (request|response) +/// * [get available product set users](struct.UserGetAvailableProductSetCall.html) (response) /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] -pub struct CollectionViewersListResponse { - /// Identifies what kind of resource this is. Value: the fixed string "androidenterprise#collectionViewersListResponse". +pub struct ProductSet { + /// Identifies what kind of resource this is. Value: the fixed string "androidenterprise#productSet". pub kind: Option, - /// A user of an enterprise. - pub user: Option>, -} - -impl ResponseResult for CollectionViewersListResponse {} - - -/// Information on an approval 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 ApprovalUrlInfo { - /// Identifies what kind of resource this is. Value: the fixed string "androidenterprise#approvalUrlInfo". - pub kind: Option, - /// A URL that displays a product's permissions and that can also be used to approve the product with the Products.approve call. - #[serde(rename="approvalUrl")] - pub approval_url: Option, -} - -impl Part for ApprovalUrlInfo {} - - -/// This represents a single version of the app. -/// -/// This type is not used in any activity, and only used as *part* of another schema. -/// -#[derive(Default, Clone, Debug, Serialize, Deserialize)] -pub struct AppVersion { - /// Unique increasing identifier for the app version. - #[serde(rename="versionCode")] - pub version_code: Option, - /// The string used in the Play Store by the app developer to identify the version. The string is not necessarily unique or localized (for example, the string could be "1.4"). - #[serde(rename="versionString")] - pub version_string: Option, -} - -impl Part for AppVersion {} - - -/// 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, Serialize, Deserialize)] -pub struct GroupLicensesListResponse { - /// A group license for a product approved for use in the enterprise. - #[serde(rename="groupLicense")] - pub group_license: Option>, - /// Identifies what kind of resource this is. Value: the fixed string "androidenterprise#groupLicensesListResponse". - pub kind: Option, -} - -impl ResponseResult for GroupLicensesListResponse {} - - -/// 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, Serialize, Deserialize)] -pub struct DevicesListResponse { - /// A managed device. - pub device: Option>, - /// Identifies what kind of resource this is. Value: the fixed string "androidenterprise#devicesListResponse". - pub kind: Option, -} - -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(rename="installState")] - pub install_state: Option, - /// The version of the installed product. Guaranteed to be set only if the install state is "installed". - #[serde(rename="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". + /// The list of product IDs making up the set of products. #[serde(rename="productId")] - pub product_id: Option, + 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(rename="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, Serialize, Deserialize)] -pub struct UserToken { - /// Identifies what kind of resource this is. Value: the fixed string "androidenterprise#userToken". - pub kind: Option, - /// The unique ID for the user. - #[serde(rename="userId")] - pub user_id: Option, - /// 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: Option, -} - -impl ResponseResult for UserToken {} +impl RequestValue for ProductSet {} +impl ResponseResult for ProductSet {} /// The state of a user's device, as accessed by the getState and setState methods on device resources. @@ -619,8 +418,7 @@ pub struct Product { /// A link to the (consumer) Google Play details page for the product. #[serde(rename="detailsUrl")] pub details_url: Option, - /// A string of the form app: - /// . For example, app:com.google.android.gm represents the Gmail app. + /// A string of the form app:. For example, app:com.google.android.gm represents the Gmail app. #[serde(rename="productId")] pub product_id: Option, } @@ -677,46 +475,6 @@ pub struct EntitlementsListResponse { impl ResponseResult for EntitlementsListResponse {} -/// 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, Serialize, Deserialize)] -pub struct CollectionsListResponse { - /// Identifies what kind of resource this is. Value: the fixed string "androidenterprise#collectionsListResponse". - pub kind: Option, - /// An ordered collection of products which can be made visible on the Google Play Store app to a selected group of users. - pub collection: Option>, -} - -impl ResponseResult for CollectionsListResponse {} - - -/// 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, Serialize, Deserialize)] -pub struct UsersListResponse { - /// Identifies what kind of resource this is. Value: the fixed string "androidenterprise#usersListResponse". - pub kind: Option, - /// A user of an enterprise. - pub user: Option>, -} - -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. @@ -742,7 +500,9 @@ pub struct Collection { 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. + /// Whether this collection is visible to all users, or only to the users that have been granted access through the "Collectionviewers" API. With the launch of the "setAvailableProductSet" API, this property should always be set to "viewersOnly", as the "allUsers" option will bypass the "availableProductSet" for all users within a domain. + /// + /// The "allUsers" setting is deprecated, and will be removed. pub visibility: Option, /// The IDs of the products in the collection, in the order in which they should be displayed. #[serde(rename="productId")] @@ -754,6 +514,385 @@ impl Resource for Collection {} impl ResponseResult for Collection {} +/// 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*). +/// +/// * [send test push notification enterprises](struct.EnterpriseSendTestPushNotificationCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct EnterprisesSendTestPushNotificationResponse { + /// The name of the Cloud Pub/Sub topic to which notifications for this enterprise's enrolled account will be sent. + #[serde(rename="topicName")] + pub topic_name: Option, + /// The message ID of the test push notification that was sent. + #[serde(rename="messageId")] + pub message_id: Option, +} + +impl ResponseResult for EnterprisesSendTestPushNotificationResponse {} + + +/// 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, Serialize, Deserialize)] +pub struct GroupLicenseUsersListResponse { + /// Identifies what kind of resource this is. Value: the fixed string "androidenterprise#groupLicenseUsersListResponse". + pub kind: Option, + /// A user of an enterprise. + pub user: Option>, +} + +impl ResponseResult for GroupLicenseUsersListResponse {} + + +/// Information on an approval 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 ApprovalUrlInfo { + /// Identifies what kind of resource this is. Value: the fixed string "androidenterprise#approvalUrlInfo". + pub kind: Option, + /// A URL that displays a product's permissions and that can also be used to approve the product with the Products.approve call. + #[serde(rename="approvalUrl")] + pub approval_url: Option, +} + +impl Part for ApprovalUrlInfo {} + + +/// 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, Serialize, Deserialize)] +pub struct Device { + /// Identifies what kind of resource this is. Value: the fixed string "androidenterprise#device". + pub kind: Option, + /// The Google Play Services Android ID for the device encoded as a lowercase hex string, e.g. "123456789abcdef0". + #[serde(rename="androidId")] + pub android_id: Option, + /// The mechanism by which this device is managed by the MDM. "managedDevice" means that the MDM's app is a device owner. "managedProfile" means that the MDM's app is the profile owner (and there is a separate personal profile which is not managed). "containerApp" means that the MDM's app is managing the Android for Work container app on the device. + #[serde(rename="managementType")] + pub management_type: Option, +} + +impl Resource for Device {} +impl ResponseResult for Device {} + + +/// 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*). +/// +/// * [generate approval url products](struct.ProductGenerateApprovalUrlCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ProductsGenerateApprovalUrlResponse { + /// A URL that can be rendered in an iframe to display the permissions (if any) of a product. This URL can be used to approve the product only once and only within 24 hours of being generated, using the Products.approve call. If the product is currently unapproved and has no permissions, this URL will point to an empty page. If the product is currently approved, a URL will only be generated if that product has added permissions since it was last approved, and the URL will only display those new permissions that have not yet been accepted. + pub url: Option, +} + +impl ResponseResult for ProductsGenerateApprovalUrlResponse {} + + +/// 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, Serialize, Deserialize)] +pub struct AppRestrictionsSchema { + /// The set of restrictions that make up this schema. + pub restrictions: Option>, + /// Identifies what kind of resource this is. Value: the fixed string "androidenterprise#appRestrictionsSchema". + pub kind: Option, +} + +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, Serialize, Deserialize)] +pub struct AppRestrictionsSchemaRestriction { + /// The type of the restriction. + #[serde(rename="restrictionType")] + pub restriction_type: Option, + /// A longer description of the restriction, giving more detail of what it affects. + pub description: Option, + /// The unique key that the product uses to identify the restriction, e.g. "com.google.android.gm.fieldname". + pub key: Option, + /// The name of the restriction. + pub title: Option, + /// For choice or multiselect restrictions, the list of possible entries' human-readable names. + pub entry: Option>, + /// The default value of the restriction. + #[serde(rename="defaultValue")] + pub default_value: Option, + /// For choice or multiselect restrictions, the list of possible entries' machine-readable values. + #[serde(rename="entryValue")] + pub entry_value: Option>, +} + +impl Part for AppRestrictionsSchemaRestriction {} + + +/// 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(rename="accountEmail")] + pub account_email: Option, +} + +impl RequestValue for EnterpriseAccount {} +impl ResponseResult for EnterpriseAccount {} + + +/// This represents a single version of the app. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct AppVersion { + /// Unique increasing identifier for the app version. + #[serde(rename="versionCode")] + pub version_code: Option, + /// The string used in the Play Store by the app developer to identify the version. The string is not necessarily unique or localized (for example, the string could be "1.4"). + #[serde(rename="versionString")] + pub version_string: Option, +} + +impl Part for AppVersion {} + + +/// 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, Serialize, Deserialize)] +pub struct GroupLicensesListResponse { + /// A group license for a product approved for use in the enterprise. + #[serde(rename="groupLicense")] + pub group_license: Option>, + /// Identifies what kind of resource this is. Value: the fixed string "androidenterprise#groupLicensesListResponse". + pub kind: Option, +} + +impl ResponseResult for GroupLicensesListResponse {} + + +/// 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, Serialize, Deserialize)] +pub struct DevicesListResponse { + /// A managed device. + pub device: Option>, + /// Identifies what kind of resource this is. Value: the fixed string "androidenterprise#devicesListResponse". + pub kind: Option, +} + +impl ResponseResult for DevicesListResponse {} + + +/// 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, Serialize, Deserialize)] +pub struct EnterprisesListResponse { + /// Identifies what kind of resource this is. Value: the fixed string "androidenterprise#enterprisesListResponse". + pub kind: Option, + /// An enterprise. + pub enterprise: Option>, +} + +impl ResponseResult for EnterprisesListResponse {} + + +/// 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*). +/// +/// * [send test push notification enterprises](struct.EnterpriseSendTestPushNotificationCall.html) (none) +/// * [list enterprises](struct.EnterpriseListCall.html) (none) +/// * [unenroll enterprises](struct.EnterpriseUnenrollCall.html) (none) +/// * [set account enterprises](struct.EnterpriseSetAccountCall.html) (none) +/// * [delete enterprises](struct.EnterpriseDeleteCall.html) (none) +/// * [enroll enterprises](struct.EnterpriseEnrollCall.html) (request|response) +/// * [insert enterprises](struct.EnterpriseInsertCall.html) (request|response) +/// * [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(rename="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, Serialize, Deserialize)] +pub struct UserToken { + /// Identifies what kind of resource this is. Value: the fixed string "androidenterprise#userToken". + pub kind: Option, + /// The unique ID for the user. + #[serde(rename="userId")] + pub user_id: Option, + /// 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: Option, +} + +impl ResponseResult for UserToken {} + + +/// 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, Serialize, Deserialize)] +pub struct CollectionViewersListResponse { + /// Identifies what kind of resource this is. Value: the fixed string "androidenterprise#collectionViewersListResponse". + pub kind: Option, + /// A user of an enterprise. + pub user: Option>, +} + +impl ResponseResult for CollectionViewersListResponse {} + + +/// 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, Serialize, Deserialize)] +pub struct CollectionsListResponse { + /// Identifies what kind of resource this is. Value: the fixed string "androidenterprise#collectionsListResponse". + pub kind: Option, + /// An ordered collection of products which can be made visible on the Google Play Store to a selected group of users. + pub collection: Option>, +} + +impl ResponseResult for CollectionsListResponse {} + + +/// 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, Serialize, Deserialize)] +pub struct UsersListResponse { + /// Identifies what kind of resource this is. Value: the fixed string "androidenterprise#usersListResponse". + pub kind: Option, + /// A user of an enterprise. + pub user: Option>, +} + +impl ResponseResult for UsersListResponse {} + + /// There is no detailed description. /// /// # Activities @@ -798,94 +937,41 @@ impl RequestValue for ProductPermissions {} impl ResponseResult for ProductPermissions {} -/// There is no detailed description. +/// 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*). /// -/// * [generate approval url products](struct.ProductGenerateApprovalUrlCall.html) (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) +/// * [set available product set users](struct.UserSetAvailableProductSetCall.html) (none) +/// * [generate token users](struct.UserGenerateTokenCall.html) (none) +/// * [get available product set users](struct.UserGetAvailableProductSetCall.html) (none) +/// * [get users](struct.UserGetCall.html) (response) /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] -pub struct ProductsGenerateApprovalUrlResponse { - /// A URL that can be rendered in an iframe to display the permissions (if any) of a product. This URL can be used to approve the product only once and only within 24 hours of being generated, using the Products.approve call. If the product is currently unapproved and has no permissions, this URL will point to an empty page. If the product is currently approved, a URL will only be generated if that product has added permissions since it was last approved, and the URL will only display those new permissions that have not yet been accepted. - pub url: Option, -} - -impl ResponseResult for ProductsGenerateApprovalUrlResponse {} - - -/// 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, Serialize, Deserialize)] -pub struct GroupLicenseUsersListResponse { - /// Identifies what kind of resource this is. Value: the fixed string "androidenterprise#groupLicenseUsersListResponse". +pub struct User { + /// Identifies what kind of resource this is. Value: the fixed string "androidenterprise#user". pub kind: Option, - /// A user of an enterprise. - pub user: Option>, + /// The user's primary email, e.g. "jsmith@example.com". + #[serde(rename="primaryEmail")] + pub primary_email: Option, + /// The unique ID for the user. + pub id: Option, } -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(rename="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, Serialize, Deserialize)] -pub struct Device { - /// Identifies what kind of resource this is. Value: the fixed string "androidenterprise#device". - pub kind: Option, - /// The Google Play Services Android ID for the device encoded as a lowercase hex string, e.g. "123456789abcdef0". - #[serde(rename="androidId")] - pub android_id: Option, - /// The mechanism by which this device is managed by the MDM. "managedDevice" means that the MDM's app is a device owner. "managedProfile" means that the MDM's app is the profile owner (and there is a separate personal profile which is not managed). "containerApp" means that the MDM's app is managing the Android for Work container app on the device. - #[serde(rename="managementType")] - pub management_type: Option, -} - -impl Resource for Device {} -impl ResponseResult for Device {} +impl RequestValue for User {} +impl Resource for User {} +impl ResponseResult for User {} /// 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 by the enterprise admin. @@ -925,41 +1011,6 @@ impl Resource for GroupLicense {} impl ResponseResult for GroupLicense {} -/// 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(rename="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 {} - - // ################### // MethodBuilders ### @@ -1136,7 +1187,7 @@ impl<'a, C, A> CollectionviewerMethods<'a, C, A> { /// ::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(...)` +/// // like `generate_token(...)`, `get(...)`, `get_available_product_set(...)`, `list(...)`, `revoke_token(...)` and `set_available_product_set(...)` /// // to build up your call. /// let rb = hub.users(); /// # } @@ -1226,6 +1277,46 @@ impl<'a, C, A> UserMethods<'a, C, A> { _additional_params: Default::default(), } } + + /// Create a builder to help you perform the following task: + /// + /// Modifies the set of products a user is entitled to access. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `enterpriseId` - The ID of the enterprise. + /// * `userId` - The ID of the user. + pub fn set_available_product_set(&self, request: ProductSet, enterprise_id: &str, user_id: &str) -> UserSetAvailableProductSetCall<'a, C, A> { + UserSetAvailableProductSetCall { + hub: self.hub, + _request: request, + _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 set of products a user is entitled to access. + /// + /// # Arguments + /// + /// * `enterpriseId` - The ID of the enterprise. + /// * `userId` - The ID of the user. + pub fn get_available_product_set(&self, enterprise_id: &str, user_id: &str) -> UserGetAvailableProductSetCall<'a, C, A> { + UserGetAvailableProductSetCall { + 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(), + } + } } @@ -1536,7 +1627,7 @@ impl<'a, C, A> DeviceMethods<'a, C, A> { /// ::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(...)` +/// // like `delete(...)`, `enroll(...)`, `get(...)`, `insert(...)`, `list(...)`, `send_test_push_notification(...)`, `set_account(...)` and `unenroll(...)` /// // to build up your call. /// let rb = hub.enterprises(); /// # } @@ -1587,6 +1678,23 @@ impl<'a, C, A> EnterpriseMethods<'a, C, A> { } } + /// Create a builder to help you perform the following task: + /// + /// Sends a test push notification to validate the MDM integration with the Google Cloud Pub/Sub service for this enterprise. + /// + /// # Arguments + /// + /// * `enterpriseId` - The ID of the enterprise. + pub fn send_test_push_notification(&self, enterprise_id: &str) -> EnterpriseSendTestPushNotificationCall<'a, C, A> { + EnterpriseSendTestPushNotificationCall { + 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: /// /// Looks up an enterprise by domain name. @@ -1797,14 +1905,14 @@ impl<'a, C, A> CollectionMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Retrieves the details of a collection. + /// Deletes a collection. /// /// # Arguments /// /// * `enterpriseId` - The ID of the enterprise. /// * `collectionId` - The ID of the collection. - pub fn get(&self, enterprise_id: &str, collection_id: &str) -> CollectionGetCall<'a, C, A> { - CollectionGetCall { + pub fn delete(&self, enterprise_id: &str, collection_id: &str) -> CollectionDeleteCall<'a, C, A> { + CollectionDeleteCall { hub: self.hub, _enterprise_id: enterprise_id.to_string(), _collection_id: collection_id.to_string(), @@ -1816,14 +1924,14 @@ impl<'a, C, A> CollectionMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Deletes a collection. + /// Retrieves the details of a collection. /// /// # Arguments /// /// * `enterpriseId` - The ID of the enterprise. /// * `collectionId` - The ID of the collection. - pub fn delete(&self, enterprise_id: &str, collection_id: &str) -> CollectionDeleteCall<'a, C, A> { - CollectionDeleteCall { + pub fn get(&self, enterprise_id: &str, collection_id: &str) -> CollectionGetCall<'a, C, A> { + CollectionGetCall { hub: self.hub, _enterprise_id: enterprise_id.to_string(), _collection_id: collection_id.to_string(), @@ -4672,6 +4780,533 @@ impl<'a, C, A> UserGenerateTokenCall<'a, C, A> where C: BorrowMut } +/// Modifies the set of products a user is entitled to access. +/// +/// A builder for the *setAvailableProductSet* method supported by a *user* resource. +/// It is not used directly, but through a `UserMethods` instance. +/// +/// # 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::ProductSet; +/// # #[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 = ProductSet::default(); +/// +/// // You can configure optional parameters by calling 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().set_available_product_set(req, "enterpriseId", "userId") +/// .doit(); +/// # } +/// ``` +pub struct UserSetAvailableProductSetCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a AndroidEnterprise, + _request: ProductSet, + _enterprise_id: String, + _user_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for UserSetAvailableProductSetCall<'a, C, A> {} + +impl<'a, C, A> UserSetAvailableProductSetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ProductSet)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.setAvailableProductSet", + 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(("userId", self._user_id.to_string())); + for &field in ["alt", "enterpriseId", "userId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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}/availableProductSet".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_ref().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 ["userId", "enterpriseId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: ProductSet) -> UserSetAvailableProductSetCall<'a, C, A> { + self._request = new_value; + self + } + /// The ID of the enterprise. + /// + /// 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. + pub fn enterprise_id(mut self, new_value: &str) -> UserSetAvailableProductSetCall<'a, C, A> { + self._enterprise_id = new_value.to_string(); + self + } + /// The ID of the user. + /// + /// 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. + pub fn user_id(mut self, new_value: &str) -> UserSetAvailableProductSetCall<'a, C, A> { + self._user_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserSetAvailableProductSetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> UserSetAvailableProductSetCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Full`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> UserSetAvailableProductSetCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Retrieves the set of products a user is entitled to access. +/// +/// A builder for the *getAvailableProductSet* method supported by a *user* resource. +/// It is not used directly, but through a `UserMethods` instance. +/// +/// # 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_available_product_set("enterpriseId", "userId") +/// .doit(); +/// # } +/// ``` +pub struct UserGetAvailableProductSetCall<'a, C, A> + where C: '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, A> CallBuilder for UserGetAvailableProductSetCall<'a, C, A> {} + +impl<'a, C, A> UserGetAvailableProductSetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ProductSet)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.getAvailableProductSet", + 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 Err(Error::FieldClash(field)); + } + } + for (name, 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}/availableProductSet".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_ref().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 ["userId", "enterpriseId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The ID of the enterprise. + /// + /// 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. + pub fn enterprise_id(mut self, new_value: &str) -> UserGetAvailableProductSetCall<'a, C, A> { + self._enterprise_id = new_value.to_string(); + self + } + /// The ID of the user. + /// + /// 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. + pub fn user_id(mut self, new_value: &str) -> UserGetAvailableProductSetCall<'a, C, A> { + self._user_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserGetAvailableProductSetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> UserGetAvailableProductSetCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Full`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> UserGetAvailableProductSetCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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. @@ -7601,6 +8236,242 @@ impl<'a, C, A> EnterpriseInsertCall<'a, C, A> where C: BorrowMut, } +/// Sends a test push notification to validate the MDM integration with the Google Cloud Pub/Sub service for this enterprise. +/// +/// A builder for the *sendTestPushNotification* method supported by a *enterprise* resource. +/// It is not used directly, but through a `EnterpriseMethods` instance. +/// +/// # 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().send_test_push_notification("enterpriseId") +/// .doit(); +/// # } +/// ``` +pub struct EnterpriseSendTestPushNotificationCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a AndroidEnterprise, + _enterprise_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for EnterpriseSendTestPushNotificationCall<'a, C, A> {} + +impl<'a, C, A> EnterpriseSendTestPushNotificationCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, EnterprisesSendTestPushNotificationResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.sendTestPushNotification", + http_method: hyper::method::Method::Post }); + 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 Err(Error::FieldClash(field)); + } + } + for (name, 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}/sendTestPushNotification".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The ID of the enterprise. + /// + /// 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. + pub fn enterprise_id(mut self, new_value: &str) -> EnterpriseSendTestPushNotificationCall<'a, C, A> { + self._enterprise_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EnterpriseSendTestPushNotificationCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> EnterpriseSendTestPushNotificationCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Full`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> EnterpriseSendTestPushNotificationCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + /// Looks up an enterprise by domain name. /// /// A builder for the *list* method supported by a *enterprise* resource. @@ -9851,6 +10722,243 @@ impl<'a, C, A> CollectionListCall<'a, C, A> where C: BorrowMut, A } +/// Deletes a collection. +/// +/// A builder for the *delete* method supported by a *collection* resource. +/// It is not used directly, but through a `CollectionMethods` instance. +/// +/// # 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, A> + where C: '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, A> CallBuilder for CollectionDeleteCall<'a, C, A> {} + +impl<'a, C, A> CollectionDeleteCall<'a, C, A> where 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 Err(Error::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_ref().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 ["collectionId", "enterpriseId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = res; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The ID of the enterprise. + /// + /// 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. + pub fn enterprise_id(mut self, new_value: &str) -> CollectionDeleteCall<'a, C, A> { + self._enterprise_id = new_value.to_string(); + self + } + /// The ID of the collection. + /// + /// 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. + pub fn collection_id(mut self, new_value: &str) -> CollectionDeleteCall<'a, C, A> { + self._collection_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CollectionDeleteCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Full`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + /// Retrieves the details of a collection. /// /// A builder for the *get* method supported by a *collection* resource. @@ -10099,243 +11207,6 @@ impl<'a, C, A> CollectionGetCall<'a, C, A> where C: BorrowMut, A: } -/// Deletes a collection. -/// -/// A builder for the *delete* method supported by a *collection* resource. -/// It is not used directly, but through a `CollectionMethods` instance. -/// -/// # 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, A> - where C: '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, A> CallBuilder for CollectionDeleteCall<'a, C, A> {} - -impl<'a, C, A> CollectionDeleteCall<'a, C, A> where 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 Err(Error::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_ref().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 ["collectionId", "enterpriseId"].iter() { - if let Some(index) = params.iter().position(|t| &t.0 == param_name) { - indices_for_removal.push(index); - } - } - for &index in indices_for_removal.iter() { - params.remove(index); - } - } - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_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) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = res; - - dlg.finished(true); - return Ok(result_value) - } - } - } - } - - - /// The ID of the enterprise. - /// - /// 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. - pub fn enterprise_id(mut self, new_value: &str) -> CollectionDeleteCall<'a, C, A> { - self._enterprise_id = new_value.to_string(); - self - } - /// The ID of the collection. - /// - /// 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. - pub fn collection_id(mut self, new_value: &str) -> CollectionDeleteCall<'a, C, A> { - self._collection_id = new_value.to_string(); - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> CollectionDeleteCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. - /// * *fields* (query-string) - Selector specifying which 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, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::Full`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing 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, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().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. @@ -11428,7 +12299,7 @@ impl<'a, C, A> EntitlementGetCall<'a, C, A> where C: BorrowMut, A /// // 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) +/// .install(false) /// .doit(); /// # } /// ``` @@ -12222,7 +13093,7 @@ impl<'a, C, A> ProductGetPermissionCall<'a, C, A> where C: BorrowMut ProductApproveCall<'a, C, A> where C: BorrowMut, A /// // 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("rebum.") +/// .language("sed") /// .doit(); /// # } /// ``` @@ -13291,7 +14162,7 @@ impl<'a, C, A> ProductUpdatePermissionCall<'a, C, A> where C: BorrowMut GrouplicenseListCall<'a, C, A> where C: BorrowMut, /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.permissions().get("permissionId") -/// .language("ea") +/// .language("dolores") /// .doit(); /// # } /// ``` diff --git a/gen/androidpublisher2-cli/Cargo.toml b/gen/androidpublisher2-cli/Cargo.toml index 0195d5400b..77b421ea60 100644 --- a/gen/androidpublisher2-cli/Cargo.toml +++ b/gen/androidpublisher2-cli/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-androidpublisher2-cli" -version = "0.3.2+20150316" +version = "0.3.2+20150910" 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-cli" diff --git a/gen/androidpublisher2-cli/README.md b/gen/androidpublisher2-cli/README.md index 7a06df53fa..47eeb48e21 100644 --- a/gen/androidpublisher2-cli/README.md +++ b/gen/androidpublisher2-cli/README.md @@ -24,7 +24,7 @@ Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/ma # Usage -This documentation was generated from the *Android Publisher* API at revision *20150316*. The CLI is at version *0.3.2*. +This documentation was generated from the *Android Publisher* API at revision *20150910*. The CLI is at version *0.3.2*. ```bash androidpublisher2 [options] diff --git a/gen/androidpublisher2-cli/mkdocs.yml b/gen/androidpublisher2-cli/mkdocs.yml index 9d39604ab3..6e9074d150 100644 --- a/gen/androidpublisher2-cli/mkdocs.yml +++ b/gen/androidpublisher2-cli/mkdocs.yml @@ -1,4 +1,4 @@ -site_name: Android Publisher v0.3.2+20150316 +site_name: Android Publisher v0.3.2+20150910 site_url: http://byron.github.io/google-apis-rs/google-androidpublisher2-cli site_description: Write integrating applications with bcore diff --git a/gen/androidpublisher2-cli/src/main.rs b/gen/androidpublisher2-cli/src/main.rs index 1ecfa3d4e0..1107ad0885 100644 --- a/gen/androidpublisher2-cli/src/main.rs +++ b/gen/androidpublisher2-cli/src/main.rs @@ -5466,7 +5466,7 @@ fn main() { let mut app = App::new("androidpublisher2") .author("Sebastian Thiel ") - .version("0.3.2+20150316") + .version("0.3.2+20150910") .about("Lets Android application developers access their Google Play accounts.") .after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_androidpublisher2_cli") .arg(Arg::with_name("url") diff --git a/gen/androidpublisher2/Cargo.toml b/gen/androidpublisher2/Cargo.toml index 55c1d0c93d..f0de7b005d 100644 --- a/gen/androidpublisher2/Cargo.toml +++ b/gen/androidpublisher2/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-androidpublisher2" -version = "0.1.9+20150316" +version = "0.1.9+20150910" 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" diff --git a/gen/androidpublisher2/README.md b/gen/androidpublisher2/README.md index 40ff397f79..e0b28aa516 100644 --- a/gen/androidpublisher2/README.md +++ b/gen/androidpublisher2/README.md @@ -5,7 +5,7 @@ DO NOT EDIT ! --> 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.9+20150316*, where *20150316* is the exact revision of the *androidpublisher:v2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +This documentation was generated from *Android Publisher* crate version *0.1.9+20150910*, where *20150910* is the exact revision of the *androidpublisher:v2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. Everything else about the *Android Publisher* *v2* API can be found at the [official documentation site](https://developers.google.com/android-publisher). diff --git a/gen/androidpublisher2/src/lib.rs b/gen/androidpublisher2/src/lib.rs index 897746db91..33b4cb92b0 100644 --- a/gen/androidpublisher2/src/lib.rs +++ b/gen/androidpublisher2/src/lib.rs @@ -2,7 +2,7 @@ // This file was generated automatically from 'src/mako/api/lib.rs.mako' // DO NOT EDIT ! -//! This documentation was generated from *Android Publisher* crate version *0.1.9+20150316*, where *20150316* is the exact revision of the *androidpublisher:v2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +//! This documentation was generated from *Android Publisher* crate version *0.1.9+20150910*, where *20150910* is the exact revision of the *androidpublisher:v2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. //! //! Everything else about the *Android Publisher* *v2* API can be found at the //! [official documentation site](https://developers.google.com/android-publisher). diff --git a/gen/androidpublisher2/src/lib.rs.in b/gen/androidpublisher2/src/lib.rs.in index 96340a3989..15395ff785 100644 --- a/gen/androidpublisher2/src/lib.rs.in +++ b/gen/androidpublisher2/src/lib.rs.in @@ -224,7 +224,7 @@ pub struct InAppProduct { 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. + /// Subscription period, specified in ISO 8601 format. Acceptable values are "P1W" (one week), "P1M" (one month) and "P1Y" (one year). #[serde(rename="subscriptionPeriod")] pub subscription_period: Option, /// Definition of a season for a seasonal subscription. Can be defined only for yearly subscriptions. @@ -4492,10 +4492,10 @@ impl<'a, C, A> EditImageUploadCall<'a, C, A> where C: BorrowMut, self.doit(stream, mime_type, "simple") } /// Upload media in a resumable fashion. - /// Even if the upload fails or is interrupted, it can be resumed for a + /// Even if the upload fails or is interrupted, it can be resumed for a /// certain amount of time as the server maintains state temporarily. /// - /// The delegate will be asked for an `upload_url()`, and if not provided, will be asked to store an upload URL + /// The delegate will be asked for an `upload_url()`, and if not provided, will be asked to store an upload URL /// that was provided by the server, using `store_upload_url(...)`. The upload will be done in chunks, the delegate /// may specify the `chunk_size()` and may cancel the operation before each chunk is uploaded, using /// `cancel_chunk_upload(...)`. @@ -8395,10 +8395,10 @@ impl<'a, C, A> EditApkUploadCall<'a, C, A> where C: BorrowMut, A: self.doit(stream, mime_type, "simple") } /// Upload media in a resumable fashion. - /// Even if the upload fails or is interrupted, it can be resumed for a + /// Even if the upload fails or is interrupted, it can be resumed for a /// certain amount of time as the server maintains state temporarily. /// - /// The delegate will be asked for an `upload_url()`, and if not provided, will be asked to store an upload URL + /// The delegate will be asked for an `upload_url()`, and if not provided, will be asked to store an upload URL /// that was provided by the server, using `store_upload_url(...)`. The upload will be done in chunks, the delegate /// may specify the `chunk_size()` and may cancel the operation before each chunk is uploaded, using /// `cancel_chunk_upload(...)`. @@ -10623,10 +10623,10 @@ impl<'a, C, A> EditExpansionfileUploadCall<'a, C, A> where C: BorrowMut"] +description = "A complete library to interact with appengine (protocol v1beta4)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/appengine1_beta4-cli" +homepage = "https://developers.google.com/appengine/" +documentation = "http://byron.github.io/google-apis-rs/google_appengine1_beta4_cli" +license = "MIT" +keywords = ["appengine", "google", "cli"] + +[[bin]] +name = "appengine1-beta4" + +[dependencies] +hyper = ">= 0.6.8" +mime = "0.1.0" +serde = ">= 0.6.0" +serde_json = ">= 0.6.0" +yup-oauth2 = "*" +strsim = "*" +yup-hyper-mock = ">=1.0.0" +clap = ">= 1.0.3" + +[build-dependencies] +syntex = { version = "*" } +serde_codegen = { version = "*" } + + +[dependencies.google-appengine1_beta4] +path = "../appengine1_beta4" diff --git a/gen/appengine1_beta4-cli/LICENSE.md b/gen/appengine1_beta4-cli/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/appengine1_beta4-cli/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/appengine1_beta4-cli/README.md b/gen/appengine1_beta4-cli/README.md new file mode 100644 index 0000000000..bacb0b9032 --- /dev/null +++ b/gen/appengine1_beta4-cli/README.md @@ -0,0 +1,123 @@ + +The `appengine1-beta4` command-line interface *(CLI)* allows to use most features of the *Google appengine* service from the comfort of your terminal. + +By default all output is printed to standard out, but flags can be set to direct it into a file independent of your shell's +capabilities. Errors will be printed to standard error, and cause the program's exit code to be non-zero. + +If data-structures are requested, these will be returned as pretty-printed JSON, to be useful as input to other tools. + +Everything else about the *appengine* API can be found at the +[official documentation site](https://developers.google.com/appengine/). + +# Downloads + +You can download the pre-compiled 64bit binaries for the following platforms: + +* ![icon](http://megaicons.net/static/img/icons_sizes/6/140/16/ubuntu-icon.png) [ubuntu](http://dl.byronimo.de/google.rs/cli/0.3.2/ubuntu/appengine1-beta4.tar.gz) +* ![icon](http://hydra-media.cursecdn.com/wow.gamepedia.com/a/a2/Apple-icon-16x16.png?version=25ddd67ac3dd3b634478e3978b76cb74) [osx](http://dl.byronimo.de/google.rs/cli/0.3.2/osx/appengine1-beta4.tar.gz) + +Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/appengine1_beta4-cli). + +# Usage + +This documentation was generated from the *appengine* API at revision *20150831*. The CLI is at version *0.3.2*. + +```bash +appengine1-beta4 [options] + apps + get [-p ]... [-o ] + modules-delete [-p ]... [-o ] + modules-get [-p ]... [-o ] + modules-list [-p ]... [-o ] + modules-patch (-r )... [-p ]... [-o ] + modules-versions-create (-r )... [-p ]... [-o ] + modules-versions-delete [-p ]... [-o ] + modules-versions-get [-p ]... [-o ] + modules-versions-list [-p ]... [-o ] + operations-get [-p ]... [-o ] + operations-list [-p ]... [-o ] + appengine1-beta4 --help + +Configuration: + [--scope ]... + Specify the authentication a method should be executed in. Each scope + requires the user to grant this application permission to use it. + If unset, it defaults to the shortest scope url for a particular method. + --config-dir + A directory into which we will store our persistent data. Defaults to + a user-writable directory that we will create during the first invocation. + [default: ~/.google-service-cli] + --debug + Output all server communication to standard error. `tx` and `rx` are placed + into the same stream. + --debug-auth + Output all communication related to authentication to standard error. `tx` + and `rx` are placed into the same stream. + +``` + +# Configuration + +The program will store all persistent data in the `~/.google-service-cli` directory in *JSON* files prefixed with `appengine1-beta4-`. You can change the directory used to store configuration with the `--config-dir` flag on a per-invocation basis. + +More information about the various kinds of persistent data are given in the following paragraphs. + +# Authentication + +Most APIs require a user to authenticate any request. If this is the case, the [scope][scopes] determines the +set of permissions granted. The granularity of these is usually no more than *read-only* or *full-access*. + +If not set, the system will automatically select the smallest feasible scope, e.g. when invoking a +method that is read-only, it will ask only for a read-only scope. +You may use the `--scope` flag to specify a scope directly. +All applicable scopes are documented in the respective method's CLI documentation. + +The first time a scope is used, the user is asked for permission. Follow the instructions given +by the CLI to grant permissions, or to decline. + +If a scope was authenticated by the user, the respective information will be stored as *JSON* in the configuration +directory, e.g. `~/.google-service-cli/appengine1-beta4-token-.json`. No manual management of these tokens +is necessary. + +To revoke granted authentication, please refer to the [official documentation][revoke-access]. + +# Application Secrets + +In order to allow any application to use Google services, it will need to be registered using the +[Google Developer Console][google-dev-console]. APIs the application may use are then enabled for it +one by one. Most APIs can be used for free and have a daily quota. + +To allow more comfortable usage of the CLI without forcing anyone to register an own application, the CLI +comes with a default application secret that is configured accordingly. This also means that heavy usage +all around the world may deplete the daily quota. + +You can workaround this limitation by putting your own secrets file at this location: +`~/.google-service-cli/appengine1-beta4-secret.json`, assuming that the required *appengine* API +was enabled for it. Such a secret file can be downloaded in the *Google Developer Console* at +*APIs & auth -> Credentials -> Download JSON* and used as is. + +Learn more about how to setup Google projects and enable APIs using the [official documentation][google-project-new]. + + +# Debugging + +Even though the CLI does its best to provide usable error messages, sometimes it might be desirable to know +what exactly led to a particular issue. This is done by allowing all client-server communication to be +output to standard error *as-is*. + +The `--debug` flag will print all client-server communication to standard error, whereas the `--debug-auth` flag +will cause all communication related to authentication to standard error. +If the `--debug` flag is set, error-results will be debug-printed, possibly yielding more information about the +issue at hand. + +You may consider redirecting standard error into a file for ease of use, e.g. `appengine1-beta4 --debug [options] 2>debug.txt`. + + +[scopes]: https://developers.google.com/+/api/oauth#scopes +[revoke-access]: http://webapps.stackexchange.com/a/30849 +[google-dev-console]: https://console.developers.google.com/ +[google-project-new]: https://developers.google.com/console/help/new/ \ No newline at end of file diff --git a/gen/appengine1_beta4-cli/mkdocs.yml b/gen/appengine1_beta4-cli/mkdocs.yml new file mode 100644 index 0000000000..b341bfb11e --- /dev/null +++ b/gen/appengine1_beta4-cli/mkdocs.yml @@ -0,0 +1,27 @@ +site_name: appengine v0.3.2+20150831 +site_url: http://byron.github.io/google-apis-rs/google-appengine1_beta4-cli +site_description: Write integrating applications with bcore + +repo_url: https://github.com/Byron/google-apis-rs/tree/master/gen/appengine1_beta4-cli + +docs_dir: docs +site_dir: build_html + +pages: +- ['index.md', 'Home'] +- ['apps_get.md', 'Apps', 'Get'] +- ['apps_modules-delete.md', 'Apps', 'Modules Delete'] +- ['apps_modules-get.md', 'Apps', 'Modules Get'] +- ['apps_modules-list.md', 'Apps', 'Modules List'] +- ['apps_modules-patch.md', 'Apps', 'Modules Patch'] +- ['apps_modules-versions-create.md', 'Apps', 'Modules Versions Create'] +- ['apps_modules-versions-delete.md', 'Apps', 'Modules Versions Delete'] +- ['apps_modules-versions-get.md', 'Apps', 'Modules Versions Get'] +- ['apps_modules-versions-list.md', 'Apps', 'Modules Versions List'] +- ['apps_operations-get.md', 'Apps', 'Operations Get'] +- ['apps_operations-list.md', 'Apps', 'Operations List'] + +theme: readthedocs + +copyright: Copyright © 2015, `Sebastian Thiel` + diff --git a/gen/appengine1_beta4-cli/src/cmn.rs b/gen/appengine1_beta4-cli/src/cmn.rs new file mode 100644 index 0000000000..8358f156fa --- /dev/null +++ b/gen/appengine1_beta4-cli/src/cmn.rs @@ -0,0 +1,721 @@ +// COPY OF 'src/rust/cli/cmn.rs' +// DO NOT EDIT +use oauth2::{ApplicationSecret, ConsoleApplicationSecret, TokenStorage, Token}; +use serde_json as json; +use serde_json::value::Value; +use mime::Mime; +use clap::{App, SubCommand}; +use strsim; + +use std::fs; +use std::env; +use std::io; +use std::fmt; +use std::path::{Path, PathBuf}; +use std::str::FromStr; +use std::string::ToString; +use std::io::{Write, Read, stdout}; + +use std::default::Default; + +const FIELD_SEP: char = '.'; + + +pub enum ComplexType { + Pod, + Vec, + Map, +} + + // Null, + // Bool(bool), + // I64(i64), + // U64(u64), + // F64(f64), + // String(String), + +pub enum JsonType { + Boolean, + Int, + Uint, + Float, + String, +} + +pub struct JsonTypeInfo { + pub jtype: JsonType, + pub ctype: ComplexType, +} + +// Based on @erickt user comment. Thanks for the idea ! +// Remove all keys whose values are null from given value (changed in place) +pub fn remove_json_null_values(value: &mut Value) { + match *value { + Value::Object(ref mut map) => { + let mut for_removal = Vec::new(); + + for (key, mut value) in map.iter_mut() { + if value.is_null() { + for_removal.push(key.clone()); + } else { + remove_json_null_values(&mut value); + } + } + + for key in &for_removal { + map.remove(key); + } + } + _ => {} + } +} + +fn did_you_mean<'a>(v: &str, possible_values: &[&'a str]) -> Option<&'a str> { + + let mut candidate: Option<(f64, &str)> = None; + for pv in possible_values { + let confidence = strsim::jaro_winkler(v, pv); + if confidence > 0.8 && (candidate.is_none() || (candidate.as_ref().unwrap().0 < confidence)) { + candidate = Some((confidence, pv)); + } + } + match candidate { + None => None, + Some((_, candidate)) => Some(candidate), + } +} + +pub enum CallType { + Upload(UploadProtocol), + Standard, +} + +arg_enum!{ + pub enum UploadProtocol { + Simple, + Resumable + } +} + +impl AsRef for UploadProtocol { + fn as_ref(&self) -> &str { + match *self { + UploadProtocol::Simple => "simple", + UploadProtocol::Resumable => "resumable" + } + } +} + +impl AsRef for CallType { + fn as_ref(&self) -> &str { + match *self { + CallType::Upload(ref proto) => proto.as_ref(), + CallType::Standard => "standard-request" + } + } +} + +#[derive(Clone, Default)] +pub struct FieldCursor(Vec); + +impl ToString for FieldCursor { + fn to_string(&self) -> String { + self.0.join(".") + } +} + +impl From<&'static str> for FieldCursor { + fn from(value: &'static str) -> FieldCursor { + let mut res = FieldCursor::default(); + res.set(value).unwrap(); + res + } +} + +impl FieldCursor { + pub fn set(&mut self, value: &str) -> Result<(), CLIError> { + if value.len() == 0 { + return Err(CLIError::Field(FieldError::Empty)) + } + + let mut first_is_field_sep = false; + let mut char_count: usize = 0; + let mut last_c = FIELD_SEP; + let mut num_conscutive_field_seps = 0; + + let mut field = String::new(); + let mut fields = self.0.clone(); + + let push_field = |fs: &mut Vec, f: &mut String| { + if f.len() > 0 { + fs.push(f.clone()); + f.truncate(0); + } + }; + + for (cid, c) in value.chars().enumerate() { + char_count += 1; + + if c == FIELD_SEP { + if cid == 0 { + first_is_field_sep = true; + } + num_conscutive_field_seps += 1; + if cid > 0 && last_c == FIELD_SEP { + if fields.pop().is_none() { + return Err(CLIError::Field(FieldError::PopOnEmpty(value.to_string()))) + } + } else { + push_field(&mut fields, &mut field); + } + } else { + num_conscutive_field_seps = 0; + if cid == 1 { + if first_is_field_sep { + fields.truncate(0); + } + } + field.push(c); + } + + last_c = c; + } + + push_field(&mut fields, &mut field); + + if char_count == 1 && first_is_field_sep { + fields.truncate(0); + } + if char_count > 1 && num_conscutive_field_seps == 1 { + return Err(CLIError::Field(FieldError::TrailingFieldSep(value.to_string()))) + } + + self.0 = fields; + Ok(()) + } + + pub fn did_you_mean(value: &str, possible_values: &[&str]) -> Option { + if value.len() == 0 { + return None + } + + let mut last_c = FIELD_SEP; + + let mut field = String::new(); + let mut output = String::new(); + + let push_field = |fs: &mut String, f: &mut String| { + if f.len() > 0 { + fs.push_str( + match did_you_mean(&f, possible_values) { + Some(candidate) => candidate, + None => &f, + }); + f.truncate(0); + } + }; + + for (cid, c) in value.chars().enumerate() { + if c == FIELD_SEP { + if last_c != FIELD_SEP { + push_field(&mut output, &mut field); + } + output.push(c); + } else { + field.push(c); + } + + last_c = c; + } + + push_field(&mut output, &mut field); + + if &output == value { + None + } else { + Some(output) + } + } + + pub fn set_json_value(&self, mut object: &mut Value, + value: &str, type_info: JsonTypeInfo, + err: &mut InvalidOptionsError, + orig_cursor: &FieldCursor) { + assert!(self.0.len() > 0); + + for field in &self.0[..self.0.len()-1] { + let tmp = object; + object = + match *tmp { + Value::Object(ref mut mapping) => { + mapping.entry(field.to_owned()).or_insert( + Value::Object(Default::default()) + ) + }, + _ => panic!("We don't expect non-object Values here ...") + }; + } + + match *object { + Value::Object(ref mut mapping) => { + let field = &self.0[self.0.len()-1]; + let to_jval = + |value: &str, jtype: JsonType, err: &mut InvalidOptionsError| + -> Value { + match jtype { + JsonType::Boolean => + Value::Bool(arg_from_str(value, err, &field, "boolean")), + JsonType::Int => + Value::I64(arg_from_str(value, err, &field, "int")), + JsonType::Uint => + Value::U64(arg_from_str(value, err, &field, "uint")), + JsonType::Float => + Value::F64(arg_from_str(value, err, &field, "float")), + JsonType::String => + Value::String(value.to_owned()), + } + }; + + match type_info.ctype { + ComplexType::Pod => { + if mapping.insert(field.to_owned(), to_jval(value, type_info.jtype, err)).is_some() { + err.issues.push(CLIError::Field(FieldError::Duplicate(orig_cursor.to_string()))); + } + }, + ComplexType::Vec => { + match *mapping.entry(field.to_owned()) + .or_insert(Value::Array(Default::default())) { + Value::Array(ref mut values) => values.push(to_jval(value, type_info.jtype, err)), + _ => unreachable!() + } + }, + ComplexType::Map => { + let (key, value) = parse_kv_arg(value, err, true); + let jval = to_jval(value.unwrap_or(""), type_info.jtype, err); + + match *mapping.entry(field.to_owned()) + .or_insert(Value::Object(Default::default())) { + Value::Object(ref mut value_map) => { + if value_map.insert(key.to_owned(), jval).is_some() { + err.issues.push(CLIError::Field(FieldError::Duplicate(orig_cursor.to_string()))); + } + } + _ => unreachable!() + } + } + } + }, + _ => unreachable!() + } + } + + pub fn num_fields(&self) -> usize { + self.0.len() + } +} + +pub fn parse_kv_arg<'a>(kv: &'a str, err: &mut InvalidOptionsError, for_hashmap: bool) + -> (&'a str, Option<&'a str>) { + let mut add_err = || err.issues.push(CLIError::InvalidKeyValueSyntax(kv.to_string(),for_hashmap)); + match kv.find('=') { + None => { + add_err(); + return (kv, None) + }, + Some(pos) => { + let key = &kv[..pos]; + if kv.len() <= pos + 1 { + add_err(); + return (key, Some("")) + } + (key, Some(&kv[pos+1..])) + } + } +} + +pub fn calltype_from_str(name: &str, valid_protocols: Vec, err: &mut InvalidOptionsError) -> CallType { + CallType::Upload( + match UploadProtocol::from_str(name) { + Ok(up) => up, + Err(msg) => { + err.issues.push(CLIError::InvalidUploadProtocol(name.to_string(), valid_protocols)); + UploadProtocol::Simple + } + }) +} + +pub fn input_file_from_opts(file_path: &str, err: &mut InvalidOptionsError) -> Option { + match fs::File::open(file_path) { + Ok(f) => Some(f), + Err(io_err) => { + err.issues.push(CLIError::Input(InputError::IOError((file_path.to_string(), io_err)))); + None + } + } +} + +pub fn input_mime_from_opts(mime: &str, err: &mut InvalidOptionsError) -> Option { + match mime.parse() { + Ok(m) => Some(m), + Err(_) => { + err.issues.push(CLIError::Input(InputError::Mime(mime.to_string()))); + None + } + } +} + +pub fn writer_from_opts(arg: Option<&str>) -> Result, io::Error> { + let f = arg.unwrap_or("-"); + match f { + "-" => Ok(Box::new(stdout())), + _ => match fs::OpenOptions::new().create(true).write(true).open(f) { + Ok(f) => Ok(Box::new(f)), + Err(io_err) => Err(io_err), + } + } +} + + +pub fn arg_from_str<'a, T>(arg: &str, err: &mut InvalidOptionsError, + arg_name: &'a str, + arg_type: &'a str) -> T + where T: FromStr + Default, + ::Err: fmt::Display { + match FromStr::from_str(arg) { + Err(perr) => { + err.issues.push( + CLIError::ParseError(arg_name.to_owned(), arg_type.to_owned(), arg.to_string(), format!("{}", perr)) + ); + Default::default() + }, + Ok(v) => v, + } +} + +pub struct JsonTokenStorage { + pub program_name: &'static str, + pub db_dir: String, +} + +impl JsonTokenStorage { + fn path(&self, scope_hash: u64) -> PathBuf { + Path::new(&self.db_dir).join(&format!("{}-token-{}.json", self.program_name, scope_hash)) + } +} + +impl TokenStorage for JsonTokenStorage { + type Error = json::Error; + + // NOTE: logging might be interesting, currently we swallow all errors + fn set(&mut self, scope_hash: u64, _: &Vec<&str>, token: Option) -> Result<(), json::Error> { + match token { + None => { + match fs::remove_file(self.path(scope_hash)) { + Err(err) => + match err.kind() { + io::ErrorKind::NotFound => Ok(()), + _ => Err(json::Error::IoError(err)) + }, + Ok(_) => Ok(()), + } + } + Some(token) => { + match fs::OpenOptions::new().create(true).write(true).open(&self.path(scope_hash)) { + Ok(mut f) => { + match json::to_writer_pretty(&mut f, &token) { + Ok(_) => Ok(()), + Err(serde_err) => Err(serde_err), + } + }, + Err(io_err) => Err(json::Error::IoError(io_err)) + } + } + } + } + + fn get(&self, scope_hash: u64, _: &Vec<&str>) -> Result, json::Error> { + match fs::File::open(&self.path(scope_hash)) { + Ok(mut f) => { + match json::de::from_reader(f) { + Ok(token) => Ok(Some(token)), + Err(err) => Err(err), + } + }, + Err(io_err) => { + match io_err.kind() { + io::ErrorKind::NotFound => Ok(None), + _ => Err(json::Error::IoError(io_err)) + } + } + } + } +} + + +#[derive(Debug)] +pub enum ApplicationSecretError { + DecoderError((String, json::Error)), + FormatError(String), +} + +impl fmt::Display for ApplicationSecretError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + ApplicationSecretError::DecoderError((ref path, ref err)) + => writeln!(f, "Could not decode file at '{}' with error: {}.", + path, err), + ApplicationSecretError::FormatError(ref path) + => writeln!(f, "'installed' field is unset in secret file at '{}'.", + path), + } + } +} + +#[derive(Debug)] +pub enum ConfigurationError { + DirectoryCreationFailed((String, io::Error)), + DirectoryUnset, + HomeExpansionFailed(String), + Secret(ApplicationSecretError), + IOError((String, io::Error)), +} + +impl fmt::Display for ConfigurationError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + ConfigurationError::DirectoryCreationFailed((ref dir, ref err)) + => writeln!(f, "Directory '{}' could not be created with error: {}.", dir, err), + ConfigurationError::DirectoryUnset + => writeln!(f, "--config-dir was unset or empty."), + ConfigurationError::HomeExpansionFailed(ref dir) + => writeln!(f, "Couldn't find HOME directory of current user, failed to expand '{}'.", dir), + ConfigurationError::Secret(ref err) + => writeln!(f, "Secret -> {}", err), + ConfigurationError::IOError((ref path, ref err)) + => writeln!(f, "IO operation failed on path '{}' with error: {}.", path, err), + } + } +} + +#[derive(Debug)] +pub enum InputError { + IOError((String, io::Error)), + Mime(String), +} + +impl fmt::Display for InputError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + InputError::IOError((ref file_path, ref io_err)) + => writeln!(f, "Failed to open '{}' for reading with error: {}.", file_path, io_err), + InputError::Mime(ref mime) + => writeln!(f, "'{}' is not a known mime-type.", mime), + } + } +} + +#[derive(Debug)] +pub enum FieldError { + PopOnEmpty(String), + TrailingFieldSep(String), + Unknown(String, Option, Option), + Duplicate(String), + Empty, +} + + +impl fmt::Display for FieldError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + FieldError::PopOnEmpty(ref field) + => writeln!(f, "'{}': Cannot move up on empty field cursor.", field), + FieldError::TrailingFieldSep(ref field) + => writeln!(f, "'{}': Single field separator may not be last character.", field), + FieldError::Unknown(ref field, ref suggestion, ref value) => { + let suffix = + match *suggestion { + Some(ref s) => { + let kv = + match *value { + Some(ref v) => format!("{}={}", s, v), + None => s.clone(), + }; + format!(" Did you mean '{}' ?", kv) + }, + None => String::new(), + }; + writeln!(f, "Field '{}' does not exist.{}", field, suffix) + }, + FieldError::Duplicate(ref cursor) + => writeln!(f, "Value at '{}' was already set", cursor), + FieldError::Empty + => writeln!(f, "Field names must not be empty."), + } + } +} + + +#[derive(Debug)] +pub enum CLIError { + Configuration(ConfigurationError), + ParseError(String, String, String, String), + UnknownParameter(String, Vec<&'static str>), + InvalidUploadProtocol(String, Vec), + InvalidKeyValueSyntax(String, bool), + Input(InputError), + Field(FieldError), + MissingCommandError, + MissingMethodError(String), +} + +impl fmt::Display for CLIError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + CLIError::Configuration(ref err) => write!(f, "Configuration -> {}", err), + CLIError::Input(ref err) => write!(f, "Input -> {}", err), + CLIError::Field(ref err) => write!(f, "Field -> {}", err), + CLIError::InvalidUploadProtocol(ref proto_name, ref valid_names) + => writeln!(f, "'{}' is not a valid upload protocol. Choose from one of {}.", proto_name, valid_names.join(", ")), + CLIError::ParseError(ref arg_name, ref type_name, ref value, ref err_desc) + => writeln!(f, "Failed to parse argument '{}' with value '{}' as {} with error: {}.", + arg_name, value, type_name, err_desc), + CLIError::UnknownParameter(ref param_name, ref possible_values) => { + let mut suffix = + match did_you_mean(param_name, &possible_values) { + Some(v) => format!(" Did you mean '{}' ?", v), + None => String::new(), + }; + write!(f, "Parameter '{}' is unknown.{}\n", param_name, suffix) + }, + CLIError::InvalidKeyValueSyntax(ref kv, is_hashmap) => { + let hashmap_info = if is_hashmap { "hashmap " } else { "" }; + writeln!(f, "'{}' does not match {}pattern =.", kv, hashmap_info) + }, + CLIError::MissingCommandError => writeln!(f, "Please specify the main sub-command."), + CLIError::MissingMethodError(ref cmd) => writeln!(f, "Please specify the method to call on the '{}' command.", cmd), + } + } +} + +#[derive(Debug)] +pub struct InvalidOptionsError { + pub issues: Vec, + pub exit_code: i32, +} + +impl fmt::Display for InvalidOptionsError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + for issue in &self.issues { + try!(issue.fmt(f)); + } + Ok(()) + } +} + +impl InvalidOptionsError { + pub fn single(err: CLIError, exit_code: i32) -> InvalidOptionsError { + InvalidOptionsError { + issues: vec![err], + exit_code: exit_code, + } + } + + pub fn new() -> InvalidOptionsError { + InvalidOptionsError { + issues: Vec::new(), + exit_code: 1, + } + } +} + +pub fn assure_config_dir_exists(dir: &str) -> Result { + let trdir = dir.trim(); + if trdir.len() == 0 { + return Err(CLIError::Configuration(ConfigurationError::DirectoryUnset)) + } + + let expanded_config_dir = + if trdir.as_bytes()[0] == b'~' { + match env::var("HOME").ok().or(env::var("UserProfile").ok()) { + None => return Err(CLIError::Configuration(ConfigurationError::HomeExpansionFailed(trdir.to_string()))), + Some(mut user) => { + user.push_str(&trdir[1..]); + user + } + } + } else { + trdir.to_string() + }; + + if let Err(err) = fs::create_dir(&expanded_config_dir) { + if err.kind() != io::ErrorKind::AlreadyExists { + return Err(CLIError::Configuration( + ConfigurationError::DirectoryCreationFailed((expanded_config_dir, err)))) + } + } + + Ok(expanded_config_dir) +} + +pub fn application_secret_from_directory(dir: &str, + secret_basename: &str, + json_console_secret: &str) + -> Result { + let secret_path = Path::new(dir).join(secret_basename); + let secret_str = || secret_path.as_path().to_str().unwrap().to_string(); + let secret_io_error = |io_err: io::Error| { + Err(CLIError::Configuration(ConfigurationError::IOError( + (secret_str(), io_err) + ))) + }; + + for _ in 0..2 { + match fs::File::open(&secret_path) { + Err(mut err) => { + if err.kind() == io::ErrorKind::NotFound { + // Write our built-in one - user may adjust the written file at will + + err = match fs::OpenOptions::new().create(true).write(true).open(&secret_path) { + Err(cfe) => cfe, + Ok(mut f) => { + // Assure we convert 'ugly' json string into pretty one + let console_secret: ConsoleApplicationSecret + = json::from_str(json_console_secret).unwrap(); + match json::to_writer_pretty(&mut f, &console_secret) { + Err(serde_err) => match serde_err { + json::Error::IoError(err) => err, + _ => panic!("Unexpected serde error: {:#?}", serde_err) + }, + Ok(_) => continue, + } + } + }; + // fall through to IO error handling + } + return secret_io_error(err) + }, + Ok(mut f) => { + match json::de::from_reader::<_, ConsoleApplicationSecret>(f) { + Err(json::Error::IoError(err)) => + return secret_io_error(err), + Err(json_err) => + return Err(CLIError::Configuration( + ConfigurationError::Secret( + ApplicationSecretError::DecoderError( + (secret_str(), json_err) + )))), + Ok(console_secret) => + match console_secret.installed { + Some(secret) => return Ok(secret), + None => return Err( + CLIError::Configuration( + ConfigurationError::Secret( + ApplicationSecretError::FormatError(secret_str()) + ))) + }, + } + } + } + } + unreachable!(); +} diff --git a/gen/appengine1_beta4-cli/src/main.rs b/gen/appengine1_beta4-cli/src/main.rs new file mode 100644 index 0000000000..a55e4f6c64 --- /dev/null +++ b/gen/appengine1_beta4-cli/src/main.rs @@ -0,0 +1,1323 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/cli/main.rs.mako' +// DO NOT EDIT ! +#![allow(unused_variables, unused_imports, dead_code, unused_mut)] + +#[macro_use] +extern crate clap; +extern crate yup_oauth2 as oauth2; +extern crate yup_hyper_mock as mock; +extern crate serde; +extern crate serde_json; +extern crate hyper; +extern crate mime; +extern crate strsim; +extern crate google_appengine1_beta4 as api; + +use std::env; +use std::io::{self, Write}; +use clap::{App, SubCommand, Arg}; + +mod cmn; + +use cmn::{InvalidOptionsError, CLIError, JsonTokenStorage, arg_from_str, writer_from_opts, parse_kv_arg, + input_file_from_opts, input_mime_from_opts, FieldCursor, FieldError, CallType, UploadProtocol, + calltype_from_str, remove_json_null_values, ComplexType, JsonType, JsonTypeInfo}; + +use std::default::Default; +use std::str::FromStr; + +use oauth2::{Authenticator, DefaultAuthenticatorDelegate}; +use serde_json as json; +use clap::ArgMatches; + +enum DoitError { + IoError(String, io::Error), + ApiError(api::Error), +} + +struct Engine<'n, 'a> { + opt: ArgMatches<'n, 'a>, + hub: api::Appengine>, + gp: Vec<&'static str>, + gpm: Vec<(&'static str, &'static str)>, +} + + +impl<'n, 'a> Engine<'n, 'a> { + fn _apps_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.apps().get(opt.value_of("apps-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "ensure-resources-exist" => { + call = call.ensure_resources_exist(arg_from_str(value.unwrap_or("false"), err, "ensure-resources-exist", "boolean")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["ensure-resources-exist"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _apps_modules_delete(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.apps().modules_delete(opt.value_of("apps-id").unwrap_or(""), opt.value_of("modules-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _apps_modules_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.apps().modules_get(opt.value_of("apps-id").unwrap_or(""), opt.value_of("modules-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _apps_modules_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.apps().modules_list(opt.value_of("apps-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "page-size" => { + call = call.page_size(arg_from_str(value.unwrap_or("-0"), err, "page-size", "integer")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["page-token", "page-size"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _apps_modules_patch(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "split.shard-by" => Some(("split.shardBy", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "split.allocations" => Some(("split.allocations", JsonTypeInfo { jtype: JsonType::Float, ctype: ComplexType::Map })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["allocations", "id", "name", "shard-by", "split"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::Module = json::value::from_value(object).unwrap(); + let mut call = self.hub.apps().modules_patch(request, opt.value_of("apps-id").unwrap_or(""), opt.value_of("modules-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "migrate-traffic" => { + call = call.migrate_traffic(arg_from_str(value.unwrap_or("false"), err, "migrate-traffic", "boolean")); + }, + "mask" => { + call = call.mask(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["mask", "migrate-traffic"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _apps_modules_versions_create(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "basic-scaling.idle-timeout" => Some(("basicScaling.idleTimeout", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "basic-scaling.max-instances" => Some(("basicScaling.maxInstances", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "beta-settings" => Some(("betaSettings", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Map })), + "vm" => Some(("vm", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "instance-class" => Some(("instanceClass", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "api-config.url" => Some(("apiConfig.url", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "api-config.security-level" => Some(("apiConfig.securityLevel", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "api-config.auth-fail-action" => Some(("apiConfig.authFailAction", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "api-config.login" => Some(("apiConfig.login", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "api-config.script" => Some(("apiConfig.script", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "threadsafe" => Some(("threadsafe", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "health-check.restart-threshold" => Some(("healthCheck.restartThreshold", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "health-check.check-interval" => Some(("healthCheck.checkInterval", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "health-check.unhealthy-threshold" => Some(("healthCheck.unhealthyThreshold", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "health-check.healthy-threshold" => Some(("healthCheck.healthyThreshold", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "health-check.host" => Some(("healthCheck.host", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "health-check.timeout" => Some(("healthCheck.timeout", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "health-check.disable-health-check" => Some(("healthCheck.disableHealthCheck", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "default-expiration" => Some(("defaultExpiration", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "deployer" => Some(("deployer", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "env" => Some(("env", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "automatic-scaling.min-pending-latency" => Some(("automaticScaling.minPendingLatency", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "automatic-scaling.max-pending-latency" => Some(("automaticScaling.maxPendingLatency", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "automatic-scaling.max-idle-instances" => Some(("automaticScaling.maxIdleInstances", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "automatic-scaling.min-idle-instances" => Some(("automaticScaling.minIdleInstances", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "automatic-scaling.cool-down-period" => Some(("automaticScaling.coolDownPeriod", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "automatic-scaling.max-total-instances" => Some(("automaticScaling.maxTotalInstances", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "automatic-scaling.max-concurrent-requests" => Some(("automaticScaling.maxConcurrentRequests", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "automatic-scaling.min-total-instances" => Some(("automaticScaling.minTotalInstances", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "automatic-scaling.cpu-utilization.target-utilization" => Some(("automaticScaling.cpuUtilization.targetUtilization", JsonTypeInfo { jtype: JsonType::Float, ctype: ComplexType::Pod })), + "automatic-scaling.cpu-utilization.aggregation-window-length" => Some(("automaticScaling.cpuUtilization.aggregationWindowLength", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "env-variables" => Some(("envVariables", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Map })), + "resources.disk-gb" => Some(("resources.diskGb", JsonTypeInfo { jtype: JsonType::Float, ctype: ComplexType::Pod })), + "resources.cpu" => Some(("resources.cpu", JsonTypeInfo { jtype: JsonType::Float, ctype: ComplexType::Pod })), + "resources.memory-gb" => Some(("resources.memoryGb", JsonTypeInfo { jtype: JsonType::Float, ctype: ComplexType::Pod })), + "manual-scaling.instances" => Some(("manualScaling.instances", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "inbound-services" => Some(("inboundServices", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "deployment.container.image" => Some(("deployment.container.image", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "network.instance-tag" => Some(("network.instanceTag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "network.forwarded-ports" => Some(("network.forwardedPorts", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "network.name" => Some(("network.name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "nobuild-files-regex" => Some(("nobuildFilesRegex", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "creation-time" => Some(("creationTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "serving-status" => Some(("servingStatus", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "runtime" => Some(("runtime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["aggregation-window-length", "api-config", "auth-fail-action", "automatic-scaling", "basic-scaling", "beta-settings", "check-interval", "container", "cool-down-period", "cpu", "cpu-utilization", "creation-time", "default-expiration", "deployer", "deployment", "disable-health-check", "disk-gb", "env", "env-variables", "forwarded-ports", "health-check", "healthy-threshold", "host", "id", "idle-timeout", "image", "inbound-services", "instance-class", "instance-tag", "instances", "login", "manual-scaling", "max-concurrent-requests", "max-idle-instances", "max-instances", "max-pending-latency", "max-total-instances", "memory-gb", "min-idle-instances", "min-pending-latency", "min-total-instances", "name", "network", "nobuild-files-regex", "resources", "restart-threshold", "runtime", "script", "security-level", "serving-status", "target-utilization", "threadsafe", "timeout", "unhealthy-threshold", "url", "vm"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::Version = json::value::from_value(object).unwrap(); + let mut call = self.hub.apps().modules_versions_create(request, opt.value_of("apps-id").unwrap_or(""), opt.value_of("modules-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _apps_modules_versions_delete(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.apps().modules_versions_delete(opt.value_of("apps-id").unwrap_or(""), opt.value_of("modules-id").unwrap_or(""), opt.value_of("versions-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _apps_modules_versions_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.apps().modules_versions_get(opt.value_of("apps-id").unwrap_or(""), opt.value_of("modules-id").unwrap_or(""), opt.value_of("versions-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "view" => { + call = call.view(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["view"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _apps_modules_versions_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.apps().modules_versions_list(opt.value_of("apps-id").unwrap_or(""), opt.value_of("modules-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "view" => { + call = call.view(value.unwrap_or("")); + }, + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "page-size" => { + call = call.page_size(arg_from_str(value.unwrap_or("-0"), err, "page-size", "integer")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["page-token", "page-size", "view"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _apps_operations_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.apps().operations_get(opt.value_of("apps-id").unwrap_or(""), opt.value_of("operations-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _apps_operations_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.apps().operations_list(opt.value_of("apps-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "page-size" => { + call = call.page_size(arg_from_str(value.unwrap_or("-0"), err, "page-size", "integer")); + }, + "filter" => { + call = call.filter(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["filter", "page-token", "page-size"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _doit(&self, dry_run: bool) -> Result, Option> { + let mut err = InvalidOptionsError::new(); + let mut call_result: Result<(), DoitError> = Ok(()); + let mut err_opt: Option = None; + match self.opt.subcommand() { + ("apps", Some(opt)) => { + match opt.subcommand() { + ("get", Some(opt)) => { + call_result = self._apps_get(opt, dry_run, &mut err); + }, + ("modules-delete", Some(opt)) => { + call_result = self._apps_modules_delete(opt, dry_run, &mut err); + }, + ("modules-get", Some(opt)) => { + call_result = self._apps_modules_get(opt, dry_run, &mut err); + }, + ("modules-list", Some(opt)) => { + call_result = self._apps_modules_list(opt, dry_run, &mut err); + }, + ("modules-patch", Some(opt)) => { + call_result = self._apps_modules_patch(opt, dry_run, &mut err); + }, + ("modules-versions-create", Some(opt)) => { + call_result = self._apps_modules_versions_create(opt, dry_run, &mut err); + }, + ("modules-versions-delete", Some(opt)) => { + call_result = self._apps_modules_versions_delete(opt, dry_run, &mut err); + }, + ("modules-versions-get", Some(opt)) => { + call_result = self._apps_modules_versions_get(opt, dry_run, &mut err); + }, + ("modules-versions-list", Some(opt)) => { + call_result = self._apps_modules_versions_list(opt, dry_run, &mut err); + }, + ("operations-get", Some(opt)) => { + call_result = self._apps_operations_get(opt, dry_run, &mut err); + }, + ("operations-list", Some(opt)) => { + call_result = self._apps_operations_list(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("apps".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + _ => { + err.issues.push(CLIError::MissingCommandError); + writeln!(io::stderr(), "{}\n", self.opt.usage()).ok(); + } + } + + if dry_run { + if err.issues.len() > 0 { + err_opt = Some(err); + } + Err(err_opt) + } else { + Ok(call_result) + } + } + + // Please note that this call will fail if any part of the opt can't be handled + fn new(opt: ArgMatches<'a, 'n>) -> Result, InvalidOptionsError> { + let (config_dir, secret) = { + let config_dir = match cmn::assure_config_dir_exists(opt.value_of("folder").unwrap_or("~/.google-service-cli")) { + Err(e) => return Err(InvalidOptionsError::single(e, 3)), + Ok(p) => p, + }; + + match cmn::application_secret_from_directory(&config_dir, "appengine1-beta4-secret.json", + "{\"installed\":{\"auth_uri\":\"https://accounts.google.com/o/oauth2/auth\",\"client_secret\":\"hCsslbCUyfehWMmbkG8vTYxG\",\"token_uri\":\"https://accounts.google.com/o/oauth2/token\",\"client_email\":\"\",\"redirect_uris\":[\"urn:ietf:wg:oauth:2.0:oob\",\"oob\"],\"client_x509_cert_url\":\"\",\"client_id\":\"620010449518-9ngf7o4dhs0dka470npqvor6dc5lqb9b.apps.googleusercontent.com\",\"auth_provider_x509_cert_url\":\"https://www.googleapis.com/oauth2/v1/certs\"}}") { + Ok(secret) => (config_dir, secret), + Err(e) => return Err(InvalidOptionsError::single(e, 4)) + } + }; + + let auth = Authenticator::new( &secret, DefaultAuthenticatorDelegate, + if opt.is_present("debug-auth") { + hyper::Client::with_connector(mock::TeeConnector { + connector: hyper::net::HttpsConnector::::default() + }) + } else { + hyper::Client::new() + }, + JsonTokenStorage { + program_name: "appengine1-beta4", + db_dir: config_dir.clone(), + }, None); + + let client = + if opt.is_present("debug") { + hyper::Client::with_connector(mock::TeeConnector { + connector: hyper::net::HttpsConnector::::default() + }) + } else { + hyper::Client::new() + }; + let engine = Engine { + opt: opt, + hub: api::Appengine::new(client, auth), + gp: vec!["$-xgafv", "access-token", "alt", "bearer-token", "callback", "fields", "key", "oauth-token", "pp", "pretty-print", "quota-user", "upload-type", "upload-protocol"], + gpm: vec![ + ("$-xgafv", "$.xgafv"), + ("access-token", "access_token"), + ("bearer-token", "bearer_token"), + ("oauth-token", "oauth_token"), + ("pretty-print", "prettyPrint"), + ("quota-user", "quotaUser"), + ("upload-type", "uploadType"), + ("upload-protocol", "upload_protocol"), + ] + }; + + match engine._doit(true) { + Err(Some(err)) => Err(err), + Err(None) => Ok(engine), + Ok(_) => unreachable!(), + } + } + + fn doit(&self) -> Result<(), DoitError> { + match self._doit(false) { + Ok(res) => res, + Err(_) => unreachable!(), + } + } +} + +fn main() { + let mut exit_status = 0i32; + let arg_data = [ + ("apps", "methods: 'get', 'modules-delete', 'modules-get', 'modules-list', 'modules-patch', 'modules-versions-create', 'modules-versions-delete', 'modules-versions-get', 'modules-versions-list', 'operations-get' and 'operations-list'", vec![ + ("get", + Some(r##"Gets information about an application."##), + "Details at http://byron.github.io/google-apis-rs/google_appengine1_beta4_cli/apps_get", + vec![ + (Some(r##"apps-id"##), + None, + Some(r##"Part of `name`. Name of the application to get. For example: "apps/myapp"."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("modules-delete", + Some(r##"Deletes a module and all enclosed versions."##), + "Details at http://byron.github.io/google-apis-rs/google_appengine1_beta4_cli/apps_modules-delete", + vec![ + (Some(r##"apps-id"##), + None, + Some(r##"Part of `name`. Name of the resource requested. For example: "apps/myapp/modules/default"."##), + Some(true), + Some(false)), + + (Some(r##"modules-id"##), + None, + Some(r##"Part of `name`. See documentation of `appsId`."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("modules-get", + Some(r##"Gets the current configuration of the module."##), + "Details at http://byron.github.io/google-apis-rs/google_appengine1_beta4_cli/apps_modules-get", + vec![ + (Some(r##"apps-id"##), + None, + Some(r##"Part of `name`. Name of the resource requested. For example: "apps/myapp/modules/default"."##), + Some(true), + Some(false)), + + (Some(r##"modules-id"##), + None, + Some(r##"Part of `name`. See documentation of `appsId`."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("modules-list", + Some(r##"Lists all the modules in the application."##), + "Details at http://byron.github.io/google-apis-rs/google_appengine1_beta4_cli/apps_modules-list", + vec![ + (Some(r##"apps-id"##), + None, + Some(r##"Part of `name`. Name of the resource requested. For example: "apps/myapp"."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("modules-patch", + Some(r##"Updates the configuration of the specified module."##), + "Details at http://byron.github.io/google-apis-rs/google_appengine1_beta4_cli/apps_modules-patch", + vec![ + (Some(r##"apps-id"##), + None, + Some(r##"Part of `name`. Name of the resource to update. For example: "apps/myapp/modules/default"."##), + Some(true), + Some(false)), + + (Some(r##"modules-id"##), + None, + Some(r##"Part of `name`. See documentation of `appsId`."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("modules-versions-create", + Some(r##"Deploys new code and resource files to a version."##), + "Details at http://byron.github.io/google-apis-rs/google_appengine1_beta4_cli/apps_modules-versions-create", + vec![ + (Some(r##"apps-id"##), + None, + Some(r##"Part of `name`. Name of the resource to update. For example: "apps/myapp/modules/default"."##), + Some(true), + Some(false)), + + (Some(r##"modules-id"##), + None, + Some(r##"Part of `name`. See documentation of `appsId`."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("modules-versions-delete", + Some(r##"Deletes an existing version."##), + "Details at http://byron.github.io/google-apis-rs/google_appengine1_beta4_cli/apps_modules-versions-delete", + vec![ + (Some(r##"apps-id"##), + None, + Some(r##"Part of `name`. Name of the resource requested. For example: "apps/myapp/modules/default/versions/v1"."##), + Some(true), + Some(false)), + + (Some(r##"modules-id"##), + None, + Some(r##"Part of `name`. See documentation of `appsId`."##), + Some(true), + Some(false)), + + (Some(r##"versions-id"##), + None, + Some(r##"Part of `name`. See documentation of `appsId`."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("modules-versions-get", + Some(r##"Gets application deployment information."##), + "Details at http://byron.github.io/google-apis-rs/google_appengine1_beta4_cli/apps_modules-versions-get", + vec![ + (Some(r##"apps-id"##), + None, + Some(r##"Part of `name`. Name of the resource requested. For example: "apps/myapp/modules/default/versions/v1"."##), + Some(true), + Some(false)), + + (Some(r##"modules-id"##), + None, + Some(r##"Part of `name`. See documentation of `appsId`."##), + Some(true), + Some(false)), + + (Some(r##"versions-id"##), + None, + Some(r##"Part of `name`. See documentation of `appsId`."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("modules-versions-list", + Some(r##"Lists the versions of a module."##), + "Details at http://byron.github.io/google-apis-rs/google_appengine1_beta4_cli/apps_modules-versions-list", + vec![ + (Some(r##"apps-id"##), + None, + Some(r##"Part of `name`. Name of the resource requested. For example: "apps/myapp/modules/default"."##), + Some(true), + Some(false)), + + (Some(r##"modules-id"##), + None, + Some(r##"Part of `name`. See documentation of `appsId`."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("operations-get", + Some(r##"Gets the latest state of a long-running operation. Clients can use this method to poll the operation result at intervals as recommended by the API service."##), + "Details at http://byron.github.io/google-apis-rs/google_appengine1_beta4_cli/apps_operations-get", + vec![ + (Some(r##"apps-id"##), + None, + Some(r##"Part of `name`. The name of the operation resource."##), + Some(true), + Some(false)), + + (Some(r##"operations-id"##), + None, + Some(r##"Part of `name`. See documentation of `appsId`."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("operations-list", + Some(r##"Lists operations that match the specified filter in the request. If the server doesn't support this method, it returns `UNIMPLEMENTED`. NOTE: the `name` binding below allows API services to override the binding to use different resource name schemes, such as `users/*/operations`."##), + "Details at http://byron.github.io/google-apis-rs/google_appengine1_beta4_cli/apps_operations-list", + vec![ + (Some(r##"apps-id"##), + None, + Some(r##"Part of `name`. The name of the operation collection."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ]; + + let mut app = App::new("appengine1-beta4") + .author("Sebastian Thiel ") + .version("0.3.2+20150831") + .about("The Google App Engine Admin API enables developers to provision and manage their App Engine applications.") + .after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_appengine1_beta4_cli") + .arg(Arg::with_name("url") + .long("scope") + .help("Specify the authentication a method should be executed in. Each scope requires the user to grant this application permission to use it.If unset, it defaults to the shortest scope url for a particular method.") + .multiple(true) + .takes_value(true)) + .arg(Arg::with_name("folder") + .long("config-dir") + .help("A directory into which we will store our persistent data. Defaults to a user-writable directory that we will create during the first invocation.[default: ~/.google-service-cli") + .multiple(false) + .takes_value(true)) + .arg(Arg::with_name("debug") + .long("debug") + .help("Output all server communication to standard error. `tx` and `rx` are placed into the same stream.") + .multiple(false) + .takes_value(false)) + .arg(Arg::with_name("debug-auth") + .long("debug-auth") + .help("Output all communication related to authentication to standard error. `tx` and `rx` are placed into the same stream.") + .multiple(false) + .takes_value(false)); + + for &(main_command_name, ref about, ref subcommands) in arg_data.iter() { + let mut mcmd = SubCommand::with_name(main_command_name).about(about); + + for &(sub_command_name, ref desc, url_info, ref args) in subcommands { + let mut scmd = SubCommand::with_name(sub_command_name); + if let &Some(desc) = desc { + scmd = scmd.about(desc); + } + scmd = scmd.after_help(url_info); + + for &(ref arg_name, ref flag, ref desc, ref required, ref multi) in args { + let arg_name_str = + match (arg_name, flag) { + (&Some(an), _ ) => an, + (_ , &Some(f)) => f, + _ => unreachable!(), + }; + let mut arg = Arg::with_name(arg_name_str) + .empty_values(false); + if let &Some(short_flag) = flag { + arg = arg.short(short_flag); + } + if let &Some(desc) = desc { + arg = arg.help(desc); + } + if arg_name.is_some() && flag.is_some() { + arg = arg.takes_value(true); + } + if let &Some(required) = required { + arg = arg.required(required); + } + if let &Some(multi) = multi { + arg = arg.multiple(multi); + } + scmd = scmd.arg(arg); + } + mcmd = mcmd.subcommand(scmd); + } + app = app.subcommand(mcmd); + } + + let matches = app.get_matches(); + + let debug = matches.is_present("debug"); + match Engine::new(matches) { + Err(err) => { + exit_status = err.exit_code; + writeln!(io::stderr(), "{}", err).ok(); + }, + Ok(engine) => { + if let Err(doit_err) = engine.doit() { + exit_status = 1; + match doit_err { + DoitError::IoError(path, err) => { + writeln!(io::stderr(), "Failed to open output file '{}': {}", path, err).ok(); + }, + DoitError::ApiError(err) => { + if debug { + writeln!(io::stderr(), "{:#?}", err).ok(); + } else { + writeln!(io::stderr(), "{}", err).ok(); + } + } + } + } + } + } + + std::process::exit(exit_status); +} \ No newline at end of file diff --git a/gen/appengine1_beta4/Cargo.toml b/gen/appengine1_beta4/Cargo.toml new file mode 100644 index 0000000000..988c3b8d29 --- /dev/null +++ b/gen/appengine1_beta4/Cargo.toml @@ -0,0 +1,29 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-appengine1_beta4" +version = "0.1.9+20150831" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with appengine (protocol v1beta4)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/appengine1_beta4" +homepage = "https://developers.google.com/appengine/" +documentation = "http://byron.github.io/google-apis-rs/google_appengine1_beta4" +license = "MIT" +keywords = ["appengine", "google", "protocol", "web", "api"] +build = "src/build.rs" + + +[dependencies] +hyper = ">= 0.6.8" +mime = "0.1.0" +serde = ">= 0.6.0" +serde_json = ">= 0.6.0" +yup-oauth2 = "*" +url = "*" + +[build-dependencies] +syntex = { version = "*" } +serde_codegen = { version = "*" } + diff --git a/gen/appengine1_beta4/LICENSE.md b/gen/appengine1_beta4/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/appengine1_beta4/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/appengine1_beta4/README.md b/gen/appengine1_beta4/README.md new file mode 100644 index 0000000000..e36f150e56 --- /dev/null +++ b/gen/appengine1_beta4/README.md @@ -0,0 +1,185 @@ + +The `google-appengine1_beta4` library allows access to all features of the *Google appengine* service. + +This documentation was generated from *appengine* crate version *0.1.9+20150831*, where *20150831* is the exact revision of the *appengine:v1beta4* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. + +Everything else about the *appengine* *v1_beta4* API can be found at the +[official documentation site](https://developers.google.com/appengine/). +# Features + +Handle the following *Resources* with ease from the central [hub](http://byron.github.io/google-apis-rs/google_appengine1_beta4/struct.Appengine.html) ... + +* apps + * [*get*](http://byron.github.io/google-apis-rs/google_appengine1_beta4/struct.AppGetCall.html), [*modules delete*](http://byron.github.io/google-apis-rs/google_appengine1_beta4/struct.AppModuleDeleteCall.html), [*modules get*](http://byron.github.io/google-apis-rs/google_appengine1_beta4/struct.AppModuleGetCall.html), [*modules list*](http://byron.github.io/google-apis-rs/google_appengine1_beta4/struct.AppModuleListCall.html), [*modules patch*](http://byron.github.io/google-apis-rs/google_appengine1_beta4/struct.AppModulePatchCall.html), [*modules versions create*](http://byron.github.io/google-apis-rs/google_appengine1_beta4/struct.AppModuleVersionCreateCall.html), [*modules versions delete*](http://byron.github.io/google-apis-rs/google_appengine1_beta4/struct.AppModuleVersionDeleteCall.html), [*modules versions get*](http://byron.github.io/google-apis-rs/google_appengine1_beta4/struct.AppModuleVersionGetCall.html), [*modules versions list*](http://byron.github.io/google-apis-rs/google_appengine1_beta4/struct.AppModuleVersionListCall.html), [*operations get*](http://byron.github.io/google-apis-rs/google_appengine1_beta4/struct.AppOperationGetCall.html) and [*operations list*](http://byron.github.io/google-apis-rs/google_appengine1_beta4/struct.AppOperationListCall.html) + + + + +# Structure of this Library + +The API is structured into the following primary items: + +* **[Hub](http://byron.github.io/google-apis-rs/google_appengine1_beta4/struct.Appengine.html)** + * a central object to maintain state and allow accessing all *Activities* + * creates [*Method Builders*](http://byron.github.io/google-apis-rs/google_appengine1_beta4/trait.MethodsBuilder.html) which in turn + allow access to individual [*Call Builders*](http://byron.github.io/google-apis-rs/google_appengine1_beta4/trait.CallBuilder.html) +* **[Resources](http://byron.github.io/google-apis-rs/google_appengine1_beta4/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_appengine1_beta4/trait.Part.html)** + * a collection of properties + * never directly used in *Activities* +* **[Activities](http://byron.github.io/google-apis-rs/google_appengine1_beta4/trait.CallBuilder.html)** + * operations to apply to *Resources* + +All *structures* are marked with applicable traits to further categorize them and ease browsing. + +Generally speaking, you can invoke *Activities* like this: + +```Rust,ignore +let r = hub.resource().activity(...).doit() +``` + +Or specifically ... + +```ignore +let r = hub.apps().modules_versions_delete(...).doit() +let r = hub.apps().modules_versions_create(...).doit() +let r = hub.apps().operations_get(...).doit() +let r = hub.apps().modules_delete(...).doit() +let r = hub.apps().modules_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-appengine1_beta4 = "*" +``` + +## A complete example + +```Rust +extern crate hyper; +extern crate yup_oauth2 as oauth2; +extern crate google_appengine1_beta4 as appengine1_beta4; +use appengine1_beta4::Module; +use appengine1_beta4::{Result, Error}; +use std::default::Default; +use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +use appengine1_beta4::Appengine; + +// 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 = Appengine::new(hyper::Client::new(), auth); +// As the method needs a request, you would usually fill it with the desired information +// into the respective structure. Some of the parts shown here might not be applicable ! +// Values shown here are possibly random and not representative ! +let mut req = Module::default(); + +// You can configure optional parameters by calling 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().modules_patch(req, "appsId", "modulesId") + .migrate_traffic(false) + .mask("sed") + .doit(); + +match result { + Err(e) => match e { + // The Error enum provides details about what exactly happened. + // You can also just use its `Debug`, `Display` or `Error` traits + Error::HttpError(_) + |Error::MissingAPIKey + |Error::MissingToken(_) + |Error::Cancelled + |Error::UploadSizeLimitExceeded(_, _) + |Error::Failure(_) + |Error::BadRequest(_) + |Error::FieldClash(_) + |Error::JsonDecodeError(_, _) => println!("{}", e), + }, + Ok(res) => println!("Success: {:?}", res), +} + +``` +## Handling Errors + +All errors produced by the system are provided either as [Result](http://byron.github.io/google-apis-rs/google_appengine1_beta4/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_appengine1_beta4/trait.Delegate.html), or the [Authenticator Delegate](http://byron.github.io/google-apis-rs/google_appengine1_beta4/../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 Downloads +If a method supports downloads, the response body, which is part of the [Result](http://byron.github.io/google-apis-rs/google_appengine1_beta4/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_appengine1_beta4/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_appengine1_beta4/trait.Delegate.html) to the +[Method Builder](http://byron.github.io/google-apis-rs/google_appengine1_beta4/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_appengine1_beta4/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_appengine1_beta4/trait.RequestValue.html) and +[decodable](http://byron.github.io/google-apis-rs/google_appengine1_beta4/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_appengine1_beta4/trait.Part.html) which are identifiable 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_appengine1_beta4/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_appengine1_beta4/trait.RequestValue.html) are moved + +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 **appengine1_beta4** 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/appengine1_beta4/src/build.rs b/gen/appengine1_beta4/src/build.rs new file mode 100644 index 0000000000..ad4b330068 --- /dev/null +++ b/gen/appengine1_beta4/src/build.rs @@ -0,0 +1,16 @@ +extern crate syntex; +extern crate serde_codegen; + +use std::env; +use std::path::Path; + +pub fn main() { + let out_dir = env::var_os("OUT_DIR").unwrap(); + + let src = Path::new("src/lib.rs.in"); + let dst = Path::new(&out_dir).join("lib.rs"); + + let mut registry = syntex::Registry::new(); + serde_codegen::register(&mut registry); + registry.expand("google-appengine1_beta4", &src, &dst).unwrap(); +} diff --git a/gen/appengine1_beta4/src/cmn.rs b/gen/appengine1_beta4/src/cmn.rs new file mode 100644 index 0000000000..0e31353ba3 --- /dev/null +++ b/gen/appengine1_beta4/src/cmn.rs @@ -0,0 +1,762 @@ +// COPY OF 'src/rust/api/cmn.rs' +// DO NOT EDIT +use std::io::{self, Read, Seek, Cursor, Write, SeekFrom}; +use std; +use std::fmt::{self, Display}; +use std::str::FromStr; +use std::error; +use std::thread::sleep_ms; + +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::h1::LINE_ENDING; +use hyper::method::Method; +use hyper::status::StatusCode; + +use serde_json as json; + +/// 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 {} + +/// Identifies types for building methods of a particular resource type +pub trait MethodsBuilder {} + +/// Identifies types which represent builders for a particular resource method +pub trait CallBuilder {} + +/// Identifies types which can be inserted and deleted. +/// Types with this trait are most commonly used by clients of this API. +pub trait Resource {} + +/// Identifies types which are used in API responses. +pub trait ResponseResult {} + +/// Identifies types which are used in API requests. +pub trait RequestValue {} + +/// Identifies types which are not actually used by the API +/// This might be a bug within the google API schema. +pub trait UnusedType {} + +/// Identifies types which are only used as part of other types, which +/// usually are carrying the `Resource` trait. +pub trait Part {} + +/// 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 {} + +/// 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 +} + +/// A utility to represent detailed errors we might see in case there are BadRequests. +/// The latter happen if the sent parameters or request structures are unsound +#[derive(Deserialize, Serialize, Debug)] +pub struct ErrorResponse { + error: ServerError, +} + +#[derive(Deserialize, Serialize, Debug)] +pub struct ServerError { + errors: Vec, + code: u16, + message: String, +} + +#[derive(Deserialize, Serialize, Debug)] +pub struct ServerMessage { + domain: String, + reason: String, + message: String, + #[serde(rename="locationType")] + location_type: Option, + location: 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 successful. That way, the delegate 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. + /// + /// If you choose to retry after a duration, the duration should be chosen using the + /// [exponential backoff algorithm](http://en.wikipedia.org/wiki/Exponential_backoff). + /// + /// Return retry information. + fn http_error(&mut self, &hyper::Error) -> 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 it as a general information about the + /// impending failure. + /// The given Error provides information about why the token couldn't be acquired in the + /// first place + fn token(&mut self, err: &error::Error) -> Option { + let _ = err; + 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/canceled, 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()`. + /// It will also be called with None after a successful upload, which allows the delegate + /// to forget the URL. That way, we will not attempt to resume an upload that has already + /// finished. + fn store_upload_url(&mut self, url: Option<&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: &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. + /// + /// If you choose to retry after a duration, the duration should be chosen using the + /// [exponential backoff algorithm](http://en.wikipedia.org/wiki/Exponential_backoff). + fn http_failure(&mut self, _: &hyper::client::Response, Option, _: 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 {} + + +#[derive(Debug)] +pub enum Error { + /// The http connection failed + HttpError(hyper::Error), + + /// 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), + + /// Represents information about a request that was not understood by the server. + /// Details are included. + BadRequest(ErrorResponse), + + /// 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(Box), + + /// 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(String, json::Error), + + /// Indicates an HTTP repsonse with a non-success status code + Failure(hyper::client::Response), +} + + +impl Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + Error::HttpError(ref err) => err.fmt(f), + Error::UploadSizeLimitExceeded(ref resource_size, ref max_size) => + writeln!(f, "The media size {} exceeds the maximum allowed upload size of {}" + , resource_size, max_size), + Error::MissingAPIKey => { + (writeln!(f, "The application's API key was not found in the configuration")).ok(); + writeln!(f, "It is used as there are no Scopes defined for this method.") + }, + Error::BadRequest(ref err) => { + try!(writeln!(f, "Bad Requst ({}): {}", err.error.code, err.error.message)); + for err in err.error.errors.iter() { + try!(writeln!(f, " {}: {}, {}{}", + err.domain, + err.message, + err.reason, + match &err.location { + &Some(ref loc) => format!("@{}", loc), + &None => String::new(), + })); + } + Ok(()) + }, + Error::MissingToken(ref err) => + writeln!(f, "Token retrieval failed with error: {}", err), + Error::Cancelled => + writeln!(f, "Operation cancelled by delegate"), + Error::FieldClash(field) => + writeln!(f, "The custom parameter '{}' is already provided natively by the CallBuilder.", field), + Error::JsonDecodeError(ref json_str, ref err) + => writeln!(f, "{}: {}", err, json_str), + Error::Failure(ref response) => + writeln!(f, "Http status indicates failure: {:?}", response), + } + } +} + +impl error::Error for Error { + fn description(&self) -> &str { + match *self { + Error::HttpError(ref err) => err.description(), + Error::JsonDecodeError(_, ref err) => err.description(), + _ => "NO DESCRIPTION POSSIBLE - use `Display.fmt()` instead" + } + } + + fn cause(&self) -> Option<&error::Error> { + match *self { + Error::HttpError(ref err) => err.cause(), + Error::JsonDecodeError(_, ref err) => err.cause(), + _ => None + } + } +} + +/// A universal result type used as return for all calls. +pub type Result = std::result::Result; + +/// 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 + 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 following macro invocation needs to be expanded, as `include!` +// doens't support external macros +// header!{ +// #[doc="The `X-Upload-Content-Type` header."] +// (XUploadContentType, "X-Upload-Content-Type") => [Mime] + +// xupload_content_type { +// test_header!( +// test1, +// vec![b"text/plain"], +// Some(HeaderField( +// vec![Mime(TopLevel::Text, SubLevel::Plain, Vec::new())] +// ))); + +// } +// } + +/// The `X-Upload-Content-Type` header. +/// +/// Generated via rustc --pretty expanded -Z unstable-options, and manually +/// processed to be more readable. +#[derive(PartialEq, Debug, Clone)] +pub struct XUploadContentType(pub Mime); + +impl ::std::ops::Deref for XUploadContentType { + type Target = Mime; + fn deref<'a>(&'a self) -> &'a Mime { &self.0 } +} +impl ::std::ops::DerefMut for XUploadContentType { + fn deref_mut<'a>(&'a mut self) -> &'a mut Mime { &mut self.0 } +} +impl Header for XUploadContentType { + fn header_name() -> &'static str { "X-Upload-Content-Type" } + fn parse_header(raw: &[Vec]) -> hyper::error::Result { + hyper::header::parsing::from_one_raw_str(raw).map(XUploadContentType) + } +} +impl HeaderFormat for XUploadContentType { + fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { + Display::fmt(&**self, f) + } +} +impl Display for XUploadContentType { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Display::fmt(&**self, f) + } +} + +#[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]) -> hyper::error::Result { + Err(hyper::error::Error::Method) + } +} + + +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]) -> hyper::error::Result { + if raw.len() > 0 { + let v = &raw[0]; + if let Ok(s) = std::str::from_utf8(v) { + const PREFIX: &'static str = "bytes "; + if s.starts_with(PREFIX) { + if let Ok(c) = ::from_str(&s[PREFIX.len()..]) { + return Ok(RangeResponseHeader(c)) + } + } + } + } + Err(hyper::error::Error::Method) + } +} + +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, 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, A> ResumableUploadHelper<'a, A> + where A: oauth2::GetToken { + + fn query_transfer_status(&mut self) -> std::result::Result> { + 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, None) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + return Err(Ok(r)) + } + }; + return Ok(h.0.last) + } + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + return Err(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() { + Ok(s) => s, + Err(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 + }; + + self.reader.seek(SeekFrom::Start(start)).unwrap(); + loop { + let request_size = match self.content_length - start { + rs if rs > chunk_size => chunk_size, + rs => rs + }; + + 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 + } + // workaround https://github.com/rust-lang/rust/issues/22252 + let res = 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(); + match res { + 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, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + } + return Some(Ok(res)) + }, + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + return Some(Err(err)) + } + } + } + } +} + +// Copy of src/rust/cli/cmn.rs +// TODO(ST): Allow sharing common code between program types +pub fn remove_json_null_values(value: &mut json::value::Value) { + match *value { + json::value::Value::Object(ref mut map) => { + let mut for_removal = Vec::new(); + + for (key, mut value) in map.iter_mut() { + if value.is_null() { + for_removal.push(key.clone()); + } else { + remove_json_null_values(&mut value); + } + } + + for key in &for_removal { + map.remove(key); + } + } + _ => {} + } +} diff --git a/gen/appengine1_beta4/src/lib.rs b/gen/appengine1_beta4/src/lib.rs new file mode 100644 index 0000000000..9dd8897485 --- /dev/null +++ b/gen/appengine1_beta4/src/lib.rs @@ -0,0 +1,189 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/api/lib.rs.mako' +// DO NOT EDIT ! + +//! This documentation was generated from *appengine* crate version *0.1.9+20150831*, where *20150831* is the exact revision of the *appengine:v1beta4* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +//! +//! Everything else about the *appengine* *v1_beta4* API can be found at the +//! [official documentation site](https://developers.google.com/appengine/). +//! The original source code is [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/appengine1_beta4). +//! # Features +//! +//! Handle the following *Resources* with ease from the central [hub](struct.Appengine.html) ... +//! +//! * apps +//! * [*get*](struct.AppGetCall.html), [*modules delete*](struct.AppModuleDeleteCall.html), [*modules get*](struct.AppModuleGetCall.html), [*modules list*](struct.AppModuleListCall.html), [*modules patch*](struct.AppModulePatchCall.html), [*modules versions create*](struct.AppModuleVersionCreateCall.html), [*modules versions delete*](struct.AppModuleVersionDeleteCall.html), [*modules versions get*](struct.AppModuleVersionGetCall.html), [*modules versions list*](struct.AppModuleVersionListCall.html), [*operations get*](struct.AppOperationGetCall.html) and [*operations list*](struct.AppOperationListCall.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.Appengine.html)** +//! * a central object to maintain state and allow accessing all *Activities* +//! * creates [*Method Builders*](trait.MethodsBuilder.html) which in turn +//! allow access to individual [*Call Builders*](trait.CallBuilder.html) +//! * **[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* +//! +//! All *structures* are marked with applicable traits to further categorize them and ease browsing. +//! +//! Generally speaking, you can invoke *Activities* like this: +//! +//! ```Rust,ignore +//! let r = hub.resource().activity(...).doit() +//! ``` +//! +//! Or specifically ... +//! +//! ```ignore +//! let r = hub.apps().modules_versions_delete(...).doit() +//! let r = hub.apps().modules_versions_create(...).doit() +//! let r = hub.apps().operations_get(...).doit() +//! let r = hub.apps().modules_delete(...).doit() +//! let r = hub.apps().modules_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-appengine1_beta4 = "*" +//! ``` +//! +//! ## A complete example +//! +//! ```test_harness,no_run +//! extern crate hyper; +//! extern crate yup_oauth2 as oauth2; +//! extern crate google_appengine1_beta4 as appengine1_beta4; +//! use appengine1_beta4::Module; +//! use appengine1_beta4::{Result, Error}; +//! # #[test] fn egal() { +//! use std::default::Default; +//! use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +//! use appengine1_beta4::Appengine; +//! +//! // 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 = Appengine::new(hyper::Client::new(), auth); +//! // As the method needs a request, you would usually fill it with the desired information +//! // into the respective structure. Some of the parts shown here might not be applicable ! +//! // Values shown here are possibly random and not representative ! +//! let mut req = Module::default(); +//! +//! // You can configure optional parameters by calling 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().modules_patch(req, "appsId", "modulesId") +//! .migrate_traffic(true) +//! .mask("invidunt") +//! .doit(); +//! +//! match result { +//! Err(e) => match e { +//! // The Error enum provides details about what exactly happened. +//! // You can also just use its `Debug`, `Display` or `Error` traits +//! Error::HttpError(_) +//! |Error::MissingAPIKey +//! |Error::MissingToken(_) +//! |Error::Cancelled +//! |Error::UploadSizeLimitExceeded(_, _) +//! |Error::Failure(_) +//! |Error::BadRequest(_) +//! |Error::FieldClash(_) +//! |Error::JsonDecodeError(_, _) => println!("{}", e), +//! }, +//! Ok(res) => println!("Success: {:?}", res), +//! } +//! # } +//! ``` +//! ## 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 Downloads +//! 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 identifiable 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 moved +//! +//! 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 +//! +//! + +// 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)] + +include!(concat!(env!("OUT_DIR"), "/lib.rs")); \ No newline at end of file diff --git a/gen/appengine1_beta4/src/lib.rs.in b/gen/appengine1_beta4/src/lib.rs.in new file mode 100644 index 0000000000..8c450b654a --- /dev/null +++ b/gen/appengine1_beta4/src/lib.rs.in @@ -0,0 +1,4100 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/api/lib.rs.in.mako' +// DO NOT EDIT ! + +extern crate hyper; +extern crate serde; +extern crate serde_json; +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 serde_json as json; +use std::io; +use std::fs; +use std::thread::sleep_ms; + +pub use cmn::{MultiPartReader, ToParts, MethodInfo, Result, Error, CallBuilder, Hub, ReadSeek, Part, + ResponseResult, RequestValue, NestedType, Delegate, DefaultDelegate, MethodsBuilder, + Resource, ErrorResponse, remove_json_null_values}; + + +// ############## +// 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 AsRef for Scope { + fn as_ref(&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 Appengine related resource activities +/// +/// # Examples +/// +/// Instantiate a new hub +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate yup_oauth2 as oauth2; +/// extern crate google_appengine1_beta4 as appengine1_beta4; +/// use appengine1_beta4::Module; +/// use appengine1_beta4::{Result, Error}; +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use appengine1_beta4::Appengine; +/// +/// // 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 = Appengine::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req = Module::default(); +/// +/// // You can configure optional parameters by calling 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().modules_patch(req, "appsId", "modulesId") +/// .migrate_traffic(false) +/// .mask("accusam") +/// .doit(); +/// +/// match result { +/// Err(e) => match e { +/// // The Error enum provides details about what exactly happened. +/// // You can also just use its `Debug`, `Display` or `Error` traits +/// Error::HttpError(_) +/// |Error::MissingAPIKey +/// |Error::MissingToken(_) +/// |Error::Cancelled +/// |Error::UploadSizeLimitExceeded(_, _) +/// |Error::Failure(_) +/// |Error::BadRequest(_) +/// |Error::FieldClash(_) +/// |Error::JsonDecodeError(_, _) => println!("{}", e), +/// }, +/// Ok(res) => println!("Success: {:?}", res), +/// } +/// # } +/// ``` +pub struct Appengine { + client: RefCell, + auth: RefCell, + _user_agent: String, +} + +impl<'a, C, A> Hub for Appengine {} + +impl<'a, C, A> Appengine + where C: BorrowMut, A: oauth2::GetToken { + + pub fn new(client: C, authenticator: A) -> Appengine { + Appengine { + client: RefCell::new(client), + auth: RefCell::new(authenticator), + _user_agent: "google-api-rust-client/0.1.9".to_string(), + } + } + + pub fn apps(&'a self) -> AppMethods<'a, C, A> { + AppMethods { 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.9`. + /// + /// 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 message for `Modules.ListModules`. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [modules list apps](struct.AppModuleListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ListModulesResponse { + /// Continuation token for fetching the next page of results. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// The modules belonging to the requested application. + pub modules: Option>, +} + +impl ResponseResult for ListModulesResponse {} + + +/// Configure health checking for the VM instances. Unhealthy VM instances will be killed and replaced with new instances. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct HealthCheck { + /// The number of consecutive successful health checks before receiving traffic. + #[serde(rename="healthyThreshold")] + pub healthy_threshold: Option, + /// The number of consecutive failed health checks before an instance is restarted. + #[serde(rename="restartThreshold")] + pub restart_threshold: Option, + /// The amount of time before the health check is considered failed. + pub timeout: Option, + /// The interval between health checks. + #[serde(rename="checkInterval")] + pub check_interval: Option, + /// Whether to explicitly disable health checks for this instance. + #[serde(rename="disableHealthCheck")] + pub disable_health_check: Option, + /// The host header to send when performing an HTTP health check (e.g. myapp.appspot.com) + pub host: Option, + /// The number of consecutive failed health checks before removing traffic. + #[serde(rename="unhealthyThreshold")] + pub unhealthy_threshold: Option, +} + +impl Part for HealthCheck {} + + +/// A custom static error page to be served when an error occurs. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ErrorHandler { + /// The error condition this handler applies to. + #[serde(rename="errorCode")] + pub error_code: Option, + /// MIME type of file. If unspecified, "text/html" is assumed. + #[serde(rename="mimeType")] + pub mime_type: Option, + /// Static file content to be served for this error. + #[serde(rename="staticFile")] + pub static_file: Option, +} + +impl Part for ErrorHandler {} + + +/// Files served directly to the user for a given URL, such as images, CSS stylesheets, or JavaScript source files. Static directory handlers make it easy to serve the entire contents of a directory as static files. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct StaticDirectoryHandler { + /// If specified, all files served by this handler will be served using the specified MIME type. If not specified, the MIME type for a file will be derived from the file's filename extension. + #[serde(rename="mimeType")] + pub mime_type: Option, + /// The length of time a static file served by this handler ought to be cached by web proxies and browsers. + pub expiration: Option, + /// The path to the directory containing the static files, from the application root directory. Everything after the end of the matched url pattern is appended to static_dir to form the full path to the requested file. + pub directory: Option, + /// If true, this UrlMap entry does not match the request unless the file referenced by the handler also exists. If no such file exists, processing will continue with the next UrlMap that matches the requested URL. + #[serde(rename="requireMatchingFile")] + pub require_matching_file: Option, + /// HTTP headers to use for all responses from these URLs. + #[serde(rename="httpHeaders")] + pub http_headers: Option>, + /// By default, files declared in static file handlers are uploaded as static data and are only served to end users, they cannot be read by an application. If this field is set to true, the files are also uploaded as code data so your application can read them. Both uploads are charged against your code and static data storage resource quotas. + #[serde(rename="applicationReadable")] + pub application_readable: Option, +} + +impl Part for StaticDirectoryHandler {} + + +/// An Application contains the top-level configuration of an App Engine 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*). +/// +/// * [get apps](struct.AppGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Application { + /// HTTP path dispatch rules for requests to the app that do not explicitly target a module or version. The rules are order-dependent. + #[serde(rename="dispatchRules")] + pub dispatch_rules: Option>, + /// The location from which the application will be run. Choices are "us-central" for United States and "europe-west" for European Union. Application instances will run out of data centers in the chosen location and all of the application's End User Content will be stored at rest in the chosen location. The default is "us-central". + pub location: Option, + /// The relative name/path of the application. Example: "myapp". @OutputOnly + pub id: Option, + /// The full path to the application in the API. Example: "apps/myapp". @OutputOnly + pub name: Option, + /// A Google Cloud Storage bucket which can be used for storing files associated with an application. This bucket is associated with the application and can be used by the gcloud deployment commands. @OutputOnly + #[serde(rename="codeBucket")] + pub code_bucket: Option, +} + +impl ResponseResult for Application {} + + +/// A Version is a specific set of source code and configuration files deployed to a module. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [modules versions create apps](struct.AppModuleVersionCreateCall.html) (request) +/// * [modules versions get apps](struct.AppModuleVersionGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Version { + /// A module with basic scaling will create an instance when the application receives a request. The instance will be turned down when the app becomes idle. Basic scaling is ideal for work that is intermittent or driven by user activity. + #[serde(rename="basicScaling")] + pub basic_scaling: Option, + /// Beta settings supplied to the application via metadata. + #[serde(rename="betaSettings")] + pub beta_settings: Option>, + /// A module with manual scaling runs continuously, allowing you to perform complex initialization and rely on the state of its memory over time. + #[serde(rename="manualScaling")] + pub manual_scaling: Option, + /// Creation time of this version. This will be between the start and end times of the operation that creates this version. @OutputOnly + #[serde(rename="creationTime")] + pub creation_time: Option, + /// Whether to deploy this app in a VM container (deprecated, use "env":"2"). + pub vm: Option, + /// Before an application can receive email or XMPP messages, the application must be configured to enable the service. + #[serde(rename="inboundServices")] + pub inbound_services: Option>, + /// The frontend instance class to use to run this app. Valid values are `[F1, F2, F4, F4_1G]`. Default: "F1" + #[serde(rename="instanceClass")] + pub instance_class: Option, + /// Code and application artifacts that make up this version. Only returned in `GET` requests if `view=FULL` is set. May only be set on create requests; once created, is immutable. + pub deployment: Option, + /// Custom static error pages instead of these generic error pages, (limit 10 KB/page) Only returned in `GET` requests if `view=FULL` is set. May only be set on create requests; once created, is immutable. + #[serde(rename="errorHandlers")] + pub error_handlers: Option>, + /// The current serving status of this version. Only `SERVING` versions will have instances created or billed for. If this field is unset when a version is created, `SERVING` status will be assumed. It is an error to explicitly set this field to `SERVING_STATUS_UNSPECIFIED`. + #[serde(rename="servingStatus")] + pub serving_status: Option, + /// The relative name/path of the Version within the module. Example: "v1". Version specifiers can contain lowercase letters, digits, and hyphens. It cannot begin with the prefix `ah-` and the names `default` and `latest` are reserved and cannot be used. + pub id: Option, + /// If true, multiple requests can be dispatched to the app at once. + pub threadsafe: Option, + /// Serving configuration for Google Cloud Endpoints. Only returned in `GET` requests if `view=FULL` is set. May only be set on create requests; once created, is immutable. + #[serde(rename="apiConfig")] + pub api_config: Option, + /// Go only. Files that match this pattern will not be built into the app. May only be set on create requests. + #[serde(rename="nobuildFilesRegex")] + pub nobuild_files_regex: Option, + /// Used to specify extra network settings (for VM runtimes only). + pub network: Option, + /// An ordered list of URL Matching patterns that should be applied to incoming requests. The first matching URL consumes the request, and subsequent handlers are not attempted. Only returned in `GET` requests if `view=FULL` is set. May only be set on create requests; once created, is immutable. + pub handlers: Option>, + /// Configure health checking for the VM instances. Unhealthy VM instances will be stopped and replaced with new instances. Only returned in `GET` requests if `view=FULL` is set. May only be set on create requests; once created, is immutable. + #[serde(rename="healthCheck")] + pub health_check: Option, + /// The length of time a static file served by a static file handler ought to be cached by web proxies and browsers, if the handler does not specify its own expiration. Only returned in `GET` requests if `view=FULL` is set. May only be set on create requests; once created, is immutable. + #[serde(rename="defaultExpiration")] + pub default_expiration: Option, + /// The full path to the Version resource in the API. Example: "apps/myapp/modules/default/versions/v1". @OutputOnly + pub name: Option, + /// Configuration for Python runtime third-party libraries required by the application. Only returned in `GET` requests if `view=FULL` is set. May only be set on create requests; once created, is immutable. + pub libraries: Option>, + /// The email address of the user who created this version. @OutputOnly + pub deployer: Option, + /// The App Engine execution environment to use for this version. Default: "1" + pub env: Option, + /// Automatic scaling is the scaling policy that App Engine has used since its inception. It is based on request rate, response latencies, and other application metrics. + #[serde(rename="automaticScaling")] + pub automatic_scaling: Option, + /// The desired runtime. Values can include python27, java7, go, etc. + pub runtime: Option, + /// Environment variables made available to the application. Only returned in `GET` requests if `view=FULL` is set. May only be set on create requests; once created, is immutable. + #[serde(rename="envVariables")] + pub env_variables: Option>, + /// Used to specify how many machine resources an app version needs (for VM runtimes only). + pub resources: Option, +} + +impl RequestValue for Version {} +impl ResponseResult for Version {} + + +/// Response message for `Versions.ListVersions`. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [modules versions list apps](struct.AppModuleVersionListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ListVersionsResponse { + /// Continuation token for fetching the next page of results. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// The versions belonging to the requested application module. + pub versions: Option>, +} + +impl ResponseResult for ListVersionsResponse {} + + +/// Automatic scaling is the scaling policy that App Engine has used since its inception. It is based on request rate, response latencies, and other application metrics. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct AutomaticScaling { + /// Target scaling by CPU usage. + #[serde(rename="cpuUtilization")] + pub cpu_utilization: Option, + /// The maximum amount of time that App Engine should allow a request to wait in the pending queue before starting a new instance to handle it. + #[serde(rename="maxPendingLatency")] + pub max_pending_latency: Option, + /// The maximum number of idle instances that App Engine should maintain for this version. + #[serde(rename="maxIdleInstances")] + pub max_idle_instances: Option, + /// The minimum number of idle instances that App Engine should maintain for this version. Only applies to the default version of a module, since other versions are not expected to receive significant traffic. + #[serde(rename="minIdleInstances")] + pub min_idle_instances: Option, + /// The amount of time that the [Autoscaler](https://cloud.google.com/compute/docs/autoscaler/) should wait between changes to the number of virtual machines. Applies only to the VM runtime. + #[serde(rename="coolDownPeriod")] + pub cool_down_period: Option, + /// Max number of instances that App Engine should start to handle requests. + #[serde(rename="maxTotalInstances")] + pub max_total_instances: Option, + /// The number of concurrent requests an automatic scaling instance can accept before the scheduler spawns a new instance. Default value is chosen based on the runtime. + #[serde(rename="maxConcurrentRequests")] + pub max_concurrent_requests: Option, + /// Minimum number of instances that App Engine should maintain. + #[serde(rename="minTotalInstances")] + pub min_total_instances: Option, + /// The minimum amount of time that App Engine should allow a request to wait in the pending queue before starting a new instance to handle it. + #[serde(rename="minPendingLatency")] + pub min_pending_latency: Option, +} + +impl Part for AutomaticScaling {} + + +/// A URL pattern and description of how it should be handled. App Engine can handle URLs by executing application code, or by serving static files uploaded with the code, such as images, CSS or JavaScript. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct UrlMap { + /// Serves the entire contents of a directory as static files. This attribute is deprecated. You can mimic the behavior of static directories using static files. + #[serde(rename="staticDirectory")] + pub static_directory: Option, + /// Configures whether security (HTTPS) should be enforced for this URL. + #[serde(rename="securityLevel")] + pub security_level: Option, + /// For users not logged in, how to handle access to resources with required login. Defaults to "redirect". + #[serde(rename="authFailAction")] + pub auth_fail_action: Option, + /// A URL prefix. This value uses regular expression syntax (and so regexp special characters must be escaped), but it should not contain groupings. All URLs that begin with this prefix are handled by this handler, using the portion of the URL after the prefix as part of the file path. This is always required. + #[serde(rename="urlRegex")] + pub url_regex: Option, + /// Executes a script to handle the request that matches the URL pattern. + pub script: Option, + /// Returns the contents of a file, such as an image, as the response. + #[serde(rename="staticFiles")] + pub static_files: Option, + /// Use API Endpoints to handle requests. + #[serde(rename="apiEndpoint")] + pub api_endpoint: Option, + /// What level of login is required to access this resource. + pub login: Option, + /// `30x` code to use when performing redirects for the `secure` field. A `302` is used by default. + #[serde(rename="redirectHttpResponseCode")] + pub redirect_http_response_code: Option, +} + +impl Part for UrlMap {} + + +/// A single source file which is part of the application to be deployed. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct FileInfo { + /// The MIME type of the file; if unspecified, the value from Google Cloud Storage will be used. + #[serde(rename="mimeType")] + pub mime_type: Option, + /// The URL source to use to fetch this file. Must be a URL to a resource in Google Cloud Storage. + #[serde(rename="sourceUrl")] + pub source_url: Option, + /// The SHA1 (160 bits) hash of the file in hex. + #[serde(rename="sha1Sum")] + pub sha1_sum: Option, +} + +impl Part for FileInfo {} + + +/// Configuration for traffic splitting for versions within a single module. Traffic splitting allows traffic directed to the module to be assigned to one of several versions in a fractional way, enabling experiments and canarying new builds, for example. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct TrafficSplit { + /// Which mechanism should be used as a selector when choosing a version to send a request to. The traffic selection algorithm will be stable for either type until allocations are changed. + #[serde(rename="shardBy")] + pub shard_by: Option, + /// Mapping from module version IDs within the module to fractional (0.000, 1] allocations of traffic for that version. Each version may only be specified once, but some versions in the module may not have any traffic allocation. Modules that have traffic allocated in this field may not be deleted until the module is deleted, or their traffic allocation is removed. Allocations must sum to 1. Supports precision up to two decimal places for IP-based splits and up to three decimal places for cookie-based splits. + pub allocations: Option>, +} + +impl Part for TrafficSplit {} + + +/// Target scaling by CPU usage. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct CpuUtilization { + /// Target (0-1) CPU utilization ratio to maintain when scaling. + #[serde(rename="targetUtilization")] + pub target_utilization: Option, + /// The period of time over which CPU utilization is calculated. + #[serde(rename="aggregationWindowLength")] + pub aggregation_window_length: Option, +} + +impl Part for CpuUtilization {} + + +/// This resource represents a long-running operation that is the result of a network API call. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [modules versions delete apps](struct.AppModuleVersionDeleteCall.html) (response) +/// * [modules versions create apps](struct.AppModuleVersionCreateCall.html) (response) +/// * [operations get apps](struct.AppOperationGetCall.html) (response) +/// * [modules delete apps](struct.AppModuleDeleteCall.html) (response) +/// * [modules patch apps](struct.AppModulePatchCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Operation { + /// Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. + pub metadata: Option>, + /// If the value is `false`, it means the operation is still in progress. If true, the operation is completed, and either `error` or `response` is available. + pub done: Option, + /// The normal response of the operation in case of success. If the original method returns no data on success, such as `Delete`, the response is `google.protobuf.Empty`. If the original method is standard `Get`/`Create`/`Update`, the response should be the resource. For other methods, the response should have the type `XxxResponse`, where `Xxx` is the original method name. For example, if the original method name is `TakeSnapshot()`, the inferred response type is `TakeSnapshotResponse`. + pub response: Option>, + /// The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping above, the `name` should have the format of `operations/some/unique/name`. + pub name: Option, + /// The error result of the operation in case of failure. + pub error: Option, +} + +impl ResponseResult for Operation {} + + +/// Used to specify how many machine resources an app version needs. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Resources { + /// How much disk size, in GB, an app version needs. + #[serde(rename="diskGb")] + pub disk_gb: Option, + /// How many CPU cores an app version needs. + pub cpu: Option, + /// How much memory, in GB, an app version needs. + #[serde(rename="memoryGb")] + pub memory_gb: Option, +} + +impl Part for Resources {} + + +/// Used to specify extra network settings (for VM runtimes 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 Network { + /// A tag to apply to the VM instance during creation. + #[serde(rename="instanceTag")] + pub instance_tag: Option, + /// A list of ports (or port pairs) to forward from the VM into the app container. + #[serde(rename="forwardedPorts")] + pub forwarded_ports: Option>, + /// The Google Compute Engine network where the VMs will be created. If not specified, or empty, the network named "default" will be used. (The short name should be specified, not the resource path.) + pub name: Option, +} + +impl Part for Network {} + + +/// The `Status` type defines a logical error model that is suitable for different programming environments, including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). The error model is designed to be: - Simple to use and understand for most users - Flexible enough to meet unexpected needs # Overview The `Status` message contains three pieces of data: error code, error message, and error details. The error code should be an enum value of [google.rpc.Code][google.rpc.Code], but it may accept additional error codes if needed. The error message should be a developer-facing English message that helps developers *understand* and *resolve* the error. If a localized user-facing error message is needed, put the localized message in the error details or localize it in the client. The optional error details may contain arbitrary information about the error. There is a predefined set of error detail types in the package `google.rpc` which can be used for common error conditions. # Language mapping The `Status` message is the logical representation of the error model, but it is not necessarily the actual wire format. When the `Status` message is exposed in different client libraries and different wire protocols, it can be mapped differently. For example, it will likely be mapped to some exceptions in Java, but more likely mapped to some error codes in C. # Other uses The error model and the `Status` message can be used in a variety of environments, either with or without APIs, to provide a consistent developer experience across different environments. Example uses of this error model include: - Partial errors. If a service needs to return partial errors to the client, it may embed the `Status` in the normal response to indicate the partial errors. - Workflow errors. A typical workflow has multiple steps. Each step may have a `Status` message for error reporting purpose. - Batch operations. If a client uses batch request and batch response, the `Status` message should be used directly inside batch response, one for each error sub-response. - Asynchronous operations. If an API call embeds asynchronous operation results in its response, the status of those operations should be represented directly using the `Status` message. - Logging. If some API errors are stored in logs, the message `Status` could be used directly after any stripping needed for security/privacy 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 Status { + /// A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the [google.rpc.Status.details][google.rpc.Status.details] field, or localized by the client. + pub message: Option, + /// The status code, which should be an enum value of [google.rpc.Code][google.rpc.Code]. + pub code: Option, + /// A list of messages that carry the error details. There will be a common set of message types for APIs to use. + pub details: Option>>, +} + +impl Part for Status {} + + +/// A module with basic scaling will create an instance when the application receives a request. The instance will be turned down when the app becomes idle. Basic scaling is ideal for work that is intermittent or driven by user 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 BasicScaling { + /// The instance will be shut down this amount of time after receiving its last request. + #[serde(rename="idleTimeout")] + pub idle_timeout: Option, + /// The maximum number of instances for App Engine to create for this version. + #[serde(rename="maxInstances")] + pub max_instances: Option, +} + +impl Part for BasicScaling {} + + +/// The response message for [Operations.ListOperations][google.longrunning.Operations.ListOperations]. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where 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 apps](struct.AppOperationListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ListOperationsResponse { + /// A list of operations that matches the specified filter in the request. + pub operations: Option>, + /// The standard List next-page token. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, +} + +impl ResponseResult for ListOperationsResponse {} + + +/// Files served directly to the user for a given URL, such as images, CSS stylesheets, or JavaScript source files. Static file handlers describe which files in the application directory are static files, and which URLs serve 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 StaticFilesHandler { + /// If specified, all files served by this handler will be served using the specified MIME type. If not specified, the MIME type for a file will be derived from the file's filename extension. + #[serde(rename="mimeType")] + pub mime_type: Option, + /// The length of time a static file served by this handler ought to be cached by web proxies and browsers. + pub expiration: Option, + /// The path to the static files matched by the URL pattern, from the application root directory. The path can refer to text matched in groupings in the URL pattern. + pub path: Option, + /// A regular expression that matches the file paths for all files that will be referenced by this handler. + #[serde(rename="uploadPathRegex")] + pub upload_path_regex: Option, + /// If true, this [UrlMap][google.appengine.v1beta4.UrlMap] entry does not match the request unless the file referenced by the handler also exists. If no such file exists, processing will continue with the next [UrlMap][google.appengine.v1beta4.UrlMap] that matches the requested URL. + #[serde(rename="requireMatchingFile")] + pub require_matching_file: Option, + /// HTTP headers to use for all responses from these URLs. + #[serde(rename="httpHeaders")] + pub http_headers: Option>, + /// By default, files declared in static file handlers are uploaded as static data and are only served to end users, they cannot be read by an application. If this field is set to true, the files are also uploaded as code data so your application can read them. Both uploads are charged against your code and static data storage resource quotas. + #[serde(rename="applicationReadable")] + pub application_readable: Option, +} + +impl Part for StaticFilesHandler {} + + +/// A module with manual scaling runs continuously, allowing you to perform complex initialization and rely on the state of its memory over time. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ManualScaling { + /// The number of instances to assign to the module at the start. This number can later be altered by using the [Modules API](https://cloud.google.com/appengine/docs/python/modules/functions) `set_num_instances()` function. + pub instances: Option, +} + +impl Part for ManualScaling {} + + +/// A Docker (container) image which should be used to start the application. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ContainerInfo { + /// Reference to a hosted container image. Must be a URI to a resource in a Docker repository. Must be fully qualified, including tag or digest. e.g. gcr.io/my-project/image:tag or gcr.io/my-project/image@digest + pub image: Option, +} + +impl Part for ContainerInfo {} + + +/// API Serving configuration for Cloud Endpoints. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ApiConfigHandler { + /// URL to serve the endpoint at. + pub url: Option, + /// Configures whether security (HTTPS) should be enforced for this URL. + #[serde(rename="securityLevel")] + pub security_level: Option, + /// For users not logged in, how to handle access to resources with required login. Defaults to "redirect". + #[serde(rename="authFailAction")] + pub auth_fail_action: Option, + /// What level of login is required to access this resource. Default is "optional". + pub login: Option, + /// Specifies the path to the script from the application root directory. + pub script: Option, +} + +impl Part for ApiConfigHandler {} + + +/// A Python runtime third-party library required by the application. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Library { + /// The version of the library to select, or "latest". + pub version: Option, + /// The name of the library, e.g. "PIL" or "django". + pub name: Option, +} + +impl Part for Library {} + + +/// A reference to a particular snapshot of the source tree used to build and deploy the application. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct SourceReference { + /// The canonical (and persistent) identifier of the deployed revision, i.e. any kind of aliases including tags or branch names are not allowed. Example (git): "2198322f89e0bb2e25021667c2ed489d1fd34e6b" + #[serde(rename="revisionId")] + pub revision_id: Option, + /// Optional. A URI string identifying the repository. Example: "https://source.developers.google.com/p/app-123/r/default" + pub repository: Option, +} + +impl Part for SourceReference {} + + +/// Code and application artifacts used to deploy a version to App Engine. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Deployment { + /// A manifest of files stored in Google Cloud Storage which should be included as part of this application. All files must be readable using the credentials supplied with this call. + pub files: Option>, + /// The origin of the source code for this deployment. There can be more than one source reference per Version if source code is distributed among multiple repositories. + #[serde(rename="sourceReferences")] + pub source_references: Option>, + /// If supplied, a docker (container) image which should be used to start the application. Only applicable to the 'vm' runtime. + pub container: Option, +} + +impl Part for Deployment {} + + +/// A module is a component of an application that provides a single service or configuration. A module has a collection of versions that define a specific set of code used to implement the functionality of that module. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [modules get apps](struct.AppModuleGetCall.html) (response) +/// * [modules patch apps](struct.AppModulePatchCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Module { + /// A mapping that defines fractional HTTP traffic diversion to different versions within the module. + pub split: Option, + /// The relative name/path of the module within the application. Example: "default" @OutputOnly + pub id: Option, + /// The full path to the Module resource in the API. Example: "apps/myapp/modules/default" @OutputOnly + pub name: Option, +} + +impl RequestValue for Module {} +impl ResponseResult for Module {} + + +/// Executes a script to handle the request that matches the URL pattern. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ScriptHandler { + /// Specifies the path to the script from the application root directory. + #[serde(rename="scriptPath")] + pub script_path: Option, +} + +impl Part for ScriptHandler {} + + +/// Rules to match an HTTP request and dispatch that request to a module. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct UrlDispatchRule { + /// The pathname within the host. This must start with a '/'. A single '*' (glob) can be included at the end of the path. The sum of the lengths of the domain and path may not exceed 100 characters. + pub path: Option, + /// The domain name to match on. Supports '*' (glob) wildcarding on the left-hand side of a '.'. If empty, all domains will be matched (the same as '*'). + pub domain: Option, + /// The resource id of a Module in this application that should service the matched request. The Module must already exist. Example: "default". + pub module: Option, +} + +impl Part for UrlDispatchRule {} + + +/// Use Google Cloud Endpoints to handle 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 ApiEndpointHandler { + /// Specifies the path to the script from the application root directory. + #[serde(rename="scriptPath")] + pub script_path: Option, +} + +impl Part for ApiEndpointHandler {} + + + +// ################### +// MethodBuilders ### +// ################# + +/// A builder providing access to all methods supported on *app* resources. +/// It is not used directly, but through the `Appengine` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate yup_oauth2 as oauth2; +/// extern crate google_appengine1_beta4 as appengine1_beta4; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use appengine1_beta4::Appengine; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Appengine::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get(...)`, `modules_delete(...)`, `modules_get(...)`, `modules_list(...)`, `modules_patch(...)`, `modules_versions_create(...)`, `modules_versions_delete(...)`, `modules_versions_get(...)`, `modules_versions_list(...)`, `operations_get(...)` and `operations_list(...)` +/// // to build up your call. +/// let rb = hub.apps(); +/// # } +/// ``` +pub struct AppMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Appengine, +} + +impl<'a, C, A> MethodsBuilder for AppMethods<'a, C, A> {} + +impl<'a, C, A> AppMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Updates the configuration of the specified module. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `appsId` - Part of `name`. Name of the resource to update. For example: "apps/myapp/modules/default". + /// * `modulesId` - Part of `name`. See documentation of `appsId`. + pub fn modules_patch(&self, request: Module, apps_id: &str, modules_id: &str) -> AppModulePatchCall<'a, C, A> { + AppModulePatchCall { + hub: self.hub, + _request: request, + _apps_id: apps_id.to_string(), + _modules_id: modules_id.to_string(), + _migrate_traffic: Default::default(), + _mask: 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 modules in the application. + /// + /// # Arguments + /// + /// * `appsId` - Part of `name`. Name of the resource requested. For example: "apps/myapp". + pub fn modules_list(&self, apps_id: &str) -> AppModuleListCall<'a, C, A> { + AppModuleListCall { + hub: self.hub, + _apps_id: apps_id.to_string(), + _page_token: Default::default(), + _page_size: 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 configuration of the module. + /// + /// # Arguments + /// + /// * `appsId` - Part of `name`. Name of the resource requested. For example: "apps/myapp/modules/default". + /// * `modulesId` - Part of `name`. See documentation of `appsId`. + pub fn modules_get(&self, apps_id: &str, modules_id: &str) -> AppModuleGetCall<'a, C, A> { + AppModuleGetCall { + hub: self.hub, + _apps_id: apps_id.to_string(), + _modules_id: modules_id.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 an application. + /// + /// # Arguments + /// + /// * `appsId` - Part of `name`. Name of the application to get. For example: "apps/myapp". + pub fn get(&self, apps_id: &str) -> AppGetCall<'a, C, A> { + AppGetCall { + hub: self.hub, + _apps_id: apps_id.to_string(), + _ensure_resources_exist: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Deletes a module and all enclosed versions. + /// + /// # Arguments + /// + /// * `appsId` - Part of `name`. Name of the resource requested. For example: "apps/myapp/modules/default". + /// * `modulesId` - Part of `name`. See documentation of `appsId`. + pub fn modules_delete(&self, apps_id: &str, modules_id: &str) -> AppModuleDeleteCall<'a, C, A> { + AppModuleDeleteCall { + hub: self.hub, + _apps_id: apps_id.to_string(), + _modules_id: modules_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 latest state of a long-running operation. Clients can use this method to poll the operation result at intervals as recommended by the API service. + /// + /// # Arguments + /// + /// * `appsId` - Part of `name`. The name of the operation resource. + /// * `operationsId` - Part of `name`. See documentation of `appsId`. + pub fn operations_get(&self, apps_id: &str, operations_id: &str) -> AppOperationGetCall<'a, C, A> { + AppOperationGetCall { + hub: self.hub, + _apps_id: apps_id.to_string(), + _operations_id: operations_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Lists operations that match the specified filter in the request. If the server doesn't support this method, it returns `UNIMPLEMENTED`. NOTE: the `name` binding below allows API services to override the binding to use different resource name schemes, such as `users/*/operations`. + /// + /// # Arguments + /// + /// * `appsId` - Part of `name`. The name of the operation collection. + pub fn operations_list(&self, apps_id: &str) -> AppOperationListCall<'a, C, A> { + AppOperationListCall { + hub: self.hub, + _apps_id: apps_id.to_string(), + _page_token: Default::default(), + _page_size: 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 an existing version. + /// + /// # Arguments + /// + /// * `appsId` - Part of `name`. Name of the resource requested. For example: "apps/myapp/modules/default/versions/v1". + /// * `modulesId` - Part of `name`. See documentation of `appsId`. + /// * `versionsId` - Part of `name`. See documentation of `appsId`. + pub fn modules_versions_delete(&self, apps_id: &str, modules_id: &str, versions_id: &str) -> AppModuleVersionDeleteCall<'a, C, A> { + AppModuleVersionDeleteCall { + hub: self.hub, + _apps_id: apps_id.to_string(), + _modules_id: modules_id.to_string(), + _versions_id: versions_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Deploys new code and resource files to a version. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `appsId` - Part of `name`. Name of the resource to update. For example: "apps/myapp/modules/default". + /// * `modulesId` - Part of `name`. See documentation of `appsId`. + pub fn modules_versions_create(&self, request: Version, apps_id: &str, modules_id: &str) -> AppModuleVersionCreateCall<'a, C, A> { + AppModuleVersionCreateCall { + hub: self.hub, + _request: request, + _apps_id: apps_id.to_string(), + _modules_id: modules_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets application deployment information. + /// + /// # Arguments + /// + /// * `appsId` - Part of `name`. Name of the resource requested. For example: "apps/myapp/modules/default/versions/v1". + /// * `modulesId` - Part of `name`. See documentation of `appsId`. + /// * `versionsId` - Part of `name`. See documentation of `appsId`. + pub fn modules_versions_get(&self, apps_id: &str, modules_id: &str, versions_id: &str) -> AppModuleVersionGetCall<'a, C, A> { + AppModuleVersionGetCall { + hub: self.hub, + _apps_id: apps_id.to_string(), + _modules_id: modules_id.to_string(), + _versions_id: versions_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: + /// + /// Lists the versions of a module. + /// + /// # Arguments + /// + /// * `appsId` - Part of `name`. Name of the resource requested. For example: "apps/myapp/modules/default". + /// * `modulesId` - Part of `name`. See documentation of `appsId`. + pub fn modules_versions_list(&self, apps_id: &str, modules_id: &str) -> AppModuleVersionListCall<'a, C, A> { + AppModuleVersionListCall { + hub: self.hub, + _apps_id: apps_id.to_string(), + _modules_id: modules_id.to_string(), + _view: Default::default(), + _page_token: Default::default(), + _page_size: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + + + +// ################### +// CallBuilders ### +// ################# + +/// Updates the configuration of the specified module. +/// +/// A builder for the *modules.patch* method supported by a *app* resource. +/// It is not used directly, but through a `AppMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_appengine1_beta4 as appengine1_beta4; +/// use appengine1_beta4::Module; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use appengine1_beta4::Appengine; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Appengine::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req = Module::default(); +/// +/// // You can configure optional parameters by calling 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().modules_patch(req, "appsId", "modulesId") +/// .migrate_traffic(true) +/// .mask("erat") +/// .doit(); +/// # } +/// ``` +pub struct AppModulePatchCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Appengine, + _request: Module, + _apps_id: String, + _modules_id: String, + _migrate_traffic: Option, + _mask: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for AppModulePatchCall<'a, C, A> {} + +impl<'a, C, A> AppModulePatchCall<'a, C, A> where 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: "appengine.apps.modules.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + params.push(("appsId", self._apps_id.to_string())); + params.push(("modulesId", self._modules_id.to_string())); + if let Some(value) = self._migrate_traffic { + params.push(("migrateTraffic", value.to_string())); + } + if let Some(value) = self._mask { + params.push(("mask", value.to_string())); + } + for &field in ["alt", "appsId", "modulesId", "migrateTraffic", "mask"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://appengine.googleapis.com/v1beta4/apps/{appsId}/modules/{modulesId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{appsId}", "appsId"), ("{modulesId}", "modulesId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["modulesId", "appsId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: Module) -> AppModulePatchCall<'a, C, A> { + self._request = new_value; + self + } + /// Part of `name`. Name of the resource to update. For example: "apps/myapp/modules/default". + /// + /// Sets the *apps id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn apps_id(mut self, new_value: &str) -> AppModulePatchCall<'a, C, A> { + self._apps_id = new_value.to_string(); + self + } + /// Part of `name`. See documentation of `appsId`. + /// + /// Sets the *modules id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn modules_id(mut self, new_value: &str) -> AppModulePatchCall<'a, C, A> { + self._modules_id = new_value.to_string(); + self + } + /// Whether to use Traffic Migration to shift traffic gradually. Traffic can only be migrated from a single version to another single version. + /// + /// Sets the *migrate traffic* query property to the given value. + pub fn migrate_traffic(mut self, new_value: bool) -> AppModulePatchCall<'a, C, A> { + self._migrate_traffic = Some(new_value); + self + } + /// Standard field mask for the set of fields to be updated. + /// + /// Sets the *mask* query property to the given value. + pub fn mask(mut self, new_value: &str) -> AppModulePatchCall<'a, C, A> { + self._mask = Some(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AppModulePatchCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> AppModulePatchCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AppModulePatchCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Lists all the modules in the application. +/// +/// A builder for the *modules.list* method supported by a *app* resource. +/// It is not used directly, but through a `AppMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_appengine1_beta4 as appengine1_beta4; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use appengine1_beta4::Appengine; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Appengine::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling 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().modules_list("appsId") +/// .page_token("sea") +/// .page_size(-90) +/// .doit(); +/// # } +/// ``` +pub struct AppModuleListCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Appengine, + _apps_id: String, + _page_token: Option, + _page_size: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for AppModuleListCall<'a, C, A> {} + +impl<'a, C, A> AppModuleListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ListModulesResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "appengine.apps.modules.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("appsId", self._apps_id.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())); + } + for &field in ["alt", "appsId", "pageToken", "pageSize"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://appengine.googleapis.com/v1beta4/apps/{appsId}/modules".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{appsId}", "appsId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["appsId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Part of `name`. Name of the resource requested. For example: "apps/myapp". + /// + /// Sets the *apps id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn apps_id(mut self, new_value: &str) -> AppModuleListCall<'a, C, A> { + self._apps_id = new_value.to_string(); + self + } + /// Continuation token for fetching the next page of results. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> AppModuleListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Maximum results to return per page. + /// + /// Sets the *page size* query property to the given value. + pub fn page_size(mut self, new_value: i32) -> AppModuleListCall<'a, C, A> { + self._page_size = Some(new_value); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AppModuleListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> AppModuleListCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AppModuleListCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Gets the current configuration of the module. +/// +/// A builder for the *modules.get* method supported by a *app* resource. +/// It is not used directly, but through a `AppMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_appengine1_beta4 as appengine1_beta4; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use appengine1_beta4::Appengine; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Appengine::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling 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().modules_get("appsId", "modulesId") +/// .doit(); +/// # } +/// ``` +pub struct AppModuleGetCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Appengine, + _apps_id: String, + _modules_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for AppModuleGetCall<'a, C, A> {} + +impl<'a, C, A> AppModuleGetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Module)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "appengine.apps.modules.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("appsId", self._apps_id.to_string())); + params.push(("modulesId", self._modules_id.to_string())); + for &field in ["alt", "appsId", "modulesId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://appengine.googleapis.com/v1beta4/apps/{appsId}/modules/{modulesId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{appsId}", "appsId"), ("{modulesId}", "modulesId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["modulesId", "appsId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Part of `name`. Name of the resource requested. For example: "apps/myapp/modules/default". + /// + /// Sets the *apps id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn apps_id(mut self, new_value: &str) -> AppModuleGetCall<'a, C, A> { + self._apps_id = new_value.to_string(); + self + } + /// Part of `name`. See documentation of `appsId`. + /// + /// Sets the *modules id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn modules_id(mut self, new_value: &str) -> AppModuleGetCall<'a, C, A> { + self._modules_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AppModuleGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> AppModuleGetCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AppModuleGetCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Gets information about an application. +/// +/// A builder for the *get* method supported by a *app* resource. +/// It is not used directly, but through a `AppMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_appengine1_beta4 as appengine1_beta4; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use appengine1_beta4::Appengine; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Appengine::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling 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("appsId") +/// .ensure_resources_exist(true) +/// .doit(); +/// # } +/// ``` +pub struct AppGetCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Appengine, + _apps_id: String, + _ensure_resources_exist: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for AppGetCall<'a, C, A> {} + +impl<'a, C, A> AppGetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Application)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "appengine.apps.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("appsId", self._apps_id.to_string())); + if let Some(value) = self._ensure_resources_exist { + params.push(("ensureResourcesExist", value.to_string())); + } + for &field in ["alt", "appsId", "ensureResourcesExist"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://appengine.googleapis.com/v1beta4/apps/{appsId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{appsId}", "appsId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["appsId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Part of `name`. Name of the application to get. For example: "apps/myapp". + /// + /// Sets the *apps id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn apps_id(mut self, new_value: &str) -> AppGetCall<'a, C, A> { + self._apps_id = new_value.to_string(); + self + } + /// Certain resources associated with an application are created on-demand. Controls whether these resources should be created when performing the `GET` operation. If specified and any resources cloud not be created, the request will fail with an error code. + /// + /// Sets the *ensure resources exist* query property to the given value. + pub fn ensure_resources_exist(mut self, new_value: bool) -> AppGetCall<'a, C, A> { + self._ensure_resources_exist = Some(new_value); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AppGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> AppGetCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Deletes a module and all enclosed versions. +/// +/// A builder for the *modules.delete* method supported by a *app* resource. +/// It is not used directly, but through a `AppMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_appengine1_beta4 as appengine1_beta4; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use appengine1_beta4::Appengine; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Appengine::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling 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().modules_delete("appsId", "modulesId") +/// .doit(); +/// # } +/// ``` +pub struct AppModuleDeleteCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Appengine, + _apps_id: String, + _modules_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for AppModuleDeleteCall<'a, C, A> {} + +impl<'a, C, A> AppModuleDeleteCall<'a, C, A> where 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: "appengine.apps.modules.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("appsId", self._apps_id.to_string())); + params.push(("modulesId", self._modules_id.to_string())); + for &field in ["alt", "appsId", "modulesId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://appengine.googleapis.com/v1beta4/apps/{appsId}/modules/{modulesId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{appsId}", "appsId"), ("{modulesId}", "modulesId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["modulesId", "appsId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Part of `name`. Name of the resource requested. For example: "apps/myapp/modules/default". + /// + /// Sets the *apps id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn apps_id(mut self, new_value: &str) -> AppModuleDeleteCall<'a, C, A> { + self._apps_id = new_value.to_string(); + self + } + /// Part of `name`. See documentation of `appsId`. + /// + /// Sets the *modules id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn modules_id(mut self, new_value: &str) -> AppModuleDeleteCall<'a, C, A> { + self._modules_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AppModuleDeleteCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> AppModuleDeleteCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AppModuleDeleteCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Gets the latest state of a long-running operation. Clients can use this method to poll the operation result at intervals as recommended by the API service. +/// +/// A builder for the *operations.get* method supported by a *app* resource. +/// It is not used directly, but through a `AppMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_appengine1_beta4 as appengine1_beta4; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use appengine1_beta4::Appengine; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Appengine::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling 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().operations_get("appsId", "operationsId") +/// .doit(); +/// # } +/// ``` +pub struct AppOperationGetCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Appengine, + _apps_id: String, + _operations_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for AppOperationGetCall<'a, C, A> {} + +impl<'a, C, A> AppOperationGetCall<'a, C, A> where 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: "appengine.apps.operations.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("appsId", self._apps_id.to_string())); + params.push(("operationsId", self._operations_id.to_string())); + for &field in ["alt", "appsId", "operationsId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://appengine.googleapis.com/v1beta4/apps/{appsId}/operations/{operationsId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{appsId}", "appsId"), ("{operationsId}", "operationsId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["operationsId", "appsId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Part of `name`. The name of the operation resource. + /// + /// Sets the *apps id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn apps_id(mut self, new_value: &str) -> AppOperationGetCall<'a, C, A> { + self._apps_id = new_value.to_string(); + self + } + /// Part of `name`. See documentation of `appsId`. + /// + /// Sets the *operations id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn operations_id(mut self, new_value: &str) -> AppOperationGetCall<'a, C, A> { + self._operations_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AppOperationGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> AppOperationGetCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AppOperationGetCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Lists operations that match the specified filter in the request. If the server doesn't support this method, it returns `UNIMPLEMENTED`. NOTE: the `name` binding below allows API services to override the binding to use different resource name schemes, such as `users/*/operations`. +/// +/// A builder for the *operations.list* method supported by a *app* resource. +/// It is not used directly, but through a `AppMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_appengine1_beta4 as appengine1_beta4; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use appengine1_beta4::Appengine; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Appengine::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling 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().operations_list("appsId") +/// .page_token("et") +/// .page_size(-41) +/// .filter("ipsum") +/// .doit(); +/// # } +/// ``` +pub struct AppOperationListCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Appengine, + _apps_id: String, + _page_token: Option, + _page_size: Option, + _filter: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for AppOperationListCall<'a, C, A> {} + +impl<'a, C, A> AppOperationListCall<'a, C, A> where 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: "appengine.apps.operations.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("appsId", self._apps_id.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._filter { + params.push(("filter", value.to_string())); + } + for &field in ["alt", "appsId", "pageToken", "pageSize", "filter"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://appengine.googleapis.com/v1beta4/apps/{appsId}/operations".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{appsId}", "appsId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["appsId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Part of `name`. The name of the operation collection. + /// + /// Sets the *apps id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn apps_id(mut self, new_value: &str) -> AppOperationListCall<'a, C, A> { + self._apps_id = new_value.to_string(); + self + } + /// The standard list page token. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> AppOperationListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// The standard list page size. + /// + /// Sets the *page size* query property to the given value. + pub fn page_size(mut self, new_value: i32) -> AppOperationListCall<'a, C, A> { + self._page_size = Some(new_value); + self + } + /// The standard list filter. + /// + /// Sets the *filter* query property to the given value. + pub fn filter(mut self, new_value: &str) -> AppOperationListCall<'a, C, A> { + self._filter = Some(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AppOperationListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> AppOperationListCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AppOperationListCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Deletes an existing version. +/// +/// A builder for the *modules.versions.delete* method supported by a *app* resource. +/// It is not used directly, but through a `AppMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_appengine1_beta4 as appengine1_beta4; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use appengine1_beta4::Appengine; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Appengine::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling 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().modules_versions_delete("appsId", "modulesId", "versionsId") +/// .doit(); +/// # } +/// ``` +pub struct AppModuleVersionDeleteCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Appengine, + _apps_id: String, + _modules_id: String, + _versions_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for AppModuleVersionDeleteCall<'a, C, A> {} + +impl<'a, C, A> AppModuleVersionDeleteCall<'a, C, A> where 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: "appengine.apps.modules.versions.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("appsId", self._apps_id.to_string())); + params.push(("modulesId", self._modules_id.to_string())); + params.push(("versionsId", self._versions_id.to_string())); + for &field in ["alt", "appsId", "modulesId", "versionsId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://appengine.googleapis.com/v1beta4/apps/{appsId}/modules/{modulesId}/versions/{versionsId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{appsId}", "appsId"), ("{modulesId}", "modulesId"), ("{versionsId}", "versionsId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + 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 ["versionsId", "modulesId", "appsId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Part of `name`. Name of the resource requested. For example: "apps/myapp/modules/default/versions/v1". + /// + /// Sets the *apps id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn apps_id(mut self, new_value: &str) -> AppModuleVersionDeleteCall<'a, C, A> { + self._apps_id = new_value.to_string(); + self + } + /// Part of `name`. See documentation of `appsId`. + /// + /// Sets the *modules id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn modules_id(mut self, new_value: &str) -> AppModuleVersionDeleteCall<'a, C, A> { + self._modules_id = new_value.to_string(); + self + } + /// Part of `name`. See documentation of `appsId`. + /// + /// Sets the *versions id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn versions_id(mut self, new_value: &str) -> AppModuleVersionDeleteCall<'a, C, A> { + self._versions_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AppModuleVersionDeleteCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> AppModuleVersionDeleteCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AppModuleVersionDeleteCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Deploys new code and resource files to a version. +/// +/// A builder for the *modules.versions.create* method supported by a *app* resource. +/// It is not used directly, but through a `AppMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_appengine1_beta4 as appengine1_beta4; +/// use appengine1_beta4::Version; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use appengine1_beta4::Appengine; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Appengine::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req = Version::default(); +/// +/// // You can configure optional parameters by calling 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().modules_versions_create(req, "appsId", "modulesId") +/// .doit(); +/// # } +/// ``` +pub struct AppModuleVersionCreateCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Appengine, + _request: Version, + _apps_id: String, + _modules_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for AppModuleVersionCreateCall<'a, C, A> {} + +impl<'a, C, A> AppModuleVersionCreateCall<'a, C, A> where 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: "appengine.apps.modules.versions.create", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("appsId", self._apps_id.to_string())); + params.push(("modulesId", self._modules_id.to_string())); + for &field in ["alt", "appsId", "modulesId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://appengine.googleapis.com/v1beta4/apps/{appsId}/modules/{modulesId}/versions".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{appsId}", "appsId"), ("{modulesId}", "modulesId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["modulesId", "appsId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: Version) -> AppModuleVersionCreateCall<'a, C, A> { + self._request = new_value; + self + } + /// Part of `name`. Name of the resource to update. For example: "apps/myapp/modules/default". + /// + /// Sets the *apps id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn apps_id(mut self, new_value: &str) -> AppModuleVersionCreateCall<'a, C, A> { + self._apps_id = new_value.to_string(); + self + } + /// Part of `name`. See documentation of `appsId`. + /// + /// Sets the *modules id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn modules_id(mut self, new_value: &str) -> AppModuleVersionCreateCall<'a, C, A> { + self._modules_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AppModuleVersionCreateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> AppModuleVersionCreateCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AppModuleVersionCreateCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Gets application deployment information. +/// +/// A builder for the *modules.versions.get* method supported by a *app* resource. +/// It is not used directly, but through a `AppMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_appengine1_beta4 as appengine1_beta4; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use appengine1_beta4::Appengine; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Appengine::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling 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().modules_versions_get("appsId", "modulesId", "versionsId") +/// .view("sadipscing") +/// .doit(); +/// # } +/// ``` +pub struct AppModuleVersionGetCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Appengine, + _apps_id: String, + _modules_id: String, + _versions_id: String, + _view: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for AppModuleVersionGetCall<'a, C, A> {} + +impl<'a, C, A> AppModuleVersionGetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Version)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "appengine.apps.modules.versions.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("appsId", self._apps_id.to_string())); + params.push(("modulesId", self._modules_id.to_string())); + params.push(("versionsId", self._versions_id.to_string())); + if let Some(value) = self._view { + params.push(("view", value.to_string())); + } + for &field in ["alt", "appsId", "modulesId", "versionsId", "view"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://appengine.googleapis.com/v1beta4/apps/{appsId}/modules/{modulesId}/versions/{versionsId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{appsId}", "appsId"), ("{modulesId}", "modulesId"), ("{versionsId}", "versionsId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + 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 ["versionsId", "modulesId", "appsId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Part of `name`. Name of the resource requested. For example: "apps/myapp/modules/default/versions/v1". + /// + /// Sets the *apps id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn apps_id(mut self, new_value: &str) -> AppModuleVersionGetCall<'a, C, A> { + self._apps_id = new_value.to_string(); + self + } + /// Part of `name`. See documentation of `appsId`. + /// + /// Sets the *modules id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn modules_id(mut self, new_value: &str) -> AppModuleVersionGetCall<'a, C, A> { + self._modules_id = new_value.to_string(); + self + } + /// Part of `name`. See documentation of `appsId`. + /// + /// Sets the *versions id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn versions_id(mut self, new_value: &str) -> AppModuleVersionGetCall<'a, C, A> { + self._versions_id = new_value.to_string(); + self + } + /// Controls the set of fields returned in the `Get` response. + /// + /// Sets the *view* query property to the given value. + pub fn view(mut self, new_value: &str) -> AppModuleVersionGetCall<'a, C, A> { + self._view = Some(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AppModuleVersionGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> AppModuleVersionGetCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AppModuleVersionGetCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Lists the versions of a module. +/// +/// A builder for the *modules.versions.list* method supported by a *app* resource. +/// It is not used directly, but through a `AppMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_appengine1_beta4 as appengine1_beta4; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use appengine1_beta4::Appengine; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Appengine::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling 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().modules_versions_list("appsId", "modulesId") +/// .view("elitr") +/// .page_token("amet") +/// .page_size(-60) +/// .doit(); +/// # } +/// ``` +pub struct AppModuleVersionListCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Appengine, + _apps_id: String, + _modules_id: String, + _view: Option, + _page_token: Option, + _page_size: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for AppModuleVersionListCall<'a, C, A> {} + +impl<'a, C, A> AppModuleVersionListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ListVersionsResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "appengine.apps.modules.versions.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + params.push(("appsId", self._apps_id.to_string())); + params.push(("modulesId", self._modules_id.to_string())); + if let Some(value) = self._view { + params.push(("view", 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())); + } + for &field in ["alt", "appsId", "modulesId", "view", "pageToken", "pageSize"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://appengine.googleapis.com/v1beta4/apps/{appsId}/modules/{modulesId}/versions".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{appsId}", "appsId"), ("{modulesId}", "modulesId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["modulesId", "appsId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Part of `name`. Name of the resource requested. For example: "apps/myapp/modules/default". + /// + /// Sets the *apps id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn apps_id(mut self, new_value: &str) -> AppModuleVersionListCall<'a, C, A> { + self._apps_id = new_value.to_string(); + self + } + /// Part of `name`. See documentation of `appsId`. + /// + /// Sets the *modules id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn modules_id(mut self, new_value: &str) -> AppModuleVersionListCall<'a, C, A> { + self._modules_id = new_value.to_string(); + self + } + /// Controls the set of fields returned in the `List` response. + /// + /// Sets the *view* query property to the given value. + pub fn view(mut self, new_value: &str) -> AppModuleVersionListCall<'a, C, A> { + self._view = Some(new_value.to_string()); + self + } + /// Continuation token for fetching the next page of results. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> AppModuleVersionListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Maximum results to return per page. + /// + /// Sets the *page size* query property to the given value. + pub fn page_size(mut self, new_value: i32) -> AppModuleVersionListCall<'a, C, A> { + self._page_size = Some(new_value); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AppModuleVersionListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> AppModuleVersionListCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AppModuleVersionListCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + diff --git a/gen/appstate1-cli/Cargo.toml b/gen/appstate1-cli/Cargo.toml index e8170d65b4..5c104a1291 100644 --- a/gen/appstate1-cli/Cargo.toml +++ b/gen/appstate1-cli/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-appstate1-cli" -version = "0.3.2+20150717" +version = "0.3.2+20151013" 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-cli" diff --git a/gen/appstate1-cli/README.md b/gen/appstate1-cli/README.md index cdd3f42c17..bce7bb4284 100644 --- a/gen/appstate1-cli/README.md +++ b/gen/appstate1-cli/README.md @@ -24,7 +24,7 @@ Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/ma # Usage -This documentation was generated from the *App State* API at revision *20150717*. The CLI is at version *0.3.2*. +This documentation was generated from the *App State* API at revision *20151013*. The CLI is at version *0.3.2*. ```bash appstate1 [options] diff --git a/gen/appstate1-cli/mkdocs.yml b/gen/appstate1-cli/mkdocs.yml index 59787b93b1..f564356885 100644 --- a/gen/appstate1-cli/mkdocs.yml +++ b/gen/appstate1-cli/mkdocs.yml @@ -1,4 +1,4 @@ -site_name: App State v0.3.2+20150717 +site_name: App State v0.3.2+20151013 site_url: http://byron.github.io/google-apis-rs/google-appstate1-cli site_description: Write integrating applications with bcore diff --git a/gen/appstate1-cli/src/main.rs b/gen/appstate1-cli/src/main.rs index 76722b6e17..9874e79c9a 100644 --- a/gen/appstate1-cli/src/main.rs +++ b/gen/appstate1-cli/src/main.rs @@ -568,7 +568,7 @@ fn main() { let mut app = App::new("appstate1") .author("Sebastian Thiel ") - .version("0.3.2+20150717") + .version("0.3.2+20151013") .about("The Google App State API.") .after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_appstate1_cli") .arg(Arg::with_name("url") diff --git a/gen/appstate1/Cargo.toml b/gen/appstate1/Cargo.toml index 0f0d40c131..05aa20d790 100644 --- a/gen/appstate1/Cargo.toml +++ b/gen/appstate1/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-appstate1" -version = "0.1.9+20150717" +version = "0.1.9+20151013" 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" diff --git a/gen/appstate1/README.md b/gen/appstate1/README.md index 90ac730490..ef55982643 100644 --- a/gen/appstate1/README.md +++ b/gen/appstate1/README.md @@ -5,7 +5,7 @@ DO NOT EDIT ! --> 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.9+20150717*, where *20150717* is the exact revision of the *appstate:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +This documentation was generated from *App State* crate version *0.1.9+20151013*, where *20151013* is the exact revision of the *appstate:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. 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). diff --git a/gen/appstate1/src/lib.rs b/gen/appstate1/src/lib.rs index 924266acec..e63fe8e009 100644 --- a/gen/appstate1/src/lib.rs +++ b/gen/appstate1/src/lib.rs @@ -2,7 +2,7 @@ // This file was generated automatically from 'src/mako/api/lib.rs.mako' // DO NOT EDIT ! -//! This documentation was generated from *App State* crate version *0.1.9+20150717*, where *20150717* is the exact revision of the *appstate:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +//! This documentation was generated from *App State* crate version *0.1.9+20151013*, where *20151013* is the exact revision of the *appstate:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. //! //! 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). diff --git a/gen/bigquery2-cli/Cargo.toml b/gen/bigquery2-cli/Cargo.toml index 05adacc9c1..278c63e47f 100644 --- a/gen/bigquery2-cli/Cargo.toml +++ b/gen/bigquery2-cli/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-bigquery2-cli" -version = "0.3.2+20150720" +version = "0.3.2+20151009" 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-cli" diff --git a/gen/bigquery2-cli/README.md b/gen/bigquery2-cli/README.md index a69b680898..7e78398791 100644 --- a/gen/bigquery2-cli/README.md +++ b/gen/bigquery2-cli/README.md @@ -24,7 +24,7 @@ Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/ma # Usage -This documentation was generated from the *bigquery* API at revision *20150720*. The CLI is at version *0.3.2*. +This documentation was generated from the *bigquery* API at revision *20151009*. The CLI is at version *0.3.2*. ```bash bigquery2 [options] diff --git a/gen/bigquery2-cli/mkdocs.yml b/gen/bigquery2-cli/mkdocs.yml index 8e06242ecb..5738978d47 100644 --- a/gen/bigquery2-cli/mkdocs.yml +++ b/gen/bigquery2-cli/mkdocs.yml @@ -1,4 +1,4 @@ -site_name: bigquery v0.3.2+20150720 +site_name: bigquery v0.3.2+20151009 site_url: http://byron.github.io/google-apis-rs/google-bigquery2-cli site_description: Write integrating applications with bcore diff --git a/gen/bigquery2-cli/src/main.rs b/gen/bigquery2-cli/src/main.rs index 96a60a83da..e8ce41b13b 100644 --- a/gen/bigquery2-cli/src/main.rs +++ b/gen/bigquery2-cli/src/main.rs @@ -701,6 +701,8 @@ impl<'n, 'a> Engine<'n, 'a> { "statistics.total-bytes-processed" => Some(("statistics.totalBytesProcessed", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "statistics.start-time" => Some(("statistics.startTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "statistics.query.cache-hit" => Some(("statistics.query.cacheHit", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "statistics.query.billing-tier" => Some(("statistics.query.billingTier", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "statistics.query.total-bytes-billed" => Some(("statistics.query.totalBytesBilled", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "statistics.query.total-bytes-processed" => Some(("statistics.query.totalBytesProcessed", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "statistics.end-time" => Some(("statistics.endTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "statistics.extract.destination-uri-file-counts" => Some(("statistics.extract.destinationUriFileCounts", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Vec })), @@ -766,7 +768,7 @@ impl<'n, 'a> Engine<'n, 'a> { "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "self-link" => Some(("selfLink", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), _ => { - let suggestion = FieldCursor::did_you_mean(key, &vec!["allow-jagged-rows", "allow-large-results", "allow-quoted-newlines", "cache-hit", "compression", "configuration", "copy", "create-disposition", "creation-time", "dataset-id", "debug-info", "default-dataset", "destination-format", "destination-table", "destination-uri", "destination-uri-file-counts", "destination-uris", "dry-run", "encoding", "end-time", "error-result", "etag", "extract", "field-delimiter", "flatten-results", "id", "ignore-unknown-values", "input-file-bytes", "input-files", "job-id", "job-reference", "kind", "link", "load", "location", "max-bad-records", "message", "output-bytes", "output-rows", "preserve-nulls", "print-header", "priority", "project-id", "projection-fields", "query", "quote", "reason", "schema-inline", "schema-inline-format", "self-link", "skip-leading-rows", "source-format", "source-table", "source-uri", "source-uris", "start-time", "state", "statistics", "status", "table-id", "total-bytes-processed", "use-query-cache", "user-email", "write-disposition"]); + let suggestion = FieldCursor::did_you_mean(key, &vec!["allow-jagged-rows", "allow-large-results", "allow-quoted-newlines", "billing-tier", "cache-hit", "compression", "configuration", "copy", "create-disposition", "creation-time", "dataset-id", "debug-info", "default-dataset", "destination-format", "destination-table", "destination-uri", "destination-uri-file-counts", "destination-uris", "dry-run", "encoding", "end-time", "error-result", "etag", "extract", "field-delimiter", "flatten-results", "id", "ignore-unknown-values", "input-file-bytes", "input-files", "job-id", "job-reference", "kind", "link", "load", "location", "max-bad-records", "message", "output-bytes", "output-rows", "preserve-nulls", "print-header", "priority", "project-id", "projection-fields", "query", "quote", "reason", "schema-inline", "schema-inline-format", "self-link", "skip-leading-rows", "source-format", "source-table", "source-uri", "source-uris", "start-time", "state", "statistics", "status", "table-id", "total-bytes-billed", "total-bytes-processed", "use-query-cache", "user-email", "write-disposition"]); err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); None } @@ -1321,6 +1323,9 @@ impl<'n, 'a> Engine<'n, 'a> { "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "expiration-time" => Some(("expirationTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "description" => Some(("description", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "streaming-buffer.estimated-bytes" => Some(("streamingBuffer.estimatedBytes", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "streaming-buffer.estimated-rows" => Some(("streamingBuffer.estimatedRows", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "streaming-buffer.oldest-entry-time" => Some(("streamingBuffer.oldestEntryTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "creation-time" => Some(("creationTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "table-reference.project-id" => Some(("tableReference.projectId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "table-reference.table-id" => Some(("tableReference.tableId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), @@ -1328,6 +1333,17 @@ impl<'n, 'a> Engine<'n, 'a> { "num-rows" => Some(("numRows", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "num-bytes" => Some(("numBytes", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "etag" => Some(("etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "external-data-configuration.compression" => Some(("externalDataConfiguration.compression", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "external-data-configuration.csv-options.encoding" => Some(("externalDataConfiguration.csvOptions.encoding", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "external-data-configuration.csv-options.quote" => Some(("externalDataConfiguration.csvOptions.quote", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "external-data-configuration.csv-options.allow-jagged-rows" => Some(("externalDataConfiguration.csvOptions.allowJaggedRows", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "external-data-configuration.csv-options.skip-leading-rows" => Some(("externalDataConfiguration.csvOptions.skipLeadingRows", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "external-data-configuration.csv-options.field-delimiter" => Some(("externalDataConfiguration.csvOptions.fieldDelimiter", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "external-data-configuration.csv-options.allow-quoted-newlines" => Some(("externalDataConfiguration.csvOptions.allowQuotedNewlines", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "external-data-configuration.source-format" => Some(("externalDataConfiguration.sourceFormat", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "external-data-configuration.max-bad-records" => Some(("externalDataConfiguration.maxBadRecords", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "external-data-configuration.ignore-unknown-values" => Some(("externalDataConfiguration.ignoreUnknownValues", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "external-data-configuration.source-uris" => Some(("externalDataConfiguration.sourceUris", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), "location" => Some(("location", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "friendly-name" => Some(("friendlyName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "last-modified-time" => Some(("lastModifiedTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), @@ -1336,7 +1352,7 @@ impl<'n, 'a> Engine<'n, 'a> { "self-link" => Some(("selfLink", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "view.query" => Some(("view.query", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), _ => { - let suggestion = FieldCursor::did_you_mean(key, &vec!["creation-time", "dataset-id", "description", "etag", "expiration-time", "friendly-name", "id", "kind", "last-modified-time", "location", "num-bytes", "num-rows", "project-id", "query", "self-link", "table-id", "table-reference", "type", "view"]); + let suggestion = FieldCursor::did_you_mean(key, &vec!["allow-jagged-rows", "allow-quoted-newlines", "compression", "creation-time", "csv-options", "dataset-id", "description", "encoding", "estimated-bytes", "estimated-rows", "etag", "expiration-time", "external-data-configuration", "field-delimiter", "friendly-name", "id", "ignore-unknown-values", "kind", "last-modified-time", "location", "max-bad-records", "num-bytes", "num-rows", "oldest-entry-time", "project-id", "query", "quote", "self-link", "skip-leading-rows", "source-format", "source-uris", "streaming-buffer", "table-id", "table-reference", "type", "view"]); err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); None } @@ -1481,6 +1497,9 @@ impl<'n, 'a> Engine<'n, 'a> { "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "expiration-time" => Some(("expirationTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "description" => Some(("description", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "streaming-buffer.estimated-bytes" => Some(("streamingBuffer.estimatedBytes", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "streaming-buffer.estimated-rows" => Some(("streamingBuffer.estimatedRows", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "streaming-buffer.oldest-entry-time" => Some(("streamingBuffer.oldestEntryTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "creation-time" => Some(("creationTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "table-reference.project-id" => Some(("tableReference.projectId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "table-reference.table-id" => Some(("tableReference.tableId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), @@ -1488,6 +1507,17 @@ impl<'n, 'a> Engine<'n, 'a> { "num-rows" => Some(("numRows", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "num-bytes" => Some(("numBytes", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "etag" => Some(("etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "external-data-configuration.compression" => Some(("externalDataConfiguration.compression", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "external-data-configuration.csv-options.encoding" => Some(("externalDataConfiguration.csvOptions.encoding", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "external-data-configuration.csv-options.quote" => Some(("externalDataConfiguration.csvOptions.quote", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "external-data-configuration.csv-options.allow-jagged-rows" => Some(("externalDataConfiguration.csvOptions.allowJaggedRows", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "external-data-configuration.csv-options.skip-leading-rows" => Some(("externalDataConfiguration.csvOptions.skipLeadingRows", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "external-data-configuration.csv-options.field-delimiter" => Some(("externalDataConfiguration.csvOptions.fieldDelimiter", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "external-data-configuration.csv-options.allow-quoted-newlines" => Some(("externalDataConfiguration.csvOptions.allowQuotedNewlines", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "external-data-configuration.source-format" => Some(("externalDataConfiguration.sourceFormat", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "external-data-configuration.max-bad-records" => Some(("externalDataConfiguration.maxBadRecords", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "external-data-configuration.ignore-unknown-values" => Some(("externalDataConfiguration.ignoreUnknownValues", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "external-data-configuration.source-uris" => Some(("externalDataConfiguration.sourceUris", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), "location" => Some(("location", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "friendly-name" => Some(("friendlyName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "last-modified-time" => Some(("lastModifiedTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), @@ -1496,7 +1526,7 @@ impl<'n, 'a> Engine<'n, 'a> { "self-link" => Some(("selfLink", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "view.query" => Some(("view.query", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), _ => { - let suggestion = FieldCursor::did_you_mean(key, &vec!["creation-time", "dataset-id", "description", "etag", "expiration-time", "friendly-name", "id", "kind", "last-modified-time", "location", "num-bytes", "num-rows", "project-id", "query", "self-link", "table-id", "table-reference", "type", "view"]); + let suggestion = FieldCursor::did_you_mean(key, &vec!["allow-jagged-rows", "allow-quoted-newlines", "compression", "creation-time", "csv-options", "dataset-id", "description", "encoding", "estimated-bytes", "estimated-rows", "etag", "expiration-time", "external-data-configuration", "field-delimiter", "friendly-name", "id", "ignore-unknown-values", "kind", "last-modified-time", "location", "max-bad-records", "num-bytes", "num-rows", "oldest-entry-time", "project-id", "query", "quote", "self-link", "skip-leading-rows", "source-format", "source-uris", "streaming-buffer", "table-id", "table-reference", "type", "view"]); err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); None } @@ -1582,6 +1612,9 @@ impl<'n, 'a> Engine<'n, 'a> { "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "expiration-time" => Some(("expirationTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "description" => Some(("description", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "streaming-buffer.estimated-bytes" => Some(("streamingBuffer.estimatedBytes", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "streaming-buffer.estimated-rows" => Some(("streamingBuffer.estimatedRows", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "streaming-buffer.oldest-entry-time" => Some(("streamingBuffer.oldestEntryTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "creation-time" => Some(("creationTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "table-reference.project-id" => Some(("tableReference.projectId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "table-reference.table-id" => Some(("tableReference.tableId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), @@ -1589,6 +1622,17 @@ impl<'n, 'a> Engine<'n, 'a> { "num-rows" => Some(("numRows", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "num-bytes" => Some(("numBytes", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "etag" => Some(("etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "external-data-configuration.compression" => Some(("externalDataConfiguration.compression", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "external-data-configuration.csv-options.encoding" => Some(("externalDataConfiguration.csvOptions.encoding", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "external-data-configuration.csv-options.quote" => Some(("externalDataConfiguration.csvOptions.quote", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "external-data-configuration.csv-options.allow-jagged-rows" => Some(("externalDataConfiguration.csvOptions.allowJaggedRows", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "external-data-configuration.csv-options.skip-leading-rows" => Some(("externalDataConfiguration.csvOptions.skipLeadingRows", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "external-data-configuration.csv-options.field-delimiter" => Some(("externalDataConfiguration.csvOptions.fieldDelimiter", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "external-data-configuration.csv-options.allow-quoted-newlines" => Some(("externalDataConfiguration.csvOptions.allowQuotedNewlines", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "external-data-configuration.source-format" => Some(("externalDataConfiguration.sourceFormat", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "external-data-configuration.max-bad-records" => Some(("externalDataConfiguration.maxBadRecords", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "external-data-configuration.ignore-unknown-values" => Some(("externalDataConfiguration.ignoreUnknownValues", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "external-data-configuration.source-uris" => Some(("externalDataConfiguration.sourceUris", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), "location" => Some(("location", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "friendly-name" => Some(("friendlyName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "last-modified-time" => Some(("lastModifiedTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), @@ -1597,7 +1641,7 @@ impl<'n, 'a> Engine<'n, 'a> { "self-link" => Some(("selfLink", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "view.query" => Some(("view.query", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), _ => { - let suggestion = FieldCursor::did_you_mean(key, &vec!["creation-time", "dataset-id", "description", "etag", "expiration-time", "friendly-name", "id", "kind", "last-modified-time", "location", "num-bytes", "num-rows", "project-id", "query", "self-link", "table-id", "table-reference", "type", "view"]); + let suggestion = FieldCursor::did_you_mean(key, &vec!["allow-jagged-rows", "allow-quoted-newlines", "compression", "creation-time", "csv-options", "dataset-id", "description", "encoding", "estimated-bytes", "estimated-rows", "etag", "expiration-time", "external-data-configuration", "field-delimiter", "friendly-name", "id", "ignore-unknown-values", "kind", "last-modified-time", "location", "max-bad-records", "num-bytes", "num-rows", "oldest-entry-time", "project-id", "query", "quote", "self-link", "skip-leading-rows", "source-format", "source-uris", "streaming-buffer", "table-id", "table-reference", "type", "view"]); err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); None } @@ -2021,7 +2065,7 @@ fn main() { ("jobs", "methods: 'cancel', 'get', 'get-query-results', 'insert', 'list' and 'query'", vec![ ("cancel", - Some(r##"Requests that a job be cancelled. This call will return immediately, and the client will need to poll for the job status to see if the cancel completed successfully."##), + Some(r##"Requests that a job be cancelled. This call will return immediately, and the client will need to poll for the job status to see if the cancel completed successfully. Cancelled jobs may still incur costs."##), "Details at http://byron.github.io/google-apis-rs/google_bigquery2_cli/jobs_cancel", vec![ (Some(r##"project-id"##), @@ -2139,7 +2183,7 @@ fn main() { Some(false)), ]), ("list", - Some(r##"Lists all jobs that you started in the specified project. The job list returns in reverse chronological order of when the jobs were created, starting with the most recent job created. Requires the Can View project role, or the Is Owner project role if you set the allUsers property."##), + Some(r##"Lists all jobs that you started in the specified project. Job information is available for a six month period after creation. The job list is sorted in reverse chronological order, by job creation time. Requires the Can View project role, or the Is Owner project role if you set the allUsers property."##), "Details at http://byron.github.io/google-apis-rs/google_bigquery2_cli/jobs_list", vec![ (Some(r##"project-id"##), @@ -2497,7 +2541,7 @@ fn main() { let mut app = App::new("bigquery2") .author("Sebastian Thiel ") - .version("0.3.2+20150720") + .version("0.3.2+20151009") .about("A data platform for customers to create, manage, share and query data.") .after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_bigquery2_cli") .arg(Arg::with_name("url") diff --git a/gen/bigquery2/Cargo.toml b/gen/bigquery2/Cargo.toml index 95287e424d..5e21102af6 100644 --- a/gen/bigquery2/Cargo.toml +++ b/gen/bigquery2/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-bigquery2" -version = "0.1.9+20150720" +version = "0.1.9+20151009" 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" diff --git a/gen/bigquery2/README.md b/gen/bigquery2/README.md index 9b950efc8d..40fcf45344 100644 --- a/gen/bigquery2/README.md +++ b/gen/bigquery2/README.md @@ -5,7 +5,7 @@ DO NOT EDIT ! --> The `google-bigquery2` library allows access to all features of the *Google bigquery* service. -This documentation was generated from *bigquery* crate version *0.1.9+20150720*, where *20150720* is the exact revision of the *bigquery:v2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +This documentation was generated from *bigquery* crate version *0.1.9+20151009*, where *20151009* is the exact revision of the *bigquery:v2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. Everything else about the *bigquery* *v2* API can be found at the [official documentation site](https://cloud.google.com/bigquery/). diff --git a/gen/bigquery2/src/lib.rs b/gen/bigquery2/src/lib.rs index 792a57aab9..24938fc04b 100644 --- a/gen/bigquery2/src/lib.rs +++ b/gen/bigquery2/src/lib.rs @@ -2,7 +2,7 @@ // This file was generated automatically from 'src/mako/api/lib.rs.mako' // DO NOT EDIT ! -//! This documentation was generated from *bigquery* crate version *0.1.9+20150720*, where *20150720* is the exact revision of the *bigquery:v2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +//! This documentation was generated from *bigquery* crate version *0.1.9+20151009*, where *20151009* is the exact revision of the *bigquery:v2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. //! //! Everything else about the *bigquery* *v2* API can be found at the //! [official documentation site](https://cloud.google.com/bigquery/). diff --git a/gen/bigquery2/src/lib.rs.in b/gen/bigquery2/src/lib.rs.in index fc16ba271a..38bafff3e5 100644 --- a/gen/bigquery2/src/lib.rs.in +++ b/gen/bigquery2/src/lib.rs.in @@ -38,6 +38,9 @@ pub enum Scope { /// Manage your data and permissions in Google Cloud Storage DevstorageFullControl, + /// View your data across Google Cloud Platform services + CloudPlatformReadOnly, + /// View your data in Google Cloud Storage DevstorageReadOnly, @@ -58,6 +61,7 @@ impl AsRef for Scope { fn as_ref(&self) -> &str { match *self { Scope::DevstorageFullControl => "https://www.googleapis.com/auth/devstorage.full_control", + Scope::CloudPlatformReadOnly => "https://www.googleapis.com/auth/cloud-platform.read-only", 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", @@ -210,7 +214,7 @@ impl Part for TableDataInsertAllRequestRows {} /// #[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. + /// [Output-only] 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(rename="destinationUriFileCounts")] pub destination_uri_file_counts: Option>, } @@ -234,7 +238,7 @@ pub struct QueryRequest { 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. + /// [Optional] If set to true, BigQuery doesn't run the job. Instead, if the query is valid, BigQuery returns statistics about the job such as how many bytes would be processed. If the query is invalid, an error returns. The default value is false. #[serde(rename="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. @@ -265,7 +269,13 @@ pub struct JobStatistics2 { /// [Output-only] Whether the query result was fetched from the query cache. #[serde(rename="cacheHit")] pub cache_hit: Option, - /// [Output-only] Total bytes processed for this job. + /// [Output-only] Billing tier for the job. + #[serde(rename="billingTier")] + pub billing_tier: Option, + /// [Output-only] Total bytes billed for the job. + #[serde(rename="totalBytesBilled")] + pub total_bytes_billed: Option, + /// [Output-only] Total bytes processed for the job. #[serde(rename="totalBytesProcessed")] pub total_bytes_processed: Option, } @@ -285,10 +295,10 @@ pub struct JobStatistics3 { /// [Output-only] Number of source files in a load job. #[serde(rename="inputFiles")] pub input_files: Option, - /// [Output-only] Number of bytes of source data in a joad job. + /// [Output-only] Number of bytes of source data in a load job. #[serde(rename="inputFileBytes")] pub input_file_bytes: Option, - /// [Output-only] Size of the loaded data in bytes. Note that while an import job is in the running state, this value may change. + /// [Output-only] Size of the loaded data in bytes. Note that while a load job is in the running state, this value may change. #[serde(rename="outputBytes")] pub output_bytes: Option, } @@ -389,7 +399,7 @@ pub struct Dataset { pub default_table_expiration_ms: Option, /// [Output-only] A hash of the resource. pub etag: Option, - /// [Experimental] The location where the data resides. If not present, the data will be stored in the US. + /// [Experimental] The geographic location where the dataset should reside. Possible values include EU and US. The default value is US. pub location: Option, /// [Optional] A descriptive name for the dataset. #[serde(rename="friendlyName")] @@ -477,6 +487,26 @@ impl NestedType for DatasetListDatasets {} impl Part for DatasetListDatasets {} +/// 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 Streamingbuffer { + /// [Output-only] A lower-bound estimate of the number of bytes currently in the streaming buffer. + #[serde(rename="estimatedBytes")] + pub estimated_bytes: Option, + /// [Output-only] A lower-bound estimate of the number of rows currently in the streaming buffer. + #[serde(rename="estimatedRows")] + pub estimated_rows: Option, + /// [Output-only] Contains the timestamp of the oldest entry in the streaming buffer, in milliseconds since the epoch, if the streaming buffer is available. + #[serde(rename="oldestEntryTime")] + pub oldest_entry_time: Option, +} + +impl Part for Streamingbuffer {} + + /// There is no detailed description. /// /// This type is not used in any activity, and only used as *part* of another schema. @@ -792,8 +822,8 @@ impl Part for JobConfigurationExtract {} pub struct GetQueryResultsResponse { /// The resource type of the response. pub kind: Option, - /// 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: Option>, + /// [Output-only] All errors and warnings encountered during the running of the job. Errors here do not necessarily mean that the job has completed or was unsuccessful. + pub errors: Option>, /// 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(rename="jobReference")] pub job_reference: Option, @@ -814,6 +844,8 @@ pub struct GetQueryResultsResponse { pub page_token: Option, /// A hash of this response. pub etag: Option, + /// 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: Option>, /// The schema of the results. Present only when the query completes successfully. pub schema: Option, } @@ -854,10 +886,10 @@ impl Part for CsvOptions {} /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct ExternalDataConfiguration { - /// [Optional] Indicates if BigQuery should allow extra values that are not represented in the table schema. If true, the extra values are ignored. If false, records with extra columns are treated as bad records, and if there are too many bad records, an invalid error is returned in the job result. The default value is false. The sourceFormat property determines what BigQuery treats as an extra value: CSV: Trailing columns + /// [Optional] Indicates if BigQuery should allow extra values that are not represented in the table schema. If true, the extra values are ignored. If false, records with extra columns are treated as bad records, and if there are too many bad records, an invalid error is returned in the job result. The default value is false. The sourceFormat property determines what BigQuery treats as an extra value: CSV: Trailing columns JSON: Named values that don't match any column names #[serde(rename="ignoreUnknownValues")] pub ignore_unknown_values: Option, - /// [Required] The fully-qualified URIs that point to your data in Google Cloud Storage. Each URI can contain one '*' wildcard character and it must come after the 'bucket' name. CSV limits related to load jobs apply to external data sources, plus an additional limit of 10 GB maximum size across all URIs. + /// [Required] The fully-qualified URIs that point to your data in Google Cloud Storage. Each URI can contain one '*' wildcard character and it must come after the 'bucket' name. Size limits related to load jobs apply to external data sources, plus an additional limit of 10 GB maximum size across all URIs. #[serde(rename="sourceUris")] pub source_uris: Option>, /// [Optional] The compression type of the data source. Possible values include GZIP and NONE. The default value is NONE. @@ -865,7 +897,7 @@ pub struct ExternalDataConfiguration { /// Additional properties to set if sourceFormat is set to CSV. #[serde(rename="csvOptions")] pub csv_options: Option, - /// [Optional] The data format. External data sources must be in CSV format. The default value is CSV. + /// [Required] The data format. For CSV files, specify "CSV". For newline-delimited JSON, specify "NEWLINE_DELIMITED_JSON". #[serde(rename="sourceFormat")] pub source_format: Option, /// [Optional] The maximum number of bad records that BigQuery can ignore when reading data. If the number of bad records exceeds this value, an invalid error is returned in the job result. The default value is 0, which requires that all records are valid. @@ -1272,7 +1304,10 @@ impl Part for TableReference {} pub struct Table { /// [Optional] A user-friendly description of this table. pub description: Option, - /// [Output-only] The size of the table in bytes. This property is unavailable for tables that are actively receiving streaming inserts. + /// [Output-only] The time when this table was created, in milliseconds since the epoch. + #[serde(rename="creationTime")] + pub creation_time: Option, + /// [Output-only] The size of this table in bytes, excluding any data in the streaming buffer. #[serde(rename="numBytes")] pub num_bytes: Option, /// [Output-only] The time when this table was last modified, in milliseconds since the epoch. @@ -1282,18 +1317,21 @@ pub struct Table { pub id: Option, /// [Output-only] The type of the resource. pub kind: Option, - /// [Output-only] The time when this table was created, in milliseconds since the epoch. - #[serde(rename="creationTime")] - pub creation_time: Option, + /// [Output-only] Contains information regarding this table's streaming buffer, if one is present. This field will be absent if the table is not being streamed to or if there is no data in the streaming buffer. + #[serde(rename="streamingBuffer")] + pub streaming_buffer: Option, + /// [Experimental] Describes the data format, location, and other properties of a table stored outside of BigQuery. By defining these properties, the data source can then be queried as if it were a standard BigQuery table. + #[serde(rename="externalDataConfiguration")] + pub external_data_configuration: Option, /// [Required] Reference describing the ID of this table. #[serde(rename="tableReference")] pub table_reference: Option, - /// [Output-only] The number of rows of data in this table. This property is unavailable for tables that are actively receiving streaming inserts. + /// [Output-only] The number of rows of data in this table, excluding any data in the streaming buffer. #[serde(rename="numRows")] pub num_rows: Option, /// [Output-only] A hash of this resource. pub etag: Option, - /// [Optional] The backing storage location. + /// [Output-only] The geographic location where the table resides. This value is inherited from the dataset. pub location: Option, /// [Optional] A descriptive name for this table. #[serde(rename="friendlyName")] @@ -1352,8 +1390,8 @@ impl ResponseResult for TableDataInsertAllResponse {} pub struct QueryResponse { /// The resource type. pub kind: Option, - /// 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: Option>, + /// [Output-only] All errors and warnings encountered during the running of the job. Errors here do not necessarily mean that the job has completed or was unsuccessful. + pub errors: Option>, /// 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(rename="jobReference")] pub job_reference: Option, @@ -1372,6 +1410,8 @@ pub struct QueryResponse { /// A token used for paging results. #[serde(rename="pageToken")] pub page_token: Option, + /// 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: Option>, /// The schema of the results. Present only when the query completes successfully. pub schema: Option, } @@ -1782,7 +1822,7 @@ impl<'a, C, A> JobMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Requests that a job be cancelled. This call will return immediately, and the client will need to poll for the job status to see if the cancel completed successfully. + /// Requests that a job be cancelled. This call will return immediately, and the client will need to poll for the job status to see if the cancel completed successfully. Cancelled jobs may still incur costs. /// /// # Arguments /// @@ -1843,7 +1883,7 @@ impl<'a, C, A> JobMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Lists all jobs that you started in the specified project. The job list returns in reverse chronological order of when the jobs were created, starting with the most recent job created. Requires the Can View project role, or the Is Owner project role if you set the allUsers property. + /// Lists all jobs that you started in the specified project. Job information is available for a six month period after creation. The job list is sorted in reverse chronological order, by job creation time. Requires the Can View project role, or the Is Owner project role if you set the allUsers property. /// /// # Arguments /// @@ -5289,7 +5329,7 @@ impl<'a, C, A> DatasetInsertCall<'a, C, A> where C: BorrowMut, A: } -/// Requests that a job be cancelled. This call will return immediately, and the client will need to poll for the job status to see if the cancel completed successfully. +/// Requests that a job be cancelled. This call will return immediately, and the client will need to poll for the job status to see if the cancel completed successfully. Cancelled jobs may still incur costs. /// /// A builder for the *cancel* method supported by a *job* resource. /// It is not used directly, but through a `JobMethods` instance. @@ -6100,7 +6140,7 @@ impl<'a, C, A> JobGetQueryResultCall<'a, C, A> where C: BorrowMut } -/// Lists all jobs that you started in the specified project. The job list returns in reverse chronological order of when the jobs were created, starting with the most recent job created. Requires the Can View project role, or the Is Owner project role if you set the allUsers property. +/// Lists all jobs that you started in the specified project. Job information is available for a six month period after creation. The job list is sorted in reverse chronological order, by job creation time. Requires the Can View project role, or the Is Owner project role if you set the allUsers property. /// /// A builder for the *list* method supported by a *job* resource. /// It is not used directly, but through a `JobMethods` instance. @@ -6939,10 +6979,10 @@ impl<'a, C, A> JobInsertCall<'a, C, A> where C: BorrowMut, A: oau self.doit(stream, mime_type, "simple") } /// Upload media in a resumable fashion. - /// Even if the upload fails or is interrupted, it can be resumed for a + /// Even if the upload fails or is interrupted, it can be resumed for a /// certain amount of time as the server maintains state temporarily. /// - /// The delegate will be asked for an `upload_url()`, and if not provided, will be asked to store an upload URL + /// The delegate will be asked for an `upload_url()`, and if not provided, will be asked to store an upload URL /// that was provided by the server, using `store_upload_url(...)`. The upload will be done in chunks, the delegate /// may specify the `chunk_size()` and may cancel the operation before each chunk is uploaded, using /// `cancel_chunk_upload(...)`. diff --git a/gen/books1-cli/Cargo.toml b/gen/books1-cli/Cargo.toml index 28eb93853c..92493eaf2a 100644 --- a/gen/books1-cli/Cargo.toml +++ b/gen/books1-cli/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-books1-cli" -version = "0.3.2+20150318" +version = "0.3.2+20150921" 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-cli" diff --git a/gen/books1-cli/README.md b/gen/books1-cli/README.md index 75c34ab3bd..a40ad5e686 100644 --- a/gen/books1-cli/README.md +++ b/gen/books1-cli/README.md @@ -24,7 +24,7 @@ Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/ma # Usage -This documentation was generated from the *books* API at revision *20150318*. The CLI is at version *0.3.2*. +This documentation was generated from the *books* API at revision *20150921*. The CLI is at version *0.3.2*. ```bash books1 [options] @@ -66,9 +66,13 @@ books1 [options] bookshelves-volumes-list [-p ]... [-o ] readingpositions-get [-p ]... [-o ] readingpositions-set-position [-p ]... + notification + get [-p ]... [-o ] onboarding list-categories [-p ]... [-o ] list-category-volumes [-p ]... [-o ] + personalizedstream + get [-p ]... [-o ] promooffer accept [-p ]... dismiss [-p ]... diff --git a/gen/books1-cli/mkdocs.yml b/gen/books1-cli/mkdocs.yml index 78ca08e210..9bd0e209ca 100644 --- a/gen/books1-cli/mkdocs.yml +++ b/gen/books1-cli/mkdocs.yml @@ -1,4 +1,4 @@ -site_name: books v0.3.2+20150318 +site_name: books v0.3.2+20150921 site_url: http://byron.github.io/google-apis-rs/google-books1-cli site_description: Write integrating applications with bcore @@ -41,8 +41,10 @@ pages: - ['mylibrary_bookshelves-volumes-list.md', 'Mylibrary', 'Bookshelves Volumes List'] - ['mylibrary_readingpositions-get.md', 'Mylibrary', 'Readingpositions Get'] - ['mylibrary_readingpositions-set-position.md', 'Mylibrary', 'Readingpositions Set Position'] +- ['notification_get.md', 'Notification', 'Get'] - ['onboarding_list-categories.md', 'Onboarding', 'List Categories'] - ['onboarding_list-category-volumes.md', 'Onboarding', 'List Category Volumes'] +- ['personalizedstream_get.md', 'Personalizedstream', 'Get'] - ['promooffer_accept.md', 'Promooffer', 'Accept'] - ['promooffer_dismiss.md', 'Promooffer', 'Dismiss'] - ['promooffer_get.md', 'Promooffer', 'Get'] diff --git a/gen/books1-cli/src/main.rs b/gen/books1-cli/src/main.rs index 4ab00c6b91..d9fab8df62 100644 --- a/gen/books1-cli/src/main.rs +++ b/gen/books1-cli/src/main.rs @@ -1155,11 +1155,12 @@ impl<'n, 'a> Engine<'n, 'a> { let type_info: Option<(&'static str, JsonTypeInfo)> = match &temp_cursor.to_string()[..] { + "notification.more-from-authors.opted-state" => Some(("notification.moreFromAuthors.opted_state", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "notes-export.is-enabled" => Some(("notesExport.isEnabled", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), "notes-export.folder-name" => Some(("notesExport.folderName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), _ => { - let suggestion = FieldCursor::did_you_mean(key, &vec!["folder-name", "is-enabled", "kind", "notes-export"]); + let suggestion = FieldCursor::did_you_mean(key, &vec!["folder-name", "is-enabled", "kind", "more-from-authors", "notes-export", "notification", "opted-state"]); err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); None } @@ -2187,6 +2188,65 @@ impl<'n, 'a> Engine<'n, 'a> { } } + fn _notification_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.notification().get(opt.value_of("notification-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "source" => { + call = call.source(value.unwrap_or("")); + }, + "locale" => { + call = call.locale(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["locale", "source"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + fn _onboarding_list_categories(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) -> Result<(), DoitError> { let mut call = self.hub.onboarding().list_categories(); @@ -2311,6 +2371,68 @@ impl<'n, 'a> Engine<'n, 'a> { } } + fn _personalizedstream_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.personalizedstream().get(); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "source" => { + call = call.source(value.unwrap_or("")); + }, + "max-allowed-maturity-rating" => { + call = call.max_allowed_maturity_rating(value.unwrap_or("")); + }, + "locale" => { + call = call.locale(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["locale", "source", "max-allowed-maturity-rating"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + fn _promooffer_accept(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) -> Result<(), DoitError> { let mut call = self.hub.promooffer().accept(); @@ -3151,6 +3273,17 @@ impl<'n, 'a> Engine<'n, 'a> { } } }, + ("notification", Some(opt)) => { + match opt.subcommand() { + ("get", Some(opt)) => { + call_result = self._notification_get(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("notification".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, ("onboarding", Some(opt)) => { match opt.subcommand() { ("list-categories", Some(opt)) => { @@ -3165,6 +3298,17 @@ impl<'n, 'a> Engine<'n, 'a> { } } }, + ("personalizedstream", Some(opt)) => { + match opt.subcommand() { + ("get", Some(opt)) => { + call_result = self._personalizedstream_get(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("personalizedstream".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, ("promooffer", Some(opt)) => { match opt.subcommand() { ("accept", Some(opt)) => { @@ -3433,7 +3577,7 @@ fn main() { ("dictionary", "methods: 'list-offline-metadata'", vec![ ("list-offline-metadata", - Some(r##"Returns a list of offline dictionary meatadata available"##), + Some(r##"Returns a list of offline dictionary metadata available"##), "Details at http://byron.github.io/google-apis-rs/google_books1_cli/dictionary_list-offline-metadata", vec![ (Some(r##"cpksver"##), @@ -4105,6 +4249,31 @@ fn main() { ]), ]), + ("notification", "methods: 'get'", vec![ + ("get", + Some(r##"Returns notification details for a given notification id."##), + "Details at http://byron.github.io/google-apis-rs/google_books1_cli/notification_get", + vec![ + (Some(r##"notification-id"##), + None, + Some(r##"String to identify the notification."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + ("onboarding", "methods: 'list-categories' and 'list-category-volumes'", vec![ ("list-categories", Some(r##"List categories for onboarding experience."##), @@ -4140,6 +4309,25 @@ fn main() { ]), ]), + ("personalizedstream", "methods: 'get'", vec![ + ("get", + Some(r##"Returns a stream of personalized book clusters"##), + "Details at http://byron.github.io/google-apis-rs/google_books1_cli/personalizedstream_get", + vec![ + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + ("promooffer", "methods: 'accept', 'dismiss' and 'get'", vec![ ("accept", Some(r##""##), @@ -4328,7 +4516,7 @@ fn main() { let mut app = App::new("books1") .author("Sebastian Thiel ") - .version("0.3.2+20150318") + .version("0.3.2+20150921") .about("Lets you search for books and manage your Google Books library.") .after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_books1_cli") .arg(Arg::with_name("url") diff --git a/gen/books1/Cargo.toml b/gen/books1/Cargo.toml index c597d65913..251410cfb2 100644 --- a/gen/books1/Cargo.toml +++ b/gen/books1/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-books1" -version = "0.1.9+20150318" +version = "0.1.9+20150921" 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" diff --git a/gen/books1/README.md b/gen/books1/README.md index 7c755fff0f..7960798791 100644 --- a/gen/books1/README.md +++ b/gen/books1/README.md @@ -5,7 +5,7 @@ DO NOT EDIT ! --> The `google-books1` library allows access to all features of the *Google books* service. -This documentation was generated from *books* crate version *0.1.9+20150318*, where *20150318* is the exact revision of the *books:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +This documentation was generated from *books* crate version *0.1.9+20150921*, where *20150921* is the exact revision of the *books:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. Everything else about the *books* *v1* API can be found at the [official documentation site](https://developers.google.com/books/docs/v1/getting_started). @@ -25,8 +25,12 @@ Handle the following *Resources* with ease from the central [hub](http://byron.g * [*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) +* [notification](http://byron.github.io/google-apis-rs/google_books1/struct.Notification.html) + * [*get*](http://byron.github.io/google-apis-rs/google_books1/struct.NotificationGetCall.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) +* personalizedstream + * [*get*](http://byron.github.io/google-apis-rs/google_books1/struct.PersonalizedstreamGetCall.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) diff --git a/gen/books1/src/lib.rs b/gen/books1/src/lib.rs index 43b4a164cd..247771466f 100644 --- a/gen/books1/src/lib.rs +++ b/gen/books1/src/lib.rs @@ -2,7 +2,7 @@ // This file was generated automatically from 'src/mako/api/lib.rs.mako' // DO NOT EDIT ! -//! This documentation was generated from *books* crate version *0.1.9+20150318*, where *20150318* is the exact revision of the *books:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +//! This documentation was generated from *books* crate version *0.1.9+20150921*, where *20150921* is the exact revision of the *books:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. //! //! Everything else about the *books* *v1* API can be found at the //! [official documentation site](https://developers.google.com/books/docs/v1/getting_started). @@ -23,8 +23,12 @@ //! * [*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) +//! * [notification](struct.Notification.html) +//! * [*get*](struct.NotificationGetCall.html) //! * onboarding //! * [*list categories*](struct.OnboardingListCategoryCall.html) and [*list category volumes*](struct.OnboardingListCategoryVolumeCall.html) +//! * personalizedstream +//! * [*get*](struct.PersonalizedstreamGetCall.html) //! * promooffer //! * [*accept*](struct.PromoofferAcceptCall.html), [*dismiss*](struct.PromoofferDismisCall.html) and [*get*](struct.PromoofferGetCall.html) //! * [volumes](struct.Volume.html) @@ -117,18 +121,18 @@ //! // execute the final call using `doit()`. //! // Values shown here are possibly random and not representative ! //! let result = hub.volumes().list("q") -//! .start_index(80) -//! .source("tempor") +//! .start_index(18) +//! .source("elitr") //! .show_preorders(false) -//! .projection("dolore") -//! .print_type("amet.") -//! .partner("dolore") -//! .order_by("magna") -//! .max_results(7) -//! .library_restrict("magna") -//! .lang_restrict("ipsum") -//! .filter("invidunt") -//! .download("accusam") +//! .projection("ipsum") +//! .print_type("invidunt") +//! .partner("accusam") +//! .order_by("labore") +//! .max_results(22) +//! .library_restrict("nonumy") +//! .lang_restrict("sed") +//! .filter("diam") +//! .download("magna") //! .doit(); //! //! match result { diff --git a/gen/books1/src/lib.rs.in b/gen/books1/src/lib.rs.in index 6a488860d5..239705f714 100644 --- a/gen/books1/src/lib.rs.in +++ b/gen/books1/src/lib.rs.in @@ -160,9 +160,15 @@ impl<'a, C, A> Books pub fn mylibrary(&'a self) -> MylibraryMethods<'a, C, A> { MylibraryMethods { hub: &self } } + pub fn notification(&'a self) -> NotificationMethods<'a, C, A> { + NotificationMethods { hub: &self } + } pub fn onboarding(&'a self) -> OnboardingMethods<'a, C, A> { OnboardingMethods { hub: &self } } + pub fn personalizedstream(&'a self) -> PersonalizedstreamMethods<'a, C, A> { + PersonalizedstreamMethods { hub: &self } + } pub fn promooffer(&'a self) -> PromoofferMethods<'a, C, A> { PromoofferMethods { hub: &self } } @@ -411,31 +417,47 @@ pub struct RequestAccess { impl ResponseResult for RequestAccess {} +/// 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, Serialize, 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(rename="nextPageToken")] + pub next_page_token: Option, + /// A list of volume annotations. + pub items: Option>, + /// Resource type + pub kind: Option, + /// 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: Option, + /// The total number of volume annotations found. + #[serde(rename="totalItems")] + pub total_items: Option, +} + +impl ResponseResult for Volumeannotations {} + + /// 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 OffersItemsItems { +pub struct UsersettingsNotification { /// no description provided - pub description: Option, - /// no description provided - pub author: Option, - /// no description provided - pub title: Option, - /// no description provided - #[serde(rename="coverUrl")] - pub cover_url: Option, - /// no description provided - #[serde(rename="volumeId")] - pub volume_id: Option, - /// no description provided - #[serde(rename="canonicalVolumeLink")] - pub canonical_volume_link: Option, + #[serde(rename="moreFromAuthors")] + pub more_from_authors: Option, } -impl NestedType for OffersItemsItems {} -impl Part for OffersItemsItems {} +impl NestedType for UsersettingsNotification {} +impl Part for UsersettingsNotification {} /// There is no detailed description. @@ -575,6 +597,29 @@ 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 personalizedstream](struct.PersonalizedstreamGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Discoveryclusters { + /// no description provided + pub clusters: Option>, + /// Resorce type. + pub kind: Option, + /// no description provided + #[serde(rename="totalClusters")] + pub total_clusters: Option, +} + +impl ResponseResult for Discoveryclusters {} + + /// There is no detailed description. /// /// # Activities @@ -587,6 +632,8 @@ impl Part for VolumeLayerInfo {} /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct Usersettings { + /// no description provided + pub notification: Option, /// Resource type. pub kind: Option, /// User settings in sub-objects, each for different purposes. @@ -634,19 +681,32 @@ impl NestedType for MetadataItems {} impl Part for MetadataItems {} -/// Author of this review. +/// There is no detailed description. /// -/// This type is not used in any activity, and only used as *part* of another schema. +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where 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 notification](struct.NotificationGetCall.html) (response) /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] -pub struct ReviewAuthor { - /// Name of this person. - #[serde(rename="displayName")] - pub display_name: Option, +pub struct Notification { + /// no description provided + pub body: Option, + /// no description provided + #[serde(rename="iconUrl")] + pub icon_url: Option, + /// Resource type. + pub kind: Option, + /// no description provided + #[serde(rename="linkUrl")] + pub link_url: Option, + /// no description provided + pub title: Option, } -impl NestedType for ReviewAuthor {} -impl Part for ReviewAuthor {} +impl ResponseResult for Notification {} /// There is no detailed description. @@ -1183,34 +1243,6 @@ pub struct Volumeannotation { 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, Serialize, 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(rename="nextPageToken")] - pub next_page_token: Option, - /// A list of volume annotations. - pub items: Option>, - /// Resource type - pub kind: Option, - /// 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: Option, - /// The total number of volume annotations found. - #[serde(rename="totalItems")] - pub total_items: Option, -} - -impl ResponseResult for Volumeannotations {} - - /// There is no detailed description. /// /// # Activities @@ -1237,6 +1269,59 @@ pub struct Annotationsdata { impl ResponseResult for Annotationsdata {} +/// 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 DiscoveryclustersClusters { + /// no description provided + #[serde(rename="totalVolumes")] + pub total_volumes: Option, + /// no description provided + #[serde(rename="subTitle")] + pub sub_title: Option, + /// no description provided + pub uid: Option, + /// no description provided + pub banner_with_content_container: Option, + /// no description provided + pub title: Option, + /// no description provided + pub volumes: Option>, +} + +impl NestedType for DiscoveryclustersClusters {} +impl Part for DiscoveryclustersClusters {} + + +/// 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 OffersItemsItems { + /// no description provided + pub description: Option, + /// no description provided + pub author: Option, + /// no description provided + pub title: Option, + /// no description provided + #[serde(rename="coverUrl")] + pub cover_url: Option, + /// no description provided + #[serde(rename="volumeId")] + pub volume_id: Option, + /// no description provided + #[serde(rename="canonicalVolumeLink")] + pub canonical_volume_link: Option, +} + +impl NestedType for OffersItemsItems {} +impl Part for OffersItemsItems {} + + /// Industry standard identifiers for this volume. /// /// This type is not used in any activity, and only used as *part* of another schema. @@ -1360,6 +1445,21 @@ impl NestedType for VolumeAccessInfoPdf {} impl Part for VolumeAccessInfoPdf {} +/// Author of this review. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ReviewAuthor { + /// Name of this person. + #[serde(rename="displayName")] + pub display_name: Option, +} + +impl NestedType for ReviewAuthor {} +impl Part for ReviewAuthor {} + + /// There is no detailed description. /// /// # Activities @@ -1464,6 +1564,36 @@ impl NestedType for OffersItems {} impl Part for OffersItems {} +/// 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 DiscoveryclustersClustersBannerWithContentContainer { + /// no description provided + #[serde(rename="maskColorArgb")] + pub mask_color_argb: Option, + /// no description provided + #[serde(rename="moreButtonText")] + pub more_button_text: Option, + /// no description provided + #[serde(rename="moreButtonUrl")] + pub more_button_url: Option, + /// no description provided + #[serde(rename="textColorArgb")] + pub text_color_argb: Option, + /// no description provided + #[serde(rename="imageUrl")] + pub image_url: Option, + /// no description provided + #[serde(rename="fillColorArgb")] + pub fill_color_argb: Option, +} + +impl NestedType for DiscoveryclustersClustersBannerWithContentContainer {} +impl Part for DiscoveryclustersClustersBannerWithContentContainer {} + + /// Copy/Paste accounting information. /// /// This type is not used in any activity, and only used as *part* of another schema. @@ -1517,8 +1647,9 @@ pub struct VolumeUserInfo { /// Period during this book is/was a valid rental. #[serde(rename="rentalPeriod")] pub rental_period: Option, - /// 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: Option, + /// How this volume was acquired. + #[serde(rename="acquisitionType")] + pub acquisition_type: Option, /// no description provided #[serde(rename="userUploadedVolumeInfo")] pub user_uploaded_volume_info: Option, @@ -1528,12 +1659,17 @@ pub struct VolumeUserInfo { /// Whether or not this volume was purchased by the authenticated user making the request. (In LITE projection.) #[serde(rename="isPurchased")] pub is_purchased: Option, - /// The user's current reading position in the volume, if one is available. (In LITE projection.) - #[serde(rename="readingPosition")] - pub reading_position: Option, + /// 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: Option, /// Whether or not this volume was pre-ordered by the authenticated user making the request. (In LITE projection.) #[serde(rename="isPreordered")] pub is_preordered: Option, + /// The user's current reading position in the volume, if one is available. (In LITE projection.) + #[serde(rename="readingPosition")] + pub reading_position: Option, + /// Whether this volume is purchased, sample, pd download etc. + #[serde(rename="entitlementType")] + pub entitlement_type: Option, /// Copy/Paste accounting information. pub copy: Option, /// This user's review of this volume, if one exists. @@ -1769,6 +1905,20 @@ pub struct Volumes { impl ResponseResult for Volumes {} +/// 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 UsersettingsNotificationMoreFromAuthors { + /// no description provided + pub opted_state: Option, +} + +impl NestedType for UsersettingsNotificationMoreFromAuthors {} +impl Part for UsersettingsNotificationMoreFromAuthors {} + + /// 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. @@ -2090,6 +2240,28 @@ impl<'a, C, A> VolumeMethods<'a, C, A> { } } + /// Create a builder to help you perform the following task: + /// + /// Gets volume information for a single volume. + /// + /// # Arguments + /// + /// * `volumeId` - ID of volume to retrieve. + pub fn get(&self, volume_id: &str) -> VolumeGetCall<'a, C, 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 books in My Library. @@ -2176,28 +2348,6 @@ impl<'a, C, A> VolumeMethods<'a, C, A> { } } - /// Create a builder to help you perform the following task: - /// - /// Gets volume information for a single volume. - /// - /// # Arguments - /// - /// * `volumeId` - ID of volume to retrieve. - pub fn get(&self, volume_id: &str) -> VolumeGetCall<'a, C, 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. @@ -2256,7 +2406,7 @@ impl<'a, C, A> DictionaryMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Returns a list of offline dictionary meatadata available + /// Returns a list of offline dictionary metadata available /// /// # Arguments /// @@ -2274,6 +2424,66 @@ impl<'a, C, A> DictionaryMethods<'a, C, A> { +/// A builder providing access to all methods supported on *notification* 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(...)` +/// // to build up your call. +/// let rb = hub.notification(); +/// # } +/// ``` +pub struct NotificationMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Books, +} + +impl<'a, C, A> MethodsBuilder for NotificationMethods<'a, C, A> {} + +impl<'a, C, A> NotificationMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Returns notification details for a given notification id. + /// + /// # Arguments + /// + /// * `notification_id` - String to identify the notification. + pub fn get(&self, notification_id: &str) -> NotificationGetCall<'a, C, A> { + NotificationGetCall { + hub: self.hub, + _notification_id: notification_id.to_string(), + _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 *bookshelve* resources. /// It is not used directly, but through the `Books` hub. /// @@ -2474,6 +2684,62 @@ impl<'a, C, A> PromoofferMethods<'a, C, A> { +/// A builder providing access to all methods supported on *personalizedstream* 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(...)` +/// // to build up your call. +/// let rb = hub.personalizedstream(); +/// # } +/// ``` +pub struct PersonalizedstreamMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Books, +} + +impl<'a, C, A> MethodsBuilder for PersonalizedstreamMethods<'a, C, A> {} + +impl<'a, C, A> PersonalizedstreamMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Returns a stream of personalized book clusters + pub fn get(&self) -> PersonalizedstreamGetCall<'a, C, A> { + PersonalizedstreamGetCall { + hub: self.hub, + _source: Default::default(), + _max_allowed_maturity_rating: Default::default(), + _locale: 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. /// @@ -5328,6 +5594,301 @@ impl<'a, C, A> VolumeRecommendedRateCall<'a, C, A> where C: BorrowMut::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(false) +/// .source("Lorem") +/// .projection("et") +/// .partner("clita") +/// .country("consetetur") +/// .doit(); +/// # } +/// ``` +pub struct VolumeGetCall<'a, C, A> + where C: '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, A> CallBuilder for VolumeGetCall<'a, C, A> {} + +impl<'a, C, A> VolumeGetCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// ID of volume to retrieve. + /// + /// 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. + pub fn volume_id(mut self, new_value: &str) -> VolumeGetCall<'a, C, 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, A> { + self._user_library_consistent_read = Some(new_value); + self + } + /// String to identify the originator of this request. + /// + /// Sets the *source* query property to the given value. + pub fn source(mut self, new_value: &str) -> VolumeGetCall<'a, C, A> { + self._source = Some(new_value.to_string()); + self + } + /// Restrict information returned to a set of selected fields. + /// + /// Sets the *projection* query property to the given value. + pub fn projection(mut self, new_value: &str) -> VolumeGetCall<'a, C, A> { + self._projection = Some(new_value.to_string()); + self + } + /// Brand results for partner ID. + /// + /// Sets the *partner* query property to the given value. + pub fn partner(mut self, new_value: &str) -> VolumeGetCall<'a, C, A> { + self._partner = Some(new_value.to_string()); + self + } + /// ISO-3166-1 code to override the IP-based location. + /// + /// Sets the *country* query property to the given value. + pub fn country(mut self, new_value: &str) -> VolumeGetCall<'a, C, A> { + self._country = Some(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> VolumeGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Full`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + /// Return a list of books in My Library. /// /// A builder for the *mybooks.list* method supported by a *volume* resource. @@ -5355,12 +5916,12 @@ impl<'a, C, A> VolumeRecommendedRateCall<'a, C, A> where C: BorrowMut VolumeMybookListCall<'a, C, A> where C: BorrowMut, /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.volumes().list("q") -/// .start_index(61) -/// .source("kasd") -/// .show_preorders(true) -/// .projection("takimata") -/// .print_type("At") -/// .partner("labore") -/// .order_by("invidunt") -/// .max_results(35) -/// .library_restrict("sadipscing") -/// .lang_restrict("rebum.") -/// .filter("dolore") -/// .download("nonumy") +/// .start_index(64) +/// .source("ea") +/// .show_preorders(false) +/// .projection("rebum.") +/// .print_type("dolore") +/// .partner("nonumy") +/// .order_by("sed") +/// .max_results(19) +/// .library_restrict("sit") +/// .lang_restrict("eirmod") +/// .filter("consetetur") +/// .download("labore") /// .doit(); /// # } /// ``` @@ -6000,11 +6561,11 @@ impl<'a, C, A> VolumeListCall<'a, C, A> where C: BorrowMut, A: oa /// // Values shown here are possibly random and not representative ! /// let result = hub.volumes().useruploaded_list() /// .add_volume_id("sed") -/// .start_index(19) -/// .source("sit") -/// .add_processing_state("eirmod") -/// .max_results(55) -/// .locale("labore") +/// .start_index(85) +/// .source("gubergren") +/// .add_processing_state("aliquyam") +/// .max_results(77) +/// .locale("tempor") /// .doit(); /// # } /// ``` @@ -6284,10 +6845,10 @@ impl<'a, C, A> VolumeUseruploadedListCall<'a, C, A> where C: BorrowMut VolumeAssociatedListCall<'a, C, A> where C: BorrowMut::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(false) -/// .source("labore") -/// .projection("ipsum") -/// .partner("aliquyam") -/// .country("dolores") -/// .doit(); -/// # } -/// ``` -pub struct VolumeGetCall<'a, C, A> - where C: '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, A> CallBuilder for VolumeGetCall<'a, C, A> {} - -impl<'a, C, A> VolumeGetCall<'a, C, A> where 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 Err(Error::FieldClash(field)); - } - } - for (name, 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_ref().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() { - if let Some(index) = params.iter().position(|t| &t.0 == param_name) { - indices_for_removal.push(index); - } - } - for &index in indices_for_removal.iter() { - params.remove(index); - } - } - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_token }); - let mut req_result = { - let mut client = &mut *self.hub.client.borrow_mut(); - let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = { - let mut json_response = String::new(); - res.read_to_string(&mut json_response).unwrap(); - match json::from_str(&json_response) { - Ok(decoded) => (res, decoded), - Err(err) => { - dlg.response_json_decode_error(&json_response, &err); - return Err(Error::JsonDecodeError(json_response, err)); - } - } - }; - - dlg.finished(true); - return Ok(result_value) - } - } - } - } - - - /// ID of volume to retrieve. - /// - /// 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. - pub fn volume_id(mut self, new_value: &str) -> VolumeGetCall<'a, C, 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, A> { - self._user_library_consistent_read = Some(new_value); - self - } - /// String to identify the originator of this request. - /// - /// Sets the *source* query property to the given value. - pub fn source(mut self, new_value: &str) -> VolumeGetCall<'a, C, A> { - self._source = Some(new_value.to_string()); - self - } - /// Restrict information returned to a set of selected fields. - /// - /// Sets the *projection* query property to the given value. - pub fn projection(mut self, new_value: &str) -> VolumeGetCall<'a, C, A> { - self._projection = Some(new_value.to_string()); - self - } - /// Brand results for partner ID. - /// - /// Sets the *partner* query property to the given value. - pub fn partner(mut self, new_value: &str) -> VolumeGetCall<'a, C, A> { - self._partner = Some(new_value.to_string()); - self - } - /// ISO-3166-1 code to override the IP-based location. - /// - /// Sets the *country* query property to the given value. - pub fn country(mut self, new_value: &str) -> VolumeGetCall<'a, C, A> { - self._country = Some(new_value.to_string()); - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> VolumeGetCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. - /// * *fields* (query-string) - Selector specifying which 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, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::Full`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing 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, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().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. @@ -7075,7 +7341,7 @@ impl<'a, C, A> VolumeRecommendedListCall<'a, C, A> where C: BorrowMut DictionaryListOfflineMetadataCall<'a, C, A> where C: BorrowMut::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.notification().get("notification_id") +/// .source("amet") +/// .locale("accusam") +/// .doit(); +/// # } +/// ``` +pub struct NotificationGetCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Books, + _notification_id: String, + _source: Option, + _locale: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for NotificationGetCall<'a, C, A> {} + +impl<'a, C, A> NotificationGetCall<'a, C, A> where 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: "books.notification.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("notification_id", self._notification_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", "notification_id", "source", "locale"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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/notification/get".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_ref().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// String to identify the notification. + /// + /// Sets the *notification_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. + pub fn notification_id(mut self, new_value: &str) -> NotificationGetCall<'a, C, A> { + self._notification_id = new_value.to_string(); + self + } + /// String to identify the originator of this request. + /// + /// Sets the *source* query property to the given value. + pub fn source(mut self, new_value: &str) -> NotificationGetCall<'a, C, A> { + self._source = Some(new_value.to_string()); + self + } + /// ISO-639-1 language and ISO-3166-1 country code. Ex: 'en_US'. Used for generating notification title and body. + /// + /// Sets the *locale* query property to the given value. + pub fn locale(mut self, new_value: &str) -> NotificationGetCall<'a, C, A> { + self._locale = Some(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> NotificationGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Full`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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. @@ -7317,10 +7822,10 @@ impl<'a, C, A> DictionaryListOfflineMetadataCall<'a, C, A> where C: BorrowMut BookshelveVolumeListCall<'a, C, A> where C: BorrowMut BookshelveListCall<'a, C, A> where C: BorrowMut, A /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.bookshelves().get("userId", "shelf") -/// .source("dolores") +/// .source("duo") /// .doit(); /// # } /// ``` @@ -8121,14 +8626,14 @@ impl<'a, C, A> BookshelveGetCall<'a, C, A> where C: BorrowMut, A: /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.promooffer().accept() -/// .volume_id("eos") -/// .serial("voluptua.") -/// .product("duo") -/// .offer_id("sed") -/// .model("aliquyam") -/// .manufacturer("ea") -/// .device("ea") -/// .android_id("et") +/// .volume_id("sed") +/// .serial("aliquyam") +/// .product("ea") +/// .offer_id("ea") +/// .model("et") +/// .manufacturer("dolor") +/// .device("diam") +/// .android_id("kasd") /// .doit(); /// # } /// ``` @@ -8408,13 +8913,13 @@ impl<'a, C, A> PromoofferAcceptCall<'a, C, A> where C: BorrowMut, /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.promooffer().dismiss() -/// .serial("dolor") -/// .product("diam") -/// .offer_id("kasd") -/// .model("invidunt") -/// .manufacturer("rebum.") -/// .device("Lorem") -/// .android_id("clita") +/// .serial("invidunt") +/// .product("rebum.") +/// .offer_id("Lorem") +/// .model("clita") +/// .manufacturer("invidunt") +/// .device("eirmod") +/// .android_id("At") /// .doit(); /// # } /// ``` @@ -8684,12 +9189,12 @@ impl<'a, C, A> PromoofferDismisCall<'a, C, A> where C: BorrowMut, /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.promooffer().get() -/// .serial("invidunt") -/// .product("eirmod") -/// .model("At") -/// .manufacturer("consetetur") -/// .device("et") -/// .android_id("sed") +/// .serial("consetetur") +/// .product("et") +/// .model("sed") +/// .manufacturer("sit") +/// .device("takimata") +/// .android_id("elitr") /// .doit(); /// # } /// ``` @@ -8932,6 +9437,245 @@ impl<'a, C, A> PromoofferGetCall<'a, C, A> where C: BorrowMut, A: } +/// Returns a stream of personalized book clusters +/// +/// A builder for the *get* method supported by a *personalizedstream* resource. +/// It is not used directly, but through a `PersonalizedstreamMethods` instance. +/// +/// # 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.personalizedstream().get() +/// .source("nonumy") +/// .max_allowed_maturity_rating("rebum.") +/// .locale("Lorem") +/// .doit(); +/// # } +/// ``` +pub struct PersonalizedstreamGetCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Books, + _source: Option, + _max_allowed_maturity_rating: Option, + _locale: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for PersonalizedstreamGetCall<'a, C, A> {} + +impl<'a, C, A> PersonalizedstreamGetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Discoveryclusters)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.personalizedstream.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._source { + params.push(("source", value.to_string())); + } + if let Some(value) = self._max_allowed_maturity_rating { + params.push(("maxAllowedMaturityRating", value.to_string())); + } + if let Some(value) = self._locale { + params.push(("locale", value.to_string())); + } + for &field in ["alt", "source", "maxAllowedMaturityRating", "locale"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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/personalizedstream/get".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_ref().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// String to identify the originator of this request. + /// + /// Sets the *source* query property to the given value. + pub fn source(mut self, new_value: &str) -> PersonalizedstreamGetCall<'a, C, A> { + self._source = Some(new_value.to_string()); + self + } + /// The maximum allowed maturity rating of returned recommendations. Books with a higher maturity rating are filtered out. + /// + /// Sets the *max allowed maturity rating* query property to the given value. + pub fn max_allowed_maturity_rating(mut self, new_value: &str) -> PersonalizedstreamGetCall<'a, C, A> { + self._max_allowed_maturity_rating = Some(new_value.to_string()); + self + } + /// ISO-639-1 language and ISO-3166-1 country code. Ex: 'en_US'. Used for generating recommendations. + /// + /// Sets the *locale* query property to the given value. + pub fn locale(mut self, new_value: &str) -> PersonalizedstreamGetCall<'a, C, A> { + self._locale = Some(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PersonalizedstreamGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PersonalizedstreamGetCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Full`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PersonalizedstreamGetCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + /// List categories for onboarding experience. /// /// A builder for the *listCategories* method supported by a *onboarding* resource. @@ -8959,7 +9703,7 @@ impl<'a, C, A> PromoofferGetCall<'a, C, A> where C: BorrowMut, A: /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.onboarding().list_categories() -/// .locale("sit") +/// .locale("Lorem") /// .doit(); /// # } /// ``` @@ -9174,11 +9918,11 @@ impl<'a, C, A> OnboardingListCategoryCall<'a, C, A> where C: BorrowMut OnboardingListCategoryVolumeCall<'a, C, A> where C: BorrowMut MyconfigRequestAccesCall<'a, C, A> where C: BorrowMut MyconfigReleaseDownloadAccesCall<'a, C, A> where C: BorrowMut MyconfigUpdateUserSettingCall<'a, C, A> where C: BorrowMut MylibraryBookshelveClearVolumeCall<'a, C, A> where C: BorrowMut MylibraryBookshelveMoveVolumeCall<'a, C, A> where C: BorrowMut MylibraryAnnotationSummaryCall<'a, C, A> where C: BorrowMut MylibraryAnnotationDeleteCall<'a, C, A> where C: BorrowMut MylibraryBookshelveAddVolumeCall<'a, C, A> where C: BorrowMut MylibraryAnnotationInsertCall<'a, C, A> where C: BorrowMut MylibraryBookshelveRemoveVolumeCall<'a, C, A> where C: BorrowMut< /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.mylibrary().annotations_list() -/// .volume_id("dolor") -/// .updated_min("aliquyam") -/// .updated_max("elitr") -/// .source("ea") +/// .volume_id("sed") +/// .updated_min("dolor") +/// .updated_max("sanctus") +/// .source("dolore") /// .show_deleted(true) -/// .page_token("Stet") -/// .max_results(58) -/// .add_layer_ids("dolor") -/// .layer_id("sanctus") -/// .content_version("dolore") +/// .page_token("consetetur") +/// .max_results(55) +/// .add_layer_ids("eirmod") +/// .layer_id("labore") +/// .content_version("gubergren") /// .doit(); /// # } /// ``` @@ -13124,7 +13868,7 @@ impl<'a, C, A> MylibraryAnnotationListCall<'a, C, A> where C: BorrowMut MylibraryAnnotationUpdateCall<'a, C, A> where C: BorrowMut MylibraryReadingpositionSetPositionCall<'a, C, A> where C: Borrow /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.mylibrary().bookshelves_get("shelf") -/// .source("Lorem") +/// .source("vero") /// .doit(); /// # } /// ``` @@ -13942,7 +14686,7 @@ impl<'a, C, A> MylibraryBookshelveGetCall<'a, C, A> where C: BorrowMut MylibraryBookshelveListCall<'a, C, A> where C: BorrowMut MylibraryReadingpositionGetCall<'a, C, A> where C: BorrowMut"] description = "A complete library to interact with calendar (protocol v3)" repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/calendar3-cli" diff --git a/gen/calendar3-cli/README.md b/gen/calendar3-cli/README.md index a27eaba45b..496edb7dcb 100644 --- a/gen/calendar3-cli/README.md +++ b/gen/calendar3-cli/README.md @@ -24,7 +24,7 @@ Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/ma # Usage -This documentation was generated from the *calendar* API at revision *20150715*. The CLI is at version *0.3.2*. +This documentation was generated from the *calendar* API at revision *20151011*. The CLI is at version *0.3.2*. ```bash calendar3 [options] diff --git a/gen/calendar3-cli/mkdocs.yml b/gen/calendar3-cli/mkdocs.yml index 3daa6d2c68..ec191fc45a 100644 --- a/gen/calendar3-cli/mkdocs.yml +++ b/gen/calendar3-cli/mkdocs.yml @@ -1,4 +1,4 @@ -site_name: calendar v0.3.2+20150715 +site_name: calendar v0.3.2+20151011 site_url: http://byron.github.io/google-apis-rs/google-calendar3-cli site_description: Write integrating applications with bcore diff --git a/gen/calendar3-cli/src/main.rs b/gen/calendar3-cli/src/main.rs index f0e6e859c8..11acceab15 100644 --- a/gen/calendar3-cli/src/main.rs +++ b/gen/calendar3-cli/src/main.rs @@ -3454,7 +3454,7 @@ fn main() { vec![ (Some(r##"calendar-id"##), None, - Some(r##"Calendar identifier."##), + Some(r##"Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword."##), Some(true), Some(false)), @@ -3476,7 +3476,7 @@ fn main() { vec![ (Some(r##"calendar-id"##), None, - Some(r##"Calendar identifier."##), + Some(r##"Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword."##), Some(true), Some(false)), @@ -3504,7 +3504,7 @@ fn main() { vec![ (Some(r##"calendar-id"##), None, - Some(r##"Calendar identifier."##), + Some(r##"Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword."##), Some(true), Some(false)), @@ -3532,7 +3532,7 @@ fn main() { vec![ (Some(r##"calendar-id"##), None, - Some(r##"Calendar identifier."##), + Some(r##"Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword."##), Some(true), Some(false)), @@ -3554,7 +3554,7 @@ fn main() { vec![ (Some(r##"calendar-id"##), None, - Some(r##"Calendar identifier."##), + Some(r##"Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword."##), Some(true), Some(false)), @@ -3588,7 +3588,7 @@ fn main() { vec![ (Some(r##"calendar-id"##), None, - Some(r##"Calendar identifier."##), + Some(r##"Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword."##), Some(true), Some(false)), @@ -3622,7 +3622,7 @@ fn main() { vec![ (Some(r##"calendar-id"##), None, - Some(r##"Calendar identifier."##), + Some(r##"Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword."##), Some(true), Some(false)), @@ -3653,7 +3653,7 @@ fn main() { vec![ (Some(r##"calendar-id"##), None, - Some(r##"Calendar identifier."##), + Some(r##"Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword."##), Some(true), Some(false)), @@ -3669,7 +3669,7 @@ fn main() { vec![ (Some(r##"calendar-id"##), None, - Some(r##"Calendar identifier."##), + Some(r##"Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword."##), Some(true), Some(false)), @@ -3729,7 +3729,7 @@ fn main() { vec![ (Some(r##"calendar-id"##), None, - Some(r##"Calendar identifier."##), + Some(r##"Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword."##), Some(true), Some(false)), @@ -3757,7 +3757,7 @@ fn main() { vec![ (Some(r##"calendar-id"##), None, - Some(r##"Calendar identifier."##), + Some(r##"Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword."##), Some(true), Some(false)), @@ -3810,7 +3810,7 @@ fn main() { vec![ (Some(r##"calendar-id"##), None, - Some(r##"Calendar identifier."##), + Some(r##"Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword."##), Some(true), Some(false)), @@ -3826,7 +3826,7 @@ fn main() { vec![ (Some(r##"calendar-id"##), None, - Some(r##"Calendar identifier."##), + Some(r##"Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword."##), Some(true), Some(false)), @@ -3842,7 +3842,7 @@ fn main() { vec![ (Some(r##"calendar-id"##), None, - Some(r##"Calendar identifier."##), + Some(r##"Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword."##), Some(true), Some(false)), @@ -3886,7 +3886,7 @@ fn main() { vec![ (Some(r##"calendar-id"##), None, - Some(r##"Calendar identifier."##), + Some(r##"Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword."##), Some(true), Some(false)), @@ -3914,7 +3914,7 @@ fn main() { vec![ (Some(r##"calendar-id"##), None, - Some(r##"Calendar identifier."##), + Some(r##"Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword."##), Some(true), Some(false)), @@ -3983,7 +3983,7 @@ fn main() { vec![ (Some(r##"calendar-id"##), None, - Some(r##"Calendar identifier."##), + Some(r##"Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword."##), Some(true), Some(false)), @@ -4005,7 +4005,7 @@ fn main() { vec![ (Some(r##"calendar-id"##), None, - Some(r##"Calendar identifier."##), + Some(r##"Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword."##), Some(true), Some(false)), @@ -4033,7 +4033,7 @@ fn main() { vec![ (Some(r##"calendar-id"##), None, - Some(r##"Calendar identifier."##), + Some(r##"Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword."##), Some(true), Some(false)), @@ -4061,7 +4061,7 @@ fn main() { vec![ (Some(r##"calendar-id"##), None, - Some(r##"Calendar identifier."##), + Some(r##"Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword."##), Some(true), Some(false)), @@ -4089,7 +4089,7 @@ fn main() { vec![ (Some(r##"calendar-id"##), None, - Some(r##"Calendar identifier."##), + Some(r##"Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword."##), Some(true), Some(false)), @@ -4117,7 +4117,7 @@ fn main() { vec![ (Some(r##"calendar-id"##), None, - Some(r##"Calendar identifier."##), + Some(r##"Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword."##), Some(true), Some(false)), @@ -4173,7 +4173,7 @@ fn main() { vec![ (Some(r##"calendar-id"##), None, - Some(r##"Calendar identifier."##), + Some(r##"Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword."##), Some(true), Some(false)), @@ -4207,7 +4207,7 @@ fn main() { vec![ (Some(r##"calendar-id"##), None, - Some(r##"Calendar identifier."##), + Some(r##"Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword."##), Some(true), Some(false)), @@ -4235,7 +4235,7 @@ fn main() { vec![ (Some(r##"calendar-id"##), None, - Some(r##"Calendar identifier."##), + Some(r##"Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword."##), Some(true), Some(false)), @@ -4269,7 +4269,7 @@ fn main() { vec![ (Some(r##"calendar-id"##), None, - Some(r##"Calendar identifier."##), + Some(r##"Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword."##), Some(true), Some(false)), @@ -4385,7 +4385,7 @@ fn main() { let mut app = App::new("calendar3") .author("Sebastian Thiel ") - .version("0.3.2+20150715") + .version("0.3.2+20151011") .about("Lets you manipulate events and other calendar data.") .after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_calendar3_cli") .arg(Arg::with_name("url") diff --git a/gen/calendar3/Cargo.toml b/gen/calendar3/Cargo.toml index 2aadb9b0ac..60a11ee5f9 100644 --- a/gen/calendar3/Cargo.toml +++ b/gen/calendar3/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-calendar3" -version = "0.1.9+20150715" +version = "0.1.9+20151011" 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" diff --git a/gen/calendar3/README.md b/gen/calendar3/README.md index 3615c0e8e7..2d4d0e4d88 100644 --- a/gen/calendar3/README.md +++ b/gen/calendar3/README.md @@ -5,7 +5,7 @@ DO NOT EDIT ! --> The `google-calendar3` library allows access to all features of the *Google calendar* service. -This documentation was generated from *calendar* crate version *0.1.9+20150715*, where *20150715* is the exact revision of the *calendar:v3* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +This documentation was generated from *calendar* crate version *0.1.9+20151011*, where *20151011* is the exact revision of the *calendar:v3* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. Everything else about the *calendar* *v3* API can be found at the [official documentation site](https://developers.google.com/google-apps/calendar/firstapp). diff --git a/gen/calendar3/src/lib.rs b/gen/calendar3/src/lib.rs index 777ca58265..685b29444b 100644 --- a/gen/calendar3/src/lib.rs +++ b/gen/calendar3/src/lib.rs @@ -2,7 +2,7 @@ // This file was generated automatically from 'src/mako/api/lib.rs.mako' // DO NOT EDIT ! -//! This documentation was generated from *calendar* crate version *0.1.9+20150715*, where *20150715* is the exact revision of the *calendar:v3* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +//! This documentation was generated from *calendar* crate version *0.1.9+20151011*, where *20151011* is the exact revision of the *calendar:v3* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. //! //! Everything else about the *calendar* *v3* API can be found at the //! [official documentation site](https://developers.google.com/google-apps/calendar/firstapp). diff --git a/gen/calendar3/src/lib.rs.in b/gen/calendar3/src/lib.rs.in index 30ef568546..1bc78f6912 100644 --- a/gen/calendar3/src/lib.rs.in +++ b/gen/calendar3/src/lib.rs.in @@ -207,11 +207,11 @@ pub struct EventGadget { pub preferences: Option>, /// The gadget's title. pub title: Option, - /// The gadget's height in pixels. Optional. + /// The gadget's height in pixels. The height must be an integer greater than 0. Optional. pub height: Option, - /// The gadget's width in pixels. Optional. + /// The gadget's width in pixels. The width must be an integer greater than 0. Optional. pub width: Option, - /// The gadget's URL. + /// The gadget's URL. The URL scheme must be HTTPS. pub link: Option, /// The gadget's type. #[serde(rename="type")] @@ -220,7 +220,7 @@ pub struct EventGadget { /// - "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: Option, - /// The gadget's icon URL. + /// The gadget's icon URL. The URL scheme must be HTTPS. #[serde(rename="iconLink")] pub icon_link: Option, } @@ -310,7 +310,7 @@ pub struct EventAttachment { #[serde(rename="fileUrl")] pub file_url: Option, /// ID of the attached file. Read-only. - /// E.g. for Google Drive files this is the ID of the corresponding Files resource entry in the Drive API. + /// For Google Drive files, this is the ID of the corresponding Files resource entry in the Drive API. #[serde(rename="fileId")] pub file_id: Option, /// Attachment title. @@ -342,7 +342,7 @@ pub struct Calendar { pub etag: Option, /// Description of the calendar. Optional. pub description: Option, - /// Identifier of the calendar. + /// Identifier of the calendar. To retrieve IDs call the calendarList.list() method. pub id: Option, /// The time zone of the calendar. (Formatted as an IANA Time Zone Database name, e.g. "Europe/Zurich".) Optional. #[serde(rename="timeZone")] @@ -392,13 +392,13 @@ pub struct CalendarListEntry { 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. + /// The foreground color of the calendar in the hexadecimal format "#ffffff". This property supersedes the index-based colorId property. To set or change this property, you need to specify colorRgbFormat=true in the parameters of the insert, update and patch methods. Optional. #[serde(rename="foregroundColor")] pub foreground_color: Option, /// The default reminders that the authenticated user has for this calendar. #[serde(rename="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. + /// 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). This property is superseded by the backgroundColor and foregroundColor properties and can be ignored when using these properties. Optional. #[serde(rename="colorId")] pub color_id: Option, /// Whether the calendar content shows up in the calendar UI. Optional. The default is False. @@ -409,7 +409,7 @@ pub struct CalendarListEntry { 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. + /// The main color of the calendar in the hexadecimal format "#0088aa". This property supersedes the index-based colorId property. To set or change this property, you need to specify colorRgbFormat=true in the parameters of the insert, update and patch methods. Optional. #[serde(rename="backgroundColor")] pub background_color: Option, /// The summary that the authenticated user has set for this calendar. Optional. @@ -466,7 +466,7 @@ pub struct EventDateTime { /// 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(rename="timeZone")] pub time_zone: Option, - /// 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. + /// The time, as a combined date-time value (formatted according to RFC3339). A time zone offset is required unless a time zone is explicitly specified in timeZone. #[serde(rename="dateTime")] pub date_time: Option, } @@ -515,7 +515,7 @@ pub struct EventCreator { pub display_name: Option, /// The creator's email address, if available. pub email: Option, - /// The creator's Profile ID, if available. + /// The creator's Profile ID, if available. It corresponds to theid field in the People collection of the Google+ API pub id: Option, } @@ -629,7 +629,7 @@ pub struct Events { pub description: Option, /// List of events on the calendar. pub items: Option>, - /// Last modification time of the calendar (as a RFC 3339 timestamp). Read-only. + /// Last modification time of the calendar (as a RFC3339 timestamp). Read-only. pub updated: Option, /// Title of the calendar. Read-only. pub summary: Option, @@ -713,9 +713,9 @@ pub struct EventAttendee { /// Whether this entry represents the calendar on which this copy of the event appears. Read-only. The default is False. #[serde(rename="self")] pub self_: Option, - /// The attendee's email address, if available. This field must be present when adding an attendee. + /// The attendee's email address, if available. This field must be present when adding an attendee. It must be a valid email address as per RFC5322. pub email: Option, - /// The attendee's Profile ID, if available. + /// The attendee's Profile ID, if available. It corresponds to theid field in the People collection of the Google+ API pub id: Option, /// Number of additional guests. Optional. The default is 0. #[serde(rename="additionalGuests")] @@ -759,7 +759,7 @@ impl Part for FreeBusyGroup {} /// #[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. + /// 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. The maximum number of override reminders is 5. pub overrides: Option>, /// Whether the default reminders of the calendar apply to the event. #[serde(rename="useDefault")] @@ -866,13 +866,13 @@ impl ResponseResult for FreeBusyResponse {} /// #[derive(Default, Clone, Debug, Serialize, 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. + /// A global 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: Option>, - /// Last modification time of the color palette (as a RFC 3339 timestamp). Read-only. + /// Last modification time of the color palette (as a RFC3339 timestamp). Read-only. pub updated: Option, /// Type of the resource ("calendar#colors"). pub kind: Option, - /// 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. + /// A global 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: Option>, } @@ -912,13 +912,13 @@ pub struct FreeBusyRequest { 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. +/// Source from which the event was created. For example, a web page, an email message or any document identifiable by an URL with HTTP or HTTPS scheme. Can only be seen or modified 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. + /// URL of the source pointing to a resource. The URL scheme must be HTTP or HTTPS. pub url: Option, /// Title of the source; for example a title of a web page or an email subject. pub title: Option, @@ -940,9 +940,9 @@ pub struct EventOrganizer { /// The organizer's name, if available. #[serde(rename="displayName")] pub display_name: Option, - /// The organizer's email address, if available. + /// The organizer's email address, if available. It must be a valid email address as per RFC5322. pub email: Option, - /// The organizer's Profile ID, if available. + /// The organizer's Profile ID, if available. It corresponds to theid field in the People collection of the Google+ API pub id: Option, } @@ -956,11 +956,11 @@ impl Part for EventOrganizer {} /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct EventReminder { - /// Number of minutes before the start of the event when the reminder should trigger. + /// Number of minutes before the start of the event when the reminder should trigger. Valid values are between 0 and 40320 (4 weeks in minutes). pub minutes: Option, /// The method used by this reminder. Possible values are: /// - "email" - Reminders are sent via email. - /// - "sms" - Reminders are sent via SMS. They are only available for Google Apps for Work, Education, and Government customers. Requests to set SMS reminders for the other accounts will be ignored. + /// - "sms" - Reminders are sent via SMS. These are only available for Google Apps for Work, Education, and Government customers. Requests to set SMS reminders for other account types are ignored. /// - "popup" - Reminders are sent via a UI popup. pub method: Option, } @@ -999,7 +999,7 @@ pub struct CalendarNotification { pub type_: Option, /// 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. Furthermore, SMS reminders are only available for Google Apps for Work, Education, and Government customers. + /// - "sms" - Reminders are sent via SMS. This value is read-only and is ignored on inserts and updates. SMS reminders are only available for Google Apps for Work, Education, and Government customers. pub method: Option, } @@ -1035,10 +1035,12 @@ pub struct Event { 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: + /// Opaque 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. + /// If you do not specify an ID, it will be automatically generated by the server. + /// Note that the icalUID and the id are not identical and only one of them should be supplied at event creation time. One difference in their semantics is that in recurring events, all occurrences of one event have different ids while they all share the same icalUIDs. pub id: Option, /// An absolute link to the Google+ hangout associated with this event. Read-only. #[serde(rename="hangoutLink")] @@ -1046,22 +1048,22 @@ pub struct Event { /// Whether attendees other than the organizer can invite others to the event. Optional. The default is True. #[serde(rename="guestsCanInviteOthers")] pub guests_can_invite_others: Option, - /// The attendees of the event. + /// The attendees of the event. See the Events with attendees guide for more information on scheduling events with other calendar users. 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(rename="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. + /// List of RRULE, EXRULE, RDATE and EXDATE lines for a recurring event, as specified in RFC5545. Note that DTSTART and DTEND lines are not allowed in this field; event start and end times are specified in the start and end fields. 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. + /// Source from which the event was created. For example, a web page, an email message or any document identifiable by an URL with HTTP or HTTPS scheme. Can only be seen or modified 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. + /// For an instance of a recurring event, this is the id of the recurring event to which this instance belongs. Immutable. #[serde(rename="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. @@ -1072,11 +1074,12 @@ pub struct Event { /// - "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. + /// Last modification time of the event (as a RFC3339 timestamp). Read-only. pub updated: Option, /// Description of the event. Optional. pub description: Option, - /// Event ID in the iCalendar format. + /// Event unique identifier as defined in RFC5545. It is used to uniquely identify events accross calendaring systems and must be supplied when importing events via the import method. + /// Note that the icalUID and the id are not identical and only one of them should be supplied at event creation time. One difference in their semantics is that in recurring events, all occurrences of one event have different ids while they all share the same icalUIDs. #[serde(rename="iCalUID")] pub i_cal_uid: Option, /// A gadget that extends this event. @@ -1104,7 +1107,7 @@ pub struct 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. + /// Creation time of the event (as a RFC3339 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(rename="colorId")] @@ -1337,7 +1340,7 @@ impl<'a, C, A> CalendarListMethods<'a, C, A> { /// # Arguments /// /// * `request` - No description provided. - /// * `calendarId` - Calendar identifier. + /// * `calendarId` - Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword. pub fn update(&self, request: CalendarListEntry, calendar_id: &str) -> CalendarListUpdateCall<'a, C, A> { CalendarListUpdateCall { hub: self.hub, @@ -1356,7 +1359,7 @@ impl<'a, C, A> CalendarListMethods<'a, C, A> { /// /// # Arguments /// - /// * `calendarId` - Calendar identifier. + /// * `calendarId` - Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword. pub fn delete(&self, calendar_id: &str) -> CalendarListDeleteCall<'a, C, A> { CalendarListDeleteCall { hub: self.hub, @@ -1373,7 +1376,7 @@ impl<'a, C, A> CalendarListMethods<'a, C, A> { /// /// # Arguments /// - /// * `calendarId` - Calendar identifier. + /// * `calendarId` - Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword. pub fn get(&self, calendar_id: &str) -> CalendarListGetCall<'a, C, A> { CalendarListGetCall { hub: self.hub, @@ -1427,7 +1430,7 @@ impl<'a, C, A> CalendarListMethods<'a, C, A> { /// # Arguments /// /// * `request` - No description provided. - /// * `calendarId` - Calendar identifier. + /// * `calendarId` - Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword. pub fn patch(&self, request: CalendarListEntry, calendar_id: &str) -> CalendarListPatchCall<'a, C, A> { CalendarListPatchCall { hub: self.hub, @@ -1511,7 +1514,7 @@ impl<'a, C, A> CalendarMethods<'a, C, A> { /// # Arguments /// /// * `request` - No description provided. - /// * `calendarId` - Calendar identifier. + /// * `calendarId` - Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword. pub fn patch(&self, request: Calendar, calendar_id: &str) -> CalendarPatchCall<'a, C, A> { CalendarPatchCall { hub: self.hub, @@ -1529,7 +1532,7 @@ impl<'a, C, A> CalendarMethods<'a, C, A> { /// /// # Arguments /// - /// * `calendarId` - Calendar identifier. + /// * `calendarId` - Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword. pub fn delete(&self, calendar_id: &str) -> CalendarDeleteCall<'a, C, A> { CalendarDeleteCall { hub: self.hub, @@ -1546,7 +1549,7 @@ impl<'a, C, A> CalendarMethods<'a, C, A> { /// /// # Arguments /// - /// * `calendarId` - Calendar identifier. + /// * `calendarId` - Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword. pub fn get(&self, calendar_id: &str) -> CalendarGetCall<'a, C, A> { CalendarGetCall { hub: self.hub, @@ -1563,7 +1566,7 @@ impl<'a, C, A> CalendarMethods<'a, C, A> { /// /// # Arguments /// - /// * `calendarId` - Calendar identifier. + /// * `calendarId` - Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword. pub fn clear(&self, calendar_id: &str) -> CalendarClearCall<'a, C, A> { CalendarClearCall { hub: self.hub, @@ -1598,7 +1601,7 @@ impl<'a, C, A> CalendarMethods<'a, C, A> { /// # Arguments /// /// * `request` - No description provided. - /// * `calendarId` - Calendar identifier. + /// * `calendarId` - Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword. pub fn update(&self, request: Calendar, calendar_id: &str) -> CalendarUpdateCall<'a, C, A> { CalendarUpdateCall { hub: self.hub, @@ -1658,7 +1661,7 @@ impl<'a, C, A> AclMethods<'a, C, A> { /// # Arguments /// /// * `request` - No description provided. - /// * `calendarId` - Calendar identifier. + /// * `calendarId` - Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword. pub fn watch(&self, request: Channel, calendar_id: &str) -> AclWatchCall<'a, C, A> { AclWatchCall { hub: self.hub, @@ -1681,7 +1684,7 @@ impl<'a, C, A> AclMethods<'a, C, A> { /// # Arguments /// /// * `request` - No description provided. - /// * `calendarId` - Calendar identifier. + /// * `calendarId` - Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword. pub fn insert(&self, request: AclRule, calendar_id: &str) -> AclInsertCall<'a, C, A> { AclInsertCall { hub: self.hub, @@ -1700,7 +1703,7 @@ impl<'a, C, A> AclMethods<'a, C, A> { /// # Arguments /// /// * `request` - No description provided. - /// * `calendarId` - Calendar identifier. + /// * `calendarId` - Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword. /// * `ruleId` - ACL rule identifier. pub fn update(&self, request: AclRule, calendar_id: &str, rule_id: &str) -> AclUpdateCall<'a, C, A> { AclUpdateCall { @@ -1721,7 +1724,7 @@ impl<'a, C, A> AclMethods<'a, C, A> { /// # Arguments /// /// * `request` - No description provided. - /// * `calendarId` - Calendar identifier. + /// * `calendarId` - Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword. /// * `ruleId` - ACL rule identifier. pub fn patch(&self, request: AclRule, calendar_id: &str, rule_id: &str) -> AclPatchCall<'a, C, A> { AclPatchCall { @@ -1741,7 +1744,7 @@ impl<'a, C, A> AclMethods<'a, C, A> { /// /// # Arguments /// - /// * `calendarId` - Calendar identifier. + /// * `calendarId` - Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword. pub fn list(&self, calendar_id: &str) -> AclListCall<'a, C, A> { AclListCall { hub: self.hub, @@ -1762,7 +1765,7 @@ impl<'a, C, A> AclMethods<'a, C, A> { /// /// # Arguments /// - /// * `calendarId` - Calendar identifier. + /// * `calendarId` - Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword. /// * `ruleId` - ACL rule identifier. pub fn delete(&self, calendar_id: &str, rule_id: &str) -> AclDeleteCall<'a, C, A> { AclDeleteCall { @@ -1781,7 +1784,7 @@ impl<'a, C, A> AclMethods<'a, C, A> { /// /// # Arguments /// - /// * `calendarId` - Calendar identifier. + /// * `calendarId` - Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword. /// * `ruleId` - ACL rule identifier. pub fn get(&self, calendar_id: &str, rule_id: &str) -> AclGetCall<'a, C, A> { AclGetCall { @@ -1952,7 +1955,7 @@ impl<'a, C, A> EventMethods<'a, C, A> { /// /// # Arguments /// - /// * `calendarId` - Calendar identifier. + /// * `calendarId` - Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword. /// * `eventId` - Event identifier. pub fn delete(&self, calendar_id: &str, event_id: &str) -> EventDeleteCall<'a, C, A> { EventDeleteCall { @@ -1973,7 +1976,7 @@ impl<'a, C, A> EventMethods<'a, C, A> { /// # Arguments /// /// * `request` - No description provided. - /// * `calendarId` - Calendar identifier. + /// * `calendarId` - Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword. pub fn insert(&self, request: Event, calendar_id: &str) -> EventInsertCall<'a, C, A> { EventInsertCall { hub: self.hub, @@ -1995,7 +1998,7 @@ impl<'a, C, A> EventMethods<'a, C, A> { /// # Arguments /// /// * `request` - No description provided. - /// * `calendarId` - Calendar identifier. + /// * `calendarId` - Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword. pub fn import(&self, request: Event, calendar_id: &str) -> EventImportCall<'a, C, A> { EventImportCall { hub: self.hub, @@ -2014,7 +2017,7 @@ impl<'a, C, A> EventMethods<'a, C, A> { /// /// # Arguments /// - /// * `calendarId` - Calendar identifier. + /// * `calendarId` - Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword. /// * `eventId` - Recurring event identifier. pub fn instances(&self, calendar_id: &str, event_id: &str) -> EventInstanceCall<'a, C, A> { EventInstanceCall { @@ -2042,7 +2045,7 @@ impl<'a, C, A> EventMethods<'a, C, A> { /// /// # Arguments /// - /// * `calendarId` - Calendar identifier. + /// * `calendarId` - Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword. /// * `eventId` - Event identifier. pub fn get(&self, calendar_id: &str, event_id: &str) -> EventGetCall<'a, C, A> { EventGetCall { @@ -2064,7 +2067,7 @@ impl<'a, C, A> EventMethods<'a, C, A> { /// /// # Arguments /// - /// * `calendarId` - Calendar identifier. + /// * `calendarId` - Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword. pub fn list(&self, calendar_id: &str) -> EventListCall<'a, C, A> { EventListCall { hub: self.hub, @@ -2099,7 +2102,7 @@ impl<'a, C, A> EventMethods<'a, C, A> { /// # Arguments /// /// * `request` - No description provided. - /// * `calendarId` - Calendar identifier. + /// * `calendarId` - Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword. /// * `eventId` - Event identifier. pub fn patch(&self, request: Event, calendar_id: &str, event_id: &str) -> EventPatchCall<'a, C, A> { EventPatchCall { @@ -2146,7 +2149,7 @@ impl<'a, C, A> EventMethods<'a, C, A> { /// # Arguments /// /// * `request` - No description provided. - /// * `calendarId` - Calendar identifier. + /// * `calendarId` - Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword. /// * `eventId` - Event identifier. pub fn update(&self, request: Event, calendar_id: &str, event_id: &str) -> EventUpdateCall<'a, C, A> { EventUpdateCall { @@ -2171,7 +2174,7 @@ impl<'a, C, A> EventMethods<'a, C, A> { /// # Arguments /// /// * `request` - No description provided. - /// * `calendarId` - Calendar identifier. + /// * `calendarId` - Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword. pub fn watch(&self, request: Channel, calendar_id: &str) -> EventWatchCall<'a, C, A> { EventWatchCall { hub: self.hub, @@ -2206,7 +2209,7 @@ impl<'a, C, A> EventMethods<'a, C, A> { /// /// # Arguments /// - /// * `calendarId` - Calendar identifier. + /// * `calendarId` - Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword. /// * `text` - The text describing the event to be created. pub fn quick_add(&self, calendar_id: &str, text: &str) -> EventQuickAddCall<'a, C, A> { EventQuickAddCall { @@ -3424,7 +3427,7 @@ impl<'a, C, A> CalendarListUpdateCall<'a, C, A> where C: BorrowMut CalendarListDeleteCall<'a, C, A> where C: BorrowMut CalendarListGetCall<'a, C, A> where C: BorrowMut, } - /// Calendar identifier. + /// Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword. /// /// Sets the *calendar id* path property to the given value. /// @@ -4689,7 +4692,7 @@ impl<'a, C, A> CalendarListPatchCall<'a, C, A> where C: BorrowMut self._request = new_value; self } - /// Calendar identifier. + /// Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword. /// /// Sets the *calendar id* path property to the given value. /// @@ -5273,7 +5276,7 @@ impl<'a, C, A> CalendarPatchCall<'a, C, A> where C: BorrowMut, A: self._request = new_value; self } - /// Calendar identifier. + /// Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword. /// /// Sets the *calendar id* path property to the given value. /// @@ -5498,7 +5501,7 @@ impl<'a, C, A> CalendarDeleteCall<'a, C, A> where C: BorrowMut, A } - /// Calendar identifier. + /// Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword. /// /// Sets the *calendar id* path property to the given value. /// @@ -5734,7 +5737,7 @@ impl<'a, C, A> CalendarGetCall<'a, C, A> where C: BorrowMut, A: o } - /// Calendar identifier. + /// Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword. /// /// Sets the *calendar id* path property to the given value. /// @@ -5959,7 +5962,7 @@ impl<'a, C, A> CalendarClearCall<'a, C, A> where C: BorrowMut, A: } - /// Calendar identifier. + /// Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword. /// /// Sets the *calendar id* path property to the given value. /// @@ -6460,7 +6463,7 @@ impl<'a, C, A> CalendarUpdateCall<'a, C, A> where C: BorrowMut, A self._request = new_value; self } - /// Calendar identifier. + /// Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword. /// /// Sets the *calendar id* path property to the given value. /// @@ -6747,7 +6750,7 @@ impl<'a, C, A> AclWatchCall<'a, C, A> where C: BorrowMut, A: oaut self._request = new_value; self } - /// Calendar identifier. + /// Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword. /// /// Sets the *calendar id* path property to the given value. /// @@ -7045,7 +7048,7 @@ impl<'a, C, A> AclInsertCall<'a, C, A> where C: BorrowMut, A: oau self._request = new_value; self } - /// Calendar identifier. + /// Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword. /// /// Sets the *calendar id* path property to the given value. /// @@ -7314,7 +7317,7 @@ impl<'a, C, A> AclUpdateCall<'a, C, A> where C: BorrowMut, A: oau self._request = new_value; self } - /// Calendar identifier. + /// Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword. /// /// Sets the *calendar id* path property to the given value. /// @@ -7593,7 +7596,7 @@ impl<'a, C, A> AclPatchCall<'a, C, A> where C: BorrowMut, A: oaut self._request = new_value; self } - /// Calendar identifier. + /// Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword. /// /// Sets the *calendar id* path property to the given value. /// @@ -7859,7 +7862,7 @@ impl<'a, C, A> AclListCall<'a, C, A> where C: BorrowMut, A: oauth } - /// Calendar identifier. + /// Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword. /// /// Sets the *calendar id* path property to the given value. /// @@ -8117,7 +8120,7 @@ impl<'a, C, A> AclDeleteCall<'a, C, A> where C: BorrowMut, A: oau } - /// Calendar identifier. + /// Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword. /// /// Sets the *calendar id* path property to the given value. /// @@ -8365,7 +8368,7 @@ impl<'a, C, A> AclGetCall<'a, C, A> where C: BorrowMut, A: oauth2 } - /// Calendar identifier. + /// Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword. /// /// Sets the *calendar id* path property to the given value. /// @@ -9033,7 +9036,7 @@ impl<'a, C, A> EventDeleteCall<'a, C, A> where C: BorrowMut, A: o } - /// Calendar identifier. + /// Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword. /// /// Sets the *calendar id* path property to the given value. /// @@ -9332,7 +9335,7 @@ impl<'a, C, A> EventInsertCall<'a, C, A> where C: BorrowMut, A: o self._request = new_value; self } - /// Calendar identifier. + /// Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword. /// /// Sets the *calendar id* path property to the given value. /// @@ -9625,7 +9628,7 @@ impl<'a, C, A> EventImportCall<'a, C, A> where C: BorrowMut, A: o self._request = new_value; self } - /// Calendar identifier. + /// Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword. /// /// Sets the *calendar id* path property to the given value. /// @@ -9915,7 +9918,7 @@ impl<'a, C, A> EventInstanceCall<'a, C, A> where C: BorrowMut, A: } - /// Calendar identifier. + /// Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword. /// /// Sets the *calendar id* path property to the given value. /// @@ -9942,14 +9945,14 @@ impl<'a, C, A> EventInstanceCall<'a, C, A> where C: BorrowMut, A: self._time_zone = Some(new_value.to_string()); self } - /// Lower bound (inclusive) for an event's end time to filter by. Optional. The default is not to filter by end time. + /// Lower bound (inclusive) for an event's end time to filter by. Optional. The default is not to filter by end time. Must be an RFC3339 timestamp with mandatory time zone offset. /// /// Sets the *time min* query property to the given value. pub fn time_min(mut self, new_value: &str) -> EventInstanceCall<'a, C, A> { self._time_min = Some(new_value.to_string()); self } - /// Upper bound (exclusive) for an event's start time to filter by. Optional. The default is not to filter by start time. + /// Upper bound (exclusive) for an event's start time to filter by. Optional. The default is not to filter by start time. Must be an RFC3339 timestamp with mandatory time zone offset. /// /// Sets the *time max* query property to the given value. pub fn time_max(mut self, new_value: &str) -> EventInstanceCall<'a, C, A> { @@ -10241,7 +10244,7 @@ impl<'a, C, A> EventGetCall<'a, C, A> where C: BorrowMut, A: oaut } - /// Calendar identifier. + /// Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword. /// /// Sets the *calendar id* path property to the given value. /// @@ -10601,7 +10604,7 @@ impl<'a, C, A> EventListCall<'a, C, A> where C: BorrowMut, A: oau } - /// Calendar identifier. + /// Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword. /// /// Sets the *calendar id* path property to the given value. /// @@ -10611,7 +10614,7 @@ impl<'a, C, A> EventListCall<'a, C, A> where C: BorrowMut, A: oau self._calendar_id = new_value.to_string(); self } - /// 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. + /// Lower bound for an event's last modification time (as a RFC3339 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. /// /// Sets the *updated min* query property to the given value. pub fn updated_min(mut self, new_value: &str) -> EventListCall<'a, C, A> { @@ -10625,14 +10628,14 @@ impl<'a, C, A> EventListCall<'a, C, A> where C: BorrowMut, A: oau self._time_zone = Some(new_value.to_string()); self } - /// Lower bound (inclusive) for an event's end time to filter by. Optional. The default is not to filter by end time. + /// Lower bound (inclusive) for an event's end time to filter by. Optional. The default is not to filter by end time. Must be an RFC3339 timestamp with mandatory time zone offset, e.g., 2011-06-03T10:00:00-07:00, 2011-06-03T10:00:00Z. Milliseconds may be provided but will be ignored. /// /// Sets the *time min* query property to the given value. pub fn time_min(mut self, new_value: &str) -> EventListCall<'a, C, A> { self._time_min = Some(new_value.to_string()); self } - /// Upper bound (exclusive) for an event's start time to filter by. Optional. The default is not to filter by start time. + /// Upper bound (exclusive) for an event's start time to filter by. Optional. The default is not to filter by start time. Must be an RFC3339 timestamp with mandatory time zone offset, e.g., 2011-06-03T10:00:00-07:00, 2011-06-03T10:00:00Z. Milliseconds may be provided but will be ignored. /// /// Sets the *time max* query property to the given value. pub fn time_max(mut self, new_value: &str) -> EventListCall<'a, C, A> { @@ -11024,7 +11027,7 @@ impl<'a, C, A> EventPatchCall<'a, C, A> where C: BorrowMut, A: oa self._request = new_value; self } - /// Calendar identifier. + /// Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword. /// /// Sets the *calendar id* path property to the given value. /// @@ -11623,7 +11626,7 @@ impl<'a, C, A> EventUpdateCall<'a, C, A> where C: BorrowMut, A: o self._request = new_value; self } - /// Calendar identifier. + /// Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword. /// /// Sets the *calendar id* path property to the given value. /// @@ -12021,7 +12024,7 @@ impl<'a, C, A> EventWatchCall<'a, C, A> where C: BorrowMut, A: oa self._request = new_value; self } - /// Calendar identifier. + /// Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword. /// /// Sets the *calendar id* path property to the given value. /// @@ -12031,7 +12034,7 @@ impl<'a, C, A> EventWatchCall<'a, C, A> where C: BorrowMut, A: oa self._calendar_id = new_value.to_string(); self } - /// 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. + /// Lower bound for an event's last modification time (as a RFC3339 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. /// /// Sets the *updated min* query property to the given value. pub fn updated_min(mut self, new_value: &str) -> EventWatchCall<'a, C, A> { @@ -12045,14 +12048,14 @@ impl<'a, C, A> EventWatchCall<'a, C, A> where C: BorrowMut, A: oa self._time_zone = Some(new_value.to_string()); self } - /// Lower bound (inclusive) for an event's end time to filter by. Optional. The default is not to filter by end time. + /// Lower bound (inclusive) for an event's end time to filter by. Optional. The default is not to filter by end time. Must be an RFC3339 timestamp with mandatory time zone offset, e.g., 2011-06-03T10:00:00-07:00, 2011-06-03T10:00:00Z. Milliseconds may be provided but will be ignored. /// /// Sets the *time min* query property to the given value. pub fn time_min(mut self, new_value: &str) -> EventWatchCall<'a, C, A> { self._time_min = Some(new_value.to_string()); self } - /// Upper bound (exclusive) for an event's start time to filter by. Optional. The default is not to filter by start time. + /// Upper bound (exclusive) for an event's start time to filter by. Optional. The default is not to filter by start time. Must be an RFC3339 timestamp with mandatory time zone offset, e.g., 2011-06-03T10:00:00-07:00, 2011-06-03T10:00:00Z. Milliseconds may be provided but will be ignored. /// /// Sets the *time max* query property to the given value. pub fn time_max(mut self, new_value: &str) -> EventWatchCall<'a, C, A> { @@ -12398,7 +12401,7 @@ impl<'a, C, A> EventQuickAddCall<'a, C, A> where C: BorrowMut, A: } - /// Calendar identifier. + /// Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the "primary" keyword. /// /// Sets the *calendar id* path property to the given value. /// diff --git a/gen/civicinfo2-cli/Cargo.toml b/gen/civicinfo2-cli/Cargo.toml index c54a33fe6c..9b7bdd7ff1 100644 --- a/gen/civicinfo2-cli/Cargo.toml +++ b/gen/civicinfo2-cli/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-civicinfo2-cli" -version = "0.3.2+20150707" +version = "0.3.2+20150820" authors = ["Sebastian Thiel "] description = "A complete library to interact with Civic Info (protocol v2)" repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/civicinfo2-cli" diff --git a/gen/civicinfo2-cli/README.md b/gen/civicinfo2-cli/README.md index b4d7c536ed..6fee331824 100644 --- a/gen/civicinfo2-cli/README.md +++ b/gen/civicinfo2-cli/README.md @@ -24,7 +24,7 @@ Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/ma # Usage -This documentation was generated from the *Civic Info* API at revision *20150707*. The CLI is at version *0.3.2*. +This documentation was generated from the *Civic Info* API at revision *20150820*. The CLI is at version *0.3.2*. ```bash civicinfo2 [options] diff --git a/gen/civicinfo2-cli/mkdocs.yml b/gen/civicinfo2-cli/mkdocs.yml index c81c7b9ae9..e859aba945 100644 --- a/gen/civicinfo2-cli/mkdocs.yml +++ b/gen/civicinfo2-cli/mkdocs.yml @@ -1,4 +1,4 @@ -site_name: Civic Info v0.3.2+20150707 +site_name: Civic Info v0.3.2+20150820 site_url: http://byron.github.io/google-apis-rs/google-civicinfo2-cli site_description: Write integrating applications with bcore diff --git a/gen/civicinfo2-cli/src/main.rs b/gen/civicinfo2-cli/src/main.rs index 710a614835..19d5fc3742 100644 --- a/gen/civicinfo2-cli/src/main.rs +++ b/gen/civicinfo2-cli/src/main.rs @@ -555,7 +555,7 @@ fn main() { let mut app = App::new("civicinfo2") .author("Sebastian Thiel ") - .version("0.3.2+20150707") + .version("0.3.2+20150820") .about("An API for accessing civic information.") .after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_civicinfo2_cli") .arg(Arg::with_name("folder") diff --git a/gen/civicinfo2/Cargo.toml b/gen/civicinfo2/Cargo.toml index 5be4f02584..e69f15dd35 100644 --- a/gen/civicinfo2/Cargo.toml +++ b/gen/civicinfo2/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-civicinfo2" -version = "0.1.9+20150707" +version = "0.1.9+20150820" authors = ["Sebastian Thiel "] description = "A complete library to interact with Civic Info (protocol v2)" repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/civicinfo2" diff --git a/gen/civicinfo2/README.md b/gen/civicinfo2/README.md index ea113184ef..496edd931a 100644 --- a/gen/civicinfo2/README.md +++ b/gen/civicinfo2/README.md @@ -5,7 +5,7 @@ DO NOT EDIT ! --> The `google-civicinfo2` library allows access to all features of the *Google Civic Info* service. -This documentation was generated from *Civic Info* crate version *0.1.9+20150707*, where *20150707* is the exact revision of the *civicinfo:v2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +This documentation was generated from *Civic Info* crate version *0.1.9+20150820*, where *20150820* is the exact revision of the *civicinfo:v2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. Everything else about the *Civic Info* *v2* API can be found at the [official documentation site](https://developers.google.com/civic-information). diff --git a/gen/civicinfo2/src/lib.rs b/gen/civicinfo2/src/lib.rs index a38468bcfb..6c51bbcf8e 100644 --- a/gen/civicinfo2/src/lib.rs +++ b/gen/civicinfo2/src/lib.rs @@ -2,7 +2,7 @@ // This file was generated automatically from 'src/mako/api/lib.rs.mako' // DO NOT EDIT ! -//! This documentation was generated from *Civic Info* crate version *0.1.9+20150707*, where *20150707* is the exact revision of the *civicinfo:v2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +//! This documentation was generated from *Civic Info* crate version *0.1.9+20150820*, where *20150820* is the exact revision of the *civicinfo:v2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. //! //! Everything else about the *Civic Info* *v2* API can be found at the //! [official documentation site](https://developers.google.com/civic-information). diff --git a/gen/civicinfo2/src/lib.rs.in b/gen/civicinfo2/src/lib.rs.in index 8dba27501b..a0f4f5ceb1 100644 --- a/gen/civicinfo2/src/lib.rs.in +++ b/gen/civicinfo2/src/lib.rs.in @@ -266,7 +266,7 @@ pub struct Contest { pub referendum_text: Option, /// The name of the office for this contest. pub office: Option, - /// Specifies a short summary of the referendum that is on the ballot below the title but above the text. This field is only populated for contests of type 'Referendum'. + /// Specifies a short summary of the referendum that is typically on the ballot below the title but above the text. This field is only populated for contests of type 'Referendum'. #[serde(rename="referendumBrief")] pub referendum_brief: Option, /// A list of sources for this contest. If multiple sources are listed, the data has been aggregated from those sources. @@ -688,6 +688,9 @@ pub struct Election { pub id: Option, /// A displayable name for the election. pub name: Option, + /// The political division of the election. Represented as an OCD Division ID. Voters within these political jurisdictions are covered by this election. This is typically a state such as ocd-division/country:us/state:ca or for the midterms or general election the entire US (i.e. ocd-division/country:us). + #[serde(rename="ocdDivisionId")] + pub ocd_division_id: Option, } impl Resource for Election {} diff --git a/gen/classroom1-cli/Cargo.toml b/gen/classroom1-cli/Cargo.toml new file mode 100644 index 0000000000..71ecf6f44b --- /dev/null +++ b/gen/classroom1-cli/Cargo.toml @@ -0,0 +1,35 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-classroom1-cli" +version = "0.3.2+20151013" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with classroom (protocol v1)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/classroom1-cli" +homepage = "https://developers.google.com/classroom/" +documentation = "http://byron.github.io/google-apis-rs/google_classroom1_cli" +license = "MIT" +keywords = ["classroom", "google", "cli"] + +[[bin]] +name = "classroom1" + +[dependencies] +hyper = ">= 0.6.8" +mime = "0.1.0" +serde = ">= 0.6.0" +serde_json = ">= 0.6.0" +yup-oauth2 = "*" +strsim = "*" +yup-hyper-mock = ">=1.0.0" +clap = ">= 1.0.3" + +[build-dependencies] +syntex = { version = "*" } +serde_codegen = { version = "*" } + + +[dependencies.google-classroom1] +path = "../classroom1" diff --git a/gen/classroom1-cli/LICENSE.md b/gen/classroom1-cli/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/classroom1-cli/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/classroom1-cli/README.md b/gen/classroom1-cli/README.md new file mode 100644 index 0000000000..dddaa48178 --- /dev/null +++ b/gen/classroom1-cli/README.md @@ -0,0 +1,137 @@ + +The `classroom1` command-line interface *(CLI)* allows to use most features of the *Google classroom* service from the comfort of your terminal. + +By default all output is printed to standard out, but flags can be set to direct it into a file independent of your shell's +capabilities. Errors will be printed to standard error, and cause the program's exit code to be non-zero. + +If data-structures are requested, these will be returned as pretty-printed JSON, to be useful as input to other tools. + +Everything else about the *classroom* API can be found at the +[official documentation site](https://developers.google.com/classroom/). + +# Downloads + +You can download the pre-compiled 64bit binaries for the following platforms: + +* ![icon](http://megaicons.net/static/img/icons_sizes/6/140/16/ubuntu-icon.png) [ubuntu](http://dl.byronimo.de/google.rs/cli/0.3.2/ubuntu/classroom1.tar.gz) +* ![icon](http://hydra-media.cursecdn.com/wow.gamepedia.com/a/a2/Apple-icon-16x16.png?version=25ddd67ac3dd3b634478e3978b76cb74) [osx](http://dl.byronimo.de/google.rs/cli/0.3.2/osx/classroom1.tar.gz) + +Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/classroom1-cli). + +# Usage + +This documentation was generated from the *classroom* API at revision *20151013*. The CLI is at version *0.3.2*. + +```bash +classroom1 [options] + courses + aliases-create (-r )... [-p ]... [-o ] + aliases-delete [-p ]... [-o ] + aliases-list [-p ]... [-o ] + create (-r )... [-p ]... [-o ] + delete [-p ]... [-o ] + get [-p ]... [-o ] + list [-p ]... [-o ] + patch (-r )... [-p ]... [-o ] + students-create (-r )... [-p ]... [-o ] + students-delete [-p ]... [-o ] + students-get [-p ]... [-o ] + students-list [-p ]... [-o ] + teachers-create (-r )... [-p ]... [-o ] + teachers-delete [-p ]... [-o ] + teachers-get [-p ]... [-o ] + teachers-list [-p ]... [-o ] + update (-r )... [-p ]... [-o ] + invitations + accept [-p ]... [-o ] + create (-r )... [-p ]... [-o ] + delete [-p ]... [-o ] + get [-p ]... [-o ] + list [-p ]... [-o ] + user-profiles + get [-p ]... [-o ] + classroom1 --help + +Configuration: + [--scope ]... + Specify the authentication a method should be executed in. Each scope + requires the user to grant this application permission to use it. + If unset, it defaults to the shortest scope url for a particular method. + --config-dir + A directory into which we will store our persistent data. Defaults to + a user-writable directory that we will create during the first invocation. + [default: ~/.google-service-cli] + --debug + Output all server communication to standard error. `tx` and `rx` are placed + into the same stream. + --debug-auth + Output all communication related to authentication to standard error. `tx` + and `rx` are placed into the same stream. + +``` + +# Configuration + +The program will store all persistent data in the `~/.google-service-cli` directory in *JSON* files prefixed with `classroom1-`. You can change the directory used to store configuration with the `--config-dir` flag on a per-invocation basis. + +More information about the various kinds of persistent data are given in the following paragraphs. + +# Authentication + +Most APIs require a user to authenticate any request. If this is the case, the [scope][scopes] determines the +set of permissions granted. The granularity of these is usually no more than *read-only* or *full-access*. + +If not set, the system will automatically select the smallest feasible scope, e.g. when invoking a +method that is read-only, it will ask only for a read-only scope. +You may use the `--scope` flag to specify a scope directly. +All applicable scopes are documented in the respective method's CLI documentation. + +The first time a scope is used, the user is asked for permission. Follow the instructions given +by the CLI to grant permissions, or to decline. + +If a scope was authenticated by the user, the respective information will be stored as *JSON* in the configuration +directory, e.g. `~/.google-service-cli/classroom1-token-.json`. No manual management of these tokens +is necessary. + +To revoke granted authentication, please refer to the [official documentation][revoke-access]. + +# Application Secrets + +In order to allow any application to use Google services, it will need to be registered using the +[Google Developer Console][google-dev-console]. APIs the application may use are then enabled for it +one by one. Most APIs can be used for free and have a daily quota. + +To allow more comfortable usage of the CLI without forcing anyone to register an own application, the CLI +comes with a default application secret that is configured accordingly. This also means that heavy usage +all around the world may deplete the daily quota. + +You can workaround this limitation by putting your own secrets file at this location: +`~/.google-service-cli/classroom1-secret.json`, assuming that the required *classroom* API +was enabled for it. Such a secret file can be downloaded in the *Google Developer Console* at +*APIs & auth -> Credentials -> Download JSON* and used as is. + +Learn more about how to setup Google projects and enable APIs using the [official documentation][google-project-new]. + + +# Debugging + +Even though the CLI does its best to provide usable error messages, sometimes it might be desirable to know +what exactly led to a particular issue. This is done by allowing all client-server communication to be +output to standard error *as-is*. + +The `--debug` flag will print all client-server communication to standard error, whereas the `--debug-auth` flag +will cause all communication related to authentication to standard error. +If the `--debug` flag is set, error-results will be debug-printed, possibly yielding more information about the +issue at hand. + +You may consider redirecting standard error into a file for ease of use, e.g. `classroom1 --debug [options] 2>debug.txt`. + + +[scopes]: https://developers.google.com/+/api/oauth#scopes +[revoke-access]: http://webapps.stackexchange.com/a/30849 +[google-dev-console]: https://console.developers.google.com/ +[google-project-new]: https://developers.google.com/console/help/new/ \ No newline at end of file diff --git a/gen/classroom1-cli/mkdocs.yml b/gen/classroom1-cli/mkdocs.yml new file mode 100644 index 0000000000..22471e0cee --- /dev/null +++ b/gen/classroom1-cli/mkdocs.yml @@ -0,0 +1,39 @@ +site_name: classroom v0.3.2+20151013 +site_url: http://byron.github.io/google-apis-rs/google-classroom1-cli +site_description: Write integrating applications with bcore + +repo_url: https://github.com/Byron/google-apis-rs/tree/master/gen/classroom1-cli + +docs_dir: docs +site_dir: build_html + +pages: +- ['index.md', 'Home'] +- ['courses_aliases-create.md', 'Courses', 'Aliases Create'] +- ['courses_aliases-delete.md', 'Courses', 'Aliases Delete'] +- ['courses_aliases-list.md', 'Courses', 'Aliases List'] +- ['courses_create.md', 'Courses', 'Create'] +- ['courses_delete.md', 'Courses', 'Delete'] +- ['courses_get.md', 'Courses', 'Get'] +- ['courses_list.md', 'Courses', 'List'] +- ['courses_patch.md', 'Courses', 'Patch'] +- ['courses_students-create.md', 'Courses', 'Students Create'] +- ['courses_students-delete.md', 'Courses', 'Students Delete'] +- ['courses_students-get.md', 'Courses', 'Students Get'] +- ['courses_students-list.md', 'Courses', 'Students List'] +- ['courses_teachers-create.md', 'Courses', 'Teachers Create'] +- ['courses_teachers-delete.md', 'Courses', 'Teachers Delete'] +- ['courses_teachers-get.md', 'Courses', 'Teachers Get'] +- ['courses_teachers-list.md', 'Courses', 'Teachers List'] +- ['courses_update.md', 'Courses', 'Update'] +- ['invitations_accept.md', 'Invitations', 'Accept'] +- ['invitations_create.md', 'Invitations', 'Create'] +- ['invitations_delete.md', 'Invitations', 'Delete'] +- ['invitations_get.md', 'Invitations', 'Get'] +- ['invitations_list.md', 'Invitations', 'List'] +- ['user-profiles_get.md', 'User Profiles', 'Get'] + +theme: readthedocs + +copyright: Copyright © 2015, `Sebastian Thiel` + diff --git a/gen/classroom1-cli/src/cmn.rs b/gen/classroom1-cli/src/cmn.rs new file mode 100644 index 0000000000..8358f156fa --- /dev/null +++ b/gen/classroom1-cli/src/cmn.rs @@ -0,0 +1,721 @@ +// COPY OF 'src/rust/cli/cmn.rs' +// DO NOT EDIT +use oauth2::{ApplicationSecret, ConsoleApplicationSecret, TokenStorage, Token}; +use serde_json as json; +use serde_json::value::Value; +use mime::Mime; +use clap::{App, SubCommand}; +use strsim; + +use std::fs; +use std::env; +use std::io; +use std::fmt; +use std::path::{Path, PathBuf}; +use std::str::FromStr; +use std::string::ToString; +use std::io::{Write, Read, stdout}; + +use std::default::Default; + +const FIELD_SEP: char = '.'; + + +pub enum ComplexType { + Pod, + Vec, + Map, +} + + // Null, + // Bool(bool), + // I64(i64), + // U64(u64), + // F64(f64), + // String(String), + +pub enum JsonType { + Boolean, + Int, + Uint, + Float, + String, +} + +pub struct JsonTypeInfo { + pub jtype: JsonType, + pub ctype: ComplexType, +} + +// Based on @erickt user comment. Thanks for the idea ! +// Remove all keys whose values are null from given value (changed in place) +pub fn remove_json_null_values(value: &mut Value) { + match *value { + Value::Object(ref mut map) => { + let mut for_removal = Vec::new(); + + for (key, mut value) in map.iter_mut() { + if value.is_null() { + for_removal.push(key.clone()); + } else { + remove_json_null_values(&mut value); + } + } + + for key in &for_removal { + map.remove(key); + } + } + _ => {} + } +} + +fn did_you_mean<'a>(v: &str, possible_values: &[&'a str]) -> Option<&'a str> { + + let mut candidate: Option<(f64, &str)> = None; + for pv in possible_values { + let confidence = strsim::jaro_winkler(v, pv); + if confidence > 0.8 && (candidate.is_none() || (candidate.as_ref().unwrap().0 < confidence)) { + candidate = Some((confidence, pv)); + } + } + match candidate { + None => None, + Some((_, candidate)) => Some(candidate), + } +} + +pub enum CallType { + Upload(UploadProtocol), + Standard, +} + +arg_enum!{ + pub enum UploadProtocol { + Simple, + Resumable + } +} + +impl AsRef for UploadProtocol { + fn as_ref(&self) -> &str { + match *self { + UploadProtocol::Simple => "simple", + UploadProtocol::Resumable => "resumable" + } + } +} + +impl AsRef for CallType { + fn as_ref(&self) -> &str { + match *self { + CallType::Upload(ref proto) => proto.as_ref(), + CallType::Standard => "standard-request" + } + } +} + +#[derive(Clone, Default)] +pub struct FieldCursor(Vec); + +impl ToString for FieldCursor { + fn to_string(&self) -> String { + self.0.join(".") + } +} + +impl From<&'static str> for FieldCursor { + fn from(value: &'static str) -> FieldCursor { + let mut res = FieldCursor::default(); + res.set(value).unwrap(); + res + } +} + +impl FieldCursor { + pub fn set(&mut self, value: &str) -> Result<(), CLIError> { + if value.len() == 0 { + return Err(CLIError::Field(FieldError::Empty)) + } + + let mut first_is_field_sep = false; + let mut char_count: usize = 0; + let mut last_c = FIELD_SEP; + let mut num_conscutive_field_seps = 0; + + let mut field = String::new(); + let mut fields = self.0.clone(); + + let push_field = |fs: &mut Vec, f: &mut String| { + if f.len() > 0 { + fs.push(f.clone()); + f.truncate(0); + } + }; + + for (cid, c) in value.chars().enumerate() { + char_count += 1; + + if c == FIELD_SEP { + if cid == 0 { + first_is_field_sep = true; + } + num_conscutive_field_seps += 1; + if cid > 0 && last_c == FIELD_SEP { + if fields.pop().is_none() { + return Err(CLIError::Field(FieldError::PopOnEmpty(value.to_string()))) + } + } else { + push_field(&mut fields, &mut field); + } + } else { + num_conscutive_field_seps = 0; + if cid == 1 { + if first_is_field_sep { + fields.truncate(0); + } + } + field.push(c); + } + + last_c = c; + } + + push_field(&mut fields, &mut field); + + if char_count == 1 && first_is_field_sep { + fields.truncate(0); + } + if char_count > 1 && num_conscutive_field_seps == 1 { + return Err(CLIError::Field(FieldError::TrailingFieldSep(value.to_string()))) + } + + self.0 = fields; + Ok(()) + } + + pub fn did_you_mean(value: &str, possible_values: &[&str]) -> Option { + if value.len() == 0 { + return None + } + + let mut last_c = FIELD_SEP; + + let mut field = String::new(); + let mut output = String::new(); + + let push_field = |fs: &mut String, f: &mut String| { + if f.len() > 0 { + fs.push_str( + match did_you_mean(&f, possible_values) { + Some(candidate) => candidate, + None => &f, + }); + f.truncate(0); + } + }; + + for (cid, c) in value.chars().enumerate() { + if c == FIELD_SEP { + if last_c != FIELD_SEP { + push_field(&mut output, &mut field); + } + output.push(c); + } else { + field.push(c); + } + + last_c = c; + } + + push_field(&mut output, &mut field); + + if &output == value { + None + } else { + Some(output) + } + } + + pub fn set_json_value(&self, mut object: &mut Value, + value: &str, type_info: JsonTypeInfo, + err: &mut InvalidOptionsError, + orig_cursor: &FieldCursor) { + assert!(self.0.len() > 0); + + for field in &self.0[..self.0.len()-1] { + let tmp = object; + object = + match *tmp { + Value::Object(ref mut mapping) => { + mapping.entry(field.to_owned()).or_insert( + Value::Object(Default::default()) + ) + }, + _ => panic!("We don't expect non-object Values here ...") + }; + } + + match *object { + Value::Object(ref mut mapping) => { + let field = &self.0[self.0.len()-1]; + let to_jval = + |value: &str, jtype: JsonType, err: &mut InvalidOptionsError| + -> Value { + match jtype { + JsonType::Boolean => + Value::Bool(arg_from_str(value, err, &field, "boolean")), + JsonType::Int => + Value::I64(arg_from_str(value, err, &field, "int")), + JsonType::Uint => + Value::U64(arg_from_str(value, err, &field, "uint")), + JsonType::Float => + Value::F64(arg_from_str(value, err, &field, "float")), + JsonType::String => + Value::String(value.to_owned()), + } + }; + + match type_info.ctype { + ComplexType::Pod => { + if mapping.insert(field.to_owned(), to_jval(value, type_info.jtype, err)).is_some() { + err.issues.push(CLIError::Field(FieldError::Duplicate(orig_cursor.to_string()))); + } + }, + ComplexType::Vec => { + match *mapping.entry(field.to_owned()) + .or_insert(Value::Array(Default::default())) { + Value::Array(ref mut values) => values.push(to_jval(value, type_info.jtype, err)), + _ => unreachable!() + } + }, + ComplexType::Map => { + let (key, value) = parse_kv_arg(value, err, true); + let jval = to_jval(value.unwrap_or(""), type_info.jtype, err); + + match *mapping.entry(field.to_owned()) + .or_insert(Value::Object(Default::default())) { + Value::Object(ref mut value_map) => { + if value_map.insert(key.to_owned(), jval).is_some() { + err.issues.push(CLIError::Field(FieldError::Duplicate(orig_cursor.to_string()))); + } + } + _ => unreachable!() + } + } + } + }, + _ => unreachable!() + } + } + + pub fn num_fields(&self) -> usize { + self.0.len() + } +} + +pub fn parse_kv_arg<'a>(kv: &'a str, err: &mut InvalidOptionsError, for_hashmap: bool) + -> (&'a str, Option<&'a str>) { + let mut add_err = || err.issues.push(CLIError::InvalidKeyValueSyntax(kv.to_string(),for_hashmap)); + match kv.find('=') { + None => { + add_err(); + return (kv, None) + }, + Some(pos) => { + let key = &kv[..pos]; + if kv.len() <= pos + 1 { + add_err(); + return (key, Some("")) + } + (key, Some(&kv[pos+1..])) + } + } +} + +pub fn calltype_from_str(name: &str, valid_protocols: Vec, err: &mut InvalidOptionsError) -> CallType { + CallType::Upload( + match UploadProtocol::from_str(name) { + Ok(up) => up, + Err(msg) => { + err.issues.push(CLIError::InvalidUploadProtocol(name.to_string(), valid_protocols)); + UploadProtocol::Simple + } + }) +} + +pub fn input_file_from_opts(file_path: &str, err: &mut InvalidOptionsError) -> Option { + match fs::File::open(file_path) { + Ok(f) => Some(f), + Err(io_err) => { + err.issues.push(CLIError::Input(InputError::IOError((file_path.to_string(), io_err)))); + None + } + } +} + +pub fn input_mime_from_opts(mime: &str, err: &mut InvalidOptionsError) -> Option { + match mime.parse() { + Ok(m) => Some(m), + Err(_) => { + err.issues.push(CLIError::Input(InputError::Mime(mime.to_string()))); + None + } + } +} + +pub fn writer_from_opts(arg: Option<&str>) -> Result, io::Error> { + let f = arg.unwrap_or("-"); + match f { + "-" => Ok(Box::new(stdout())), + _ => match fs::OpenOptions::new().create(true).write(true).open(f) { + Ok(f) => Ok(Box::new(f)), + Err(io_err) => Err(io_err), + } + } +} + + +pub fn arg_from_str<'a, T>(arg: &str, err: &mut InvalidOptionsError, + arg_name: &'a str, + arg_type: &'a str) -> T + where T: FromStr + Default, + ::Err: fmt::Display { + match FromStr::from_str(arg) { + Err(perr) => { + err.issues.push( + CLIError::ParseError(arg_name.to_owned(), arg_type.to_owned(), arg.to_string(), format!("{}", perr)) + ); + Default::default() + }, + Ok(v) => v, + } +} + +pub struct JsonTokenStorage { + pub program_name: &'static str, + pub db_dir: String, +} + +impl JsonTokenStorage { + fn path(&self, scope_hash: u64) -> PathBuf { + Path::new(&self.db_dir).join(&format!("{}-token-{}.json", self.program_name, scope_hash)) + } +} + +impl TokenStorage for JsonTokenStorage { + type Error = json::Error; + + // NOTE: logging might be interesting, currently we swallow all errors + fn set(&mut self, scope_hash: u64, _: &Vec<&str>, token: Option) -> Result<(), json::Error> { + match token { + None => { + match fs::remove_file(self.path(scope_hash)) { + Err(err) => + match err.kind() { + io::ErrorKind::NotFound => Ok(()), + _ => Err(json::Error::IoError(err)) + }, + Ok(_) => Ok(()), + } + } + Some(token) => { + match fs::OpenOptions::new().create(true).write(true).open(&self.path(scope_hash)) { + Ok(mut f) => { + match json::to_writer_pretty(&mut f, &token) { + Ok(_) => Ok(()), + Err(serde_err) => Err(serde_err), + } + }, + Err(io_err) => Err(json::Error::IoError(io_err)) + } + } + } + } + + fn get(&self, scope_hash: u64, _: &Vec<&str>) -> Result, json::Error> { + match fs::File::open(&self.path(scope_hash)) { + Ok(mut f) => { + match json::de::from_reader(f) { + Ok(token) => Ok(Some(token)), + Err(err) => Err(err), + } + }, + Err(io_err) => { + match io_err.kind() { + io::ErrorKind::NotFound => Ok(None), + _ => Err(json::Error::IoError(io_err)) + } + } + } + } +} + + +#[derive(Debug)] +pub enum ApplicationSecretError { + DecoderError((String, json::Error)), + FormatError(String), +} + +impl fmt::Display for ApplicationSecretError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + ApplicationSecretError::DecoderError((ref path, ref err)) + => writeln!(f, "Could not decode file at '{}' with error: {}.", + path, err), + ApplicationSecretError::FormatError(ref path) + => writeln!(f, "'installed' field is unset in secret file at '{}'.", + path), + } + } +} + +#[derive(Debug)] +pub enum ConfigurationError { + DirectoryCreationFailed((String, io::Error)), + DirectoryUnset, + HomeExpansionFailed(String), + Secret(ApplicationSecretError), + IOError((String, io::Error)), +} + +impl fmt::Display for ConfigurationError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + ConfigurationError::DirectoryCreationFailed((ref dir, ref err)) + => writeln!(f, "Directory '{}' could not be created with error: {}.", dir, err), + ConfigurationError::DirectoryUnset + => writeln!(f, "--config-dir was unset or empty."), + ConfigurationError::HomeExpansionFailed(ref dir) + => writeln!(f, "Couldn't find HOME directory of current user, failed to expand '{}'.", dir), + ConfigurationError::Secret(ref err) + => writeln!(f, "Secret -> {}", err), + ConfigurationError::IOError((ref path, ref err)) + => writeln!(f, "IO operation failed on path '{}' with error: {}.", path, err), + } + } +} + +#[derive(Debug)] +pub enum InputError { + IOError((String, io::Error)), + Mime(String), +} + +impl fmt::Display for InputError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + InputError::IOError((ref file_path, ref io_err)) + => writeln!(f, "Failed to open '{}' for reading with error: {}.", file_path, io_err), + InputError::Mime(ref mime) + => writeln!(f, "'{}' is not a known mime-type.", mime), + } + } +} + +#[derive(Debug)] +pub enum FieldError { + PopOnEmpty(String), + TrailingFieldSep(String), + Unknown(String, Option, Option), + Duplicate(String), + Empty, +} + + +impl fmt::Display for FieldError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + FieldError::PopOnEmpty(ref field) + => writeln!(f, "'{}': Cannot move up on empty field cursor.", field), + FieldError::TrailingFieldSep(ref field) + => writeln!(f, "'{}': Single field separator may not be last character.", field), + FieldError::Unknown(ref field, ref suggestion, ref value) => { + let suffix = + match *suggestion { + Some(ref s) => { + let kv = + match *value { + Some(ref v) => format!("{}={}", s, v), + None => s.clone(), + }; + format!(" Did you mean '{}' ?", kv) + }, + None => String::new(), + }; + writeln!(f, "Field '{}' does not exist.{}", field, suffix) + }, + FieldError::Duplicate(ref cursor) + => writeln!(f, "Value at '{}' was already set", cursor), + FieldError::Empty + => writeln!(f, "Field names must not be empty."), + } + } +} + + +#[derive(Debug)] +pub enum CLIError { + Configuration(ConfigurationError), + ParseError(String, String, String, String), + UnknownParameter(String, Vec<&'static str>), + InvalidUploadProtocol(String, Vec), + InvalidKeyValueSyntax(String, bool), + Input(InputError), + Field(FieldError), + MissingCommandError, + MissingMethodError(String), +} + +impl fmt::Display for CLIError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + CLIError::Configuration(ref err) => write!(f, "Configuration -> {}", err), + CLIError::Input(ref err) => write!(f, "Input -> {}", err), + CLIError::Field(ref err) => write!(f, "Field -> {}", err), + CLIError::InvalidUploadProtocol(ref proto_name, ref valid_names) + => writeln!(f, "'{}' is not a valid upload protocol. Choose from one of {}.", proto_name, valid_names.join(", ")), + CLIError::ParseError(ref arg_name, ref type_name, ref value, ref err_desc) + => writeln!(f, "Failed to parse argument '{}' with value '{}' as {} with error: {}.", + arg_name, value, type_name, err_desc), + CLIError::UnknownParameter(ref param_name, ref possible_values) => { + let mut suffix = + match did_you_mean(param_name, &possible_values) { + Some(v) => format!(" Did you mean '{}' ?", v), + None => String::new(), + }; + write!(f, "Parameter '{}' is unknown.{}\n", param_name, suffix) + }, + CLIError::InvalidKeyValueSyntax(ref kv, is_hashmap) => { + let hashmap_info = if is_hashmap { "hashmap " } else { "" }; + writeln!(f, "'{}' does not match {}pattern =.", kv, hashmap_info) + }, + CLIError::MissingCommandError => writeln!(f, "Please specify the main sub-command."), + CLIError::MissingMethodError(ref cmd) => writeln!(f, "Please specify the method to call on the '{}' command.", cmd), + } + } +} + +#[derive(Debug)] +pub struct InvalidOptionsError { + pub issues: Vec, + pub exit_code: i32, +} + +impl fmt::Display for InvalidOptionsError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + for issue in &self.issues { + try!(issue.fmt(f)); + } + Ok(()) + } +} + +impl InvalidOptionsError { + pub fn single(err: CLIError, exit_code: i32) -> InvalidOptionsError { + InvalidOptionsError { + issues: vec![err], + exit_code: exit_code, + } + } + + pub fn new() -> InvalidOptionsError { + InvalidOptionsError { + issues: Vec::new(), + exit_code: 1, + } + } +} + +pub fn assure_config_dir_exists(dir: &str) -> Result { + let trdir = dir.trim(); + if trdir.len() == 0 { + return Err(CLIError::Configuration(ConfigurationError::DirectoryUnset)) + } + + let expanded_config_dir = + if trdir.as_bytes()[0] == b'~' { + match env::var("HOME").ok().or(env::var("UserProfile").ok()) { + None => return Err(CLIError::Configuration(ConfigurationError::HomeExpansionFailed(trdir.to_string()))), + Some(mut user) => { + user.push_str(&trdir[1..]); + user + } + } + } else { + trdir.to_string() + }; + + if let Err(err) = fs::create_dir(&expanded_config_dir) { + if err.kind() != io::ErrorKind::AlreadyExists { + return Err(CLIError::Configuration( + ConfigurationError::DirectoryCreationFailed((expanded_config_dir, err)))) + } + } + + Ok(expanded_config_dir) +} + +pub fn application_secret_from_directory(dir: &str, + secret_basename: &str, + json_console_secret: &str) + -> Result { + let secret_path = Path::new(dir).join(secret_basename); + let secret_str = || secret_path.as_path().to_str().unwrap().to_string(); + let secret_io_error = |io_err: io::Error| { + Err(CLIError::Configuration(ConfigurationError::IOError( + (secret_str(), io_err) + ))) + }; + + for _ in 0..2 { + match fs::File::open(&secret_path) { + Err(mut err) => { + if err.kind() == io::ErrorKind::NotFound { + // Write our built-in one - user may adjust the written file at will + + err = match fs::OpenOptions::new().create(true).write(true).open(&secret_path) { + Err(cfe) => cfe, + Ok(mut f) => { + // Assure we convert 'ugly' json string into pretty one + let console_secret: ConsoleApplicationSecret + = json::from_str(json_console_secret).unwrap(); + match json::to_writer_pretty(&mut f, &console_secret) { + Err(serde_err) => match serde_err { + json::Error::IoError(err) => err, + _ => panic!("Unexpected serde error: {:#?}", serde_err) + }, + Ok(_) => continue, + } + } + }; + // fall through to IO error handling + } + return secret_io_error(err) + }, + Ok(mut f) => { + match json::de::from_reader::<_, ConsoleApplicationSecret>(f) { + Err(json::Error::IoError(err)) => + return secret_io_error(err), + Err(json_err) => + return Err(CLIError::Configuration( + ConfigurationError::Secret( + ApplicationSecretError::DecoderError( + (secret_str(), json_err) + )))), + Ok(console_secret) => + match console_secret.installed { + Some(secret) => return Ok(secret), + None => return Err( + CLIError::Configuration( + ConfigurationError::Secret( + ApplicationSecretError::FormatError(secret_str()) + ))) + }, + } + } + } + } + unreachable!(); +} diff --git a/gen/classroom1-cli/src/main.rs b/gen/classroom1-cli/src/main.rs new file mode 100644 index 0000000000..c89a4f56b6 --- /dev/null +++ b/gen/classroom1-cli/src/main.rs @@ -0,0 +1,2424 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/cli/main.rs.mako' +// DO NOT EDIT ! +#![allow(unused_variables, unused_imports, dead_code, unused_mut)] + +#[macro_use] +extern crate clap; +extern crate yup_oauth2 as oauth2; +extern crate yup_hyper_mock as mock; +extern crate serde; +extern crate serde_json; +extern crate hyper; +extern crate mime; +extern crate strsim; +extern crate google_classroom1 as api; + +use std::env; +use std::io::{self, Write}; +use clap::{App, SubCommand, Arg}; + +mod cmn; + +use cmn::{InvalidOptionsError, CLIError, JsonTokenStorage, arg_from_str, writer_from_opts, parse_kv_arg, + input_file_from_opts, input_mime_from_opts, FieldCursor, FieldError, CallType, UploadProtocol, + calltype_from_str, remove_json_null_values, ComplexType, JsonType, JsonTypeInfo}; + +use std::default::Default; +use std::str::FromStr; + +use oauth2::{Authenticator, DefaultAuthenticatorDelegate}; +use serde_json as json; +use clap::ArgMatches; + +enum DoitError { + IoError(String, io::Error), + ApiError(api::Error), +} + +struct Engine<'n, 'a> { + opt: ArgMatches<'n, 'a>, + hub: api::Classroom>, + gp: Vec<&'static str>, + gpm: Vec<(&'static str, &'static str)>, +} + + +impl<'n, 'a> Engine<'n, 'a> { + fn _courses_aliases_create(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "alias" => Some(("alias", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["alias"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::CourseAlias = json::value::from_value(object).unwrap(); + let mut call = self.hub.courses().aliases_create(request, opt.value_of("course-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _courses_aliases_delete(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.courses().aliases_delete(opt.value_of("course-id").unwrap_or(""), opt.value_of("alias").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _courses_aliases_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.courses().aliases_list(opt.value_of("course-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "page-size" => { + call = call.page_size(arg_from_str(value.unwrap_or("-0"), err, "page-size", "integer")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["page-token", "page-size"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _courses_create(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "update-time" => Some(("updateTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "description" => Some(("description", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "alternate-link" => Some(("alternateLink", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "enrollment-code" => Some(("enrollmentCode", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "section" => Some(("section", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "creation-time" => Some(("creationTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "course-state" => Some(("courseState", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "owner-id" => Some(("ownerId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "description-heading" => Some(("descriptionHeading", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "room" => Some(("room", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["alternate-link", "course-state", "creation-time", "description", "description-heading", "enrollment-code", "id", "name", "owner-id", "room", "section", "update-time"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::Course = json::value::from_value(object).unwrap(); + let mut call = self.hub.courses().create(request); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _courses_delete(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.courses().delete(opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _courses_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.courses().get(opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _courses_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.courses().list(); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "teacher-id" => { + call = call.teacher_id(value.unwrap_or("")); + }, + "student-id" => { + call = call.student_id(value.unwrap_or("")); + }, + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "page-size" => { + call = call.page_size(arg_from_str(value.unwrap_or("-0"), err, "page-size", "integer")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["teacher-id", "page-token", "student-id", "page-size"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _courses_patch(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "update-time" => Some(("updateTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "description" => Some(("description", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "alternate-link" => Some(("alternateLink", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "enrollment-code" => Some(("enrollmentCode", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "section" => Some(("section", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "creation-time" => Some(("creationTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "course-state" => Some(("courseState", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "owner-id" => Some(("ownerId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "description-heading" => Some(("descriptionHeading", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "room" => Some(("room", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["alternate-link", "course-state", "creation-time", "description", "description-heading", "enrollment-code", "id", "name", "owner-id", "room", "section", "update-time"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::Course = json::value::from_value(object).unwrap(); + let mut call = self.hub.courses().patch(request, opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "update-mask" => { + call = call.update_mask(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["update-mask"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _courses_students_create(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "course-id" => Some(("courseId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "profile.email-address" => Some(("profile.emailAddress", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "profile.id" => Some(("profile.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "profile.name.full-name" => Some(("profile.name.fullName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "profile.name.given-name" => Some(("profile.name.givenName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "profile.name.family-name" => Some(("profile.name.familyName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "profile.photo-url" => Some(("profile.photoUrl", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "user-id" => Some(("userId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["course-id", "email-address", "family-name", "full-name", "given-name", "id", "name", "photo-url", "profile", "user-id"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::Student = json::value::from_value(object).unwrap(); + let mut call = self.hub.courses().students_create(request, opt.value_of("course-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "enrollment-code" => { + call = call.enrollment_code(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["enrollment-code"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _courses_students_delete(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.courses().students_delete(opt.value_of("course-id").unwrap_or(""), opt.value_of("user-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _courses_students_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.courses().students_get(opt.value_of("course-id").unwrap_or(""), opt.value_of("user-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _courses_students_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.courses().students_list(opt.value_of("course-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "page-size" => { + call = call.page_size(arg_from_str(value.unwrap_or("-0"), err, "page-size", "integer")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["page-token", "page-size"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _courses_teachers_create(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "course-id" => Some(("courseId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "profile.email-address" => Some(("profile.emailAddress", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "profile.id" => Some(("profile.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "profile.name.full-name" => Some(("profile.name.fullName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "profile.name.given-name" => Some(("profile.name.givenName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "profile.name.family-name" => Some(("profile.name.familyName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "profile.photo-url" => Some(("profile.photoUrl", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "user-id" => Some(("userId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["course-id", "email-address", "family-name", "full-name", "given-name", "id", "name", "photo-url", "profile", "user-id"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::Teacher = json::value::from_value(object).unwrap(); + let mut call = self.hub.courses().teachers_create(request, opt.value_of("course-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _courses_teachers_delete(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.courses().teachers_delete(opt.value_of("course-id").unwrap_or(""), opt.value_of("user-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _courses_teachers_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.courses().teachers_get(opt.value_of("course-id").unwrap_or(""), opt.value_of("user-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _courses_teachers_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.courses().teachers_list(opt.value_of("course-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "page-size" => { + call = call.page_size(arg_from_str(value.unwrap_or("-0"), err, "page-size", "integer")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["page-token", "page-size"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _courses_update(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "update-time" => Some(("updateTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "description" => Some(("description", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "alternate-link" => Some(("alternateLink", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "enrollment-code" => Some(("enrollmentCode", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "section" => Some(("section", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "creation-time" => Some(("creationTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "course-state" => Some(("courseState", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "owner-id" => Some(("ownerId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "description-heading" => Some(("descriptionHeading", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "room" => Some(("room", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["alternate-link", "course-state", "creation-time", "description", "description-heading", "enrollment-code", "id", "name", "owner-id", "room", "section", "update-time"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::Course = json::value::from_value(object).unwrap(); + let mut call = self.hub.courses().update(request, opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _invitations_accept(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.invitations().accept(opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _invitations_create(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "course-id" => Some(("courseId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "role" => Some(("role", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "user-id" => Some(("userId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["course-id", "id", "role", "user-id"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::Invitation = json::value::from_value(object).unwrap(); + let mut call = self.hub.invitations().create(request); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _invitations_delete(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.invitations().delete(opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _invitations_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.invitations().get(opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _invitations_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.invitations().list(); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "user-id" => { + call = call.user_id(value.unwrap_or("")); + }, + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "page-size" => { + call = call.page_size(arg_from_str(value.unwrap_or("-0"), err, "page-size", "integer")); + }, + "course-id" => { + call = call.course_id(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["course-id", "page-token", "user-id", "page-size"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _user_profiles_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.user_profiles().get(opt.value_of("user-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _doit(&self, dry_run: bool) -> Result, Option> { + let mut err = InvalidOptionsError::new(); + let mut call_result: Result<(), DoitError> = Ok(()); + let mut err_opt: Option = None; + match self.opt.subcommand() { + ("courses", Some(opt)) => { + match opt.subcommand() { + ("aliases-create", Some(opt)) => { + call_result = self._courses_aliases_create(opt, dry_run, &mut err); + }, + ("aliases-delete", Some(opt)) => { + call_result = self._courses_aliases_delete(opt, dry_run, &mut err); + }, + ("aliases-list", Some(opt)) => { + call_result = self._courses_aliases_list(opt, dry_run, &mut err); + }, + ("create", Some(opt)) => { + call_result = self._courses_create(opt, dry_run, &mut err); + }, + ("delete", Some(opt)) => { + call_result = self._courses_delete(opt, dry_run, &mut err); + }, + ("get", Some(opt)) => { + call_result = self._courses_get(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._courses_list(opt, dry_run, &mut err); + }, + ("patch", Some(opt)) => { + call_result = self._courses_patch(opt, dry_run, &mut err); + }, + ("students-create", Some(opt)) => { + call_result = self._courses_students_create(opt, dry_run, &mut err); + }, + ("students-delete", Some(opt)) => { + call_result = self._courses_students_delete(opt, dry_run, &mut err); + }, + ("students-get", Some(opt)) => { + call_result = self._courses_students_get(opt, dry_run, &mut err); + }, + ("students-list", Some(opt)) => { + call_result = self._courses_students_list(opt, dry_run, &mut err); + }, + ("teachers-create", Some(opt)) => { + call_result = self._courses_teachers_create(opt, dry_run, &mut err); + }, + ("teachers-delete", Some(opt)) => { + call_result = self._courses_teachers_delete(opt, dry_run, &mut err); + }, + ("teachers-get", Some(opt)) => { + call_result = self._courses_teachers_get(opt, dry_run, &mut err); + }, + ("teachers-list", Some(opt)) => { + call_result = self._courses_teachers_list(opt, dry_run, &mut err); + }, + ("update", Some(opt)) => { + call_result = self._courses_update(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("courses".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("invitations", Some(opt)) => { + match opt.subcommand() { + ("accept", Some(opt)) => { + call_result = self._invitations_accept(opt, dry_run, &mut err); + }, + ("create", Some(opt)) => { + call_result = self._invitations_create(opt, dry_run, &mut err); + }, + ("delete", Some(opt)) => { + call_result = self._invitations_delete(opt, dry_run, &mut err); + }, + ("get", Some(opt)) => { + call_result = self._invitations_get(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._invitations_list(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("invitations".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("user-profiles", Some(opt)) => { + match opt.subcommand() { + ("get", Some(opt)) => { + call_result = self._user_profiles_get(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("user-profiles".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + _ => { + err.issues.push(CLIError::MissingCommandError); + writeln!(io::stderr(), "{}\n", self.opt.usage()).ok(); + } + } + + if dry_run { + if err.issues.len() > 0 { + err_opt = Some(err); + } + Err(err_opt) + } else { + Ok(call_result) + } + } + + // Please note that this call will fail if any part of the opt can't be handled + fn new(opt: ArgMatches<'a, 'n>) -> Result, InvalidOptionsError> { + let (config_dir, secret) = { + let config_dir = match cmn::assure_config_dir_exists(opt.value_of("folder").unwrap_or("~/.google-service-cli")) { + Err(e) => return Err(InvalidOptionsError::single(e, 3)), + Ok(p) => p, + }; + + match cmn::application_secret_from_directory(&config_dir, "classroom1-secret.json", + "{\"installed\":{\"auth_uri\":\"https://accounts.google.com/o/oauth2/auth\",\"client_secret\":\"hCsslbCUyfehWMmbkG8vTYxG\",\"token_uri\":\"https://accounts.google.com/o/oauth2/token\",\"client_email\":\"\",\"redirect_uris\":[\"urn:ietf:wg:oauth:2.0:oob\",\"oob\"],\"client_x509_cert_url\":\"\",\"client_id\":\"620010449518-9ngf7o4dhs0dka470npqvor6dc5lqb9b.apps.googleusercontent.com\",\"auth_provider_x509_cert_url\":\"https://www.googleapis.com/oauth2/v1/certs\"}}") { + Ok(secret) => (config_dir, secret), + Err(e) => return Err(InvalidOptionsError::single(e, 4)) + } + }; + + let auth = Authenticator::new( &secret, DefaultAuthenticatorDelegate, + if opt.is_present("debug-auth") { + hyper::Client::with_connector(mock::TeeConnector { + connector: hyper::net::HttpsConnector::::default() + }) + } else { + hyper::Client::new() + }, + JsonTokenStorage { + program_name: "classroom1", + db_dir: config_dir.clone(), + }, None); + + let client = + if opt.is_present("debug") { + hyper::Client::with_connector(mock::TeeConnector { + connector: hyper::net::HttpsConnector::::default() + }) + } else { + hyper::Client::new() + }; + let engine = Engine { + opt: opt, + hub: api::Classroom::new(client, auth), + gp: vec!["$-xgafv", "access-token", "alt", "bearer-token", "callback", "fields", "key", "oauth-token", "pp", "pretty-print", "quota-user", "upload-type", "upload-protocol"], + gpm: vec![ + ("$-xgafv", "$.xgafv"), + ("access-token", "access_token"), + ("bearer-token", "bearer_token"), + ("oauth-token", "oauth_token"), + ("pretty-print", "prettyPrint"), + ("quota-user", "quotaUser"), + ("upload-type", "uploadType"), + ("upload-protocol", "upload_protocol"), + ] + }; + + match engine._doit(true) { + Err(Some(err)) => Err(err), + Err(None) => Ok(engine), + Ok(_) => unreachable!(), + } + } + + fn doit(&self) -> Result<(), DoitError> { + match self._doit(false) { + Ok(res) => res, + Err(_) => unreachable!(), + } + } +} + +fn main() { + let mut exit_status = 0i32; + let arg_data = [ + ("courses", "methods: 'aliases-create', 'aliases-delete', 'aliases-list', 'create', 'delete', 'get', 'list', 'patch', 'students-create', 'students-delete', 'students-get', 'students-list', 'teachers-create', 'teachers-delete', 'teachers-get', 'teachers-list' and 'update'", vec![ + ("aliases-create", + Some(r##"Creates an alias for a course. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to create the alias or for access errors. * `NOT_FOUND` if the course does not exist. * `ALREADY_EXISTS` if the alias already exists."##), + "Details at http://byron.github.io/google-apis-rs/google_classroom1_cli/courses_aliases-create", + vec![ + (Some(r##"course-id"##), + None, + Some(r##"Identifier of the course to alias. This identifier can be either the Classroom-assigned identifier or an alias."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("aliases-delete", + Some(r##"Deletes an alias of a course. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to remove the alias or for access errors. * `NOT_FOUND` if the alias does not exist."##), + "Details at http://byron.github.io/google-apis-rs/google_classroom1_cli/courses_aliases-delete", + vec![ + (Some(r##"course-id"##), + None, + Some(r##"Identifier of the course whose alias should be deleted. This identifier can be either the Classroom-assigned identifier or an alias."##), + Some(true), + Some(false)), + + (Some(r##"alias"##), + None, + Some(r##"Alias to delete. This may not be the Classroom-assigned identifier."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("aliases-list", + Some(r##"Returns a list of aliases for a course. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to access the course or for access errors. * `NOT_FOUND` if the course does not exist."##), + "Details at http://byron.github.io/google-apis-rs/google_classroom1_cli/courses_aliases-list", + vec![ + (Some(r##"course-id"##), + None, + Some(r##"The identifier of the course. This identifier can be either the Classroom-assigned identifier or an alias."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("create", + Some(r##"Creates a course. The user specified in `ownerId` is the owner of the created course and added as a teacher. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to create courses or for access errors. * `NOT_FOUND` if the primary teacher is not a valid user. * `FAILED_PRECONDITION` if the course owner's account is disabled or for the following request errors: * UserGroupsMembershipLimitReached * `ALREADY_EXISTS` if an alias was specified in the `id` and already exists."##), + "Details at http://byron.github.io/google-apis-rs/google_classroom1_cli/courses_create", + vec![ + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("delete", + Some(r##"Deletes a course. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to delete the requested course or for access errors. * `NOT_FOUND` if no course exists with the requested ID."##), + "Details at http://byron.github.io/google-apis-rs/google_classroom1_cli/courses_delete", + vec![ + (Some(r##"id"##), + None, + Some(r##"Identifier of the course to delete. This identifier can be either the Classroom-assigned identifier or an alias."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("get", + Some(r##"Returns a course. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to access the requested course or for access errors. * `NOT_FOUND` if no course exists with the requested ID."##), + "Details at http://byron.github.io/google-apis-rs/google_classroom1_cli/courses_get", + vec![ + (Some(r##"id"##), + None, + Some(r##"Identifier of the course to return. This identifier can be either the Classroom-assigned identifier or an alias."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Returns a list of courses that the requesting user is permitted to view, restricted to those that match the request. This method returns the following error codes: * `PERMISSION_DENIED` for access errors. * `INVALID_ARGUMENT` if the query argument is malformed. * `NOT_FOUND` if any users specified in the query arguments do not exist."##), + "Details at http://byron.github.io/google-apis-rs/google_classroom1_cli/courses_list", + vec![ + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("patch", + Some(r##"Updates one or more fields in a course. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to modify the requested course or for access errors. * `NOT_FOUND` if no course exists with the requested ID. * `INVALID_ARGUMENT` if invalid fields are specified in the update mask or if no update mask is supplied. * `FAILED_PRECONDITION` for the following request errors: * CourseNotModifiable"##), + "Details at http://byron.github.io/google-apis-rs/google_classroom1_cli/courses_patch", + vec![ + (Some(r##"id"##), + None, + Some(r##"Identifier of the course to update. This identifier can be either the Classroom-assigned identifier or an alias."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("students-create", + Some(r##"Adds a user as a student of a course. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to create students in this course or for access errors. * `NOT_FOUND` if the requested course ID does not exist. * `FAILED_PRECONDITION` if the requested user's account is disabled, for the following request errors: * CourseMemberLimitReached * CourseNotModifiable * UserGroupsMembershipLimitReached * `ALREADY_EXISTS` if the user is already a student or teacher in the course."##), + "Details at http://byron.github.io/google-apis-rs/google_classroom1_cli/courses_students-create", + vec![ + (Some(r##"course-id"##), + None, + Some(r##"Identifier of the course to create the student in. This identifier can be either the Classroom-assigned identifier or an alias."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("students-delete", + Some(r##"Deletes a student of a course. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to delete students of this course or for access errors. * `NOT_FOUND` if no student of this course has the requested ID or if the course does not exist."##), + "Details at http://byron.github.io/google-apis-rs/google_classroom1_cli/courses_students-delete", + vec![ + (Some(r##"course-id"##), + None, + Some(r##"Identifier of the course. This identifier can be either the Classroom-assigned identifier or an alias."##), + Some(true), + Some(false)), + + (Some(r##"user-id"##), + None, + Some(r##"Identifier of the student to delete. The identifier can be one of the following: * the numeric identifier for the user * the email address of the user * the string literal `"me"`, indicating the requesting user"##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("students-get", + Some(r##"Returns a student of a course. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to view students of this course or for access errors. * `NOT_FOUND` if no student of this course has the requested ID or if the course does not exist."##), + "Details at http://byron.github.io/google-apis-rs/google_classroom1_cli/courses_students-get", + vec![ + (Some(r##"course-id"##), + None, + Some(r##"Identifier of the course. This identifier can be either the Classroom-assigned identifier or an alias."##), + Some(true), + Some(false)), + + (Some(r##"user-id"##), + None, + Some(r##"Identifier of the student to return. The identifier can be one of the following: * the numeric identifier for the user * the email address of the user * the string literal `"me"`, indicating the requesting user"##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("students-list", + Some(r##"Returns a list of students of this course that the requester is permitted to view. This method returns the following error codes: * `NOT_FOUND` if the course does not exist. * `PERMISSION_DENIED` for access errors."##), + "Details at http://byron.github.io/google-apis-rs/google_classroom1_cli/courses_students-list", + vec![ + (Some(r##"course-id"##), + None, + Some(r##"Identifier of the course. This identifier can be either the Classroom-assigned identifier or an alias."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("teachers-create", + Some(r##"Creates a teacher of a course. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to create teachers in this course or for access errors. * `NOT_FOUND` if the requested course ID does not exist. * `FAILED_PRECONDITION` if the requested user's account is disabled, for the following request errors: * CourseMemberLimitReached * CourseNotModifiable * CourseTeacherLimitReached * UserGroupsMembershipLimitReached * `ALREADY_EXISTS` if the user is already a teacher or student in the course."##), + "Details at http://byron.github.io/google-apis-rs/google_classroom1_cli/courses_teachers-create", + vec![ + (Some(r##"course-id"##), + None, + Some(r##"Identifier of the course. This identifier can be either the Classroom-assigned identifier or an alias."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("teachers-delete", + Some(r##"Deletes a teacher of a course. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to delete teachers of this course or for access errors. * `NOT_FOUND` if no teacher of this course has the requested ID or if the course does not exist. * `FAILED_PRECONDITION` if the requested ID belongs to the primary teacher of this course."##), + "Details at http://byron.github.io/google-apis-rs/google_classroom1_cli/courses_teachers-delete", + vec![ + (Some(r##"course-id"##), + None, + Some(r##"Identifier of the course. This identifier can be either the Classroom-assigned identifier or an alias."##), + Some(true), + Some(false)), + + (Some(r##"user-id"##), + None, + Some(r##"Identifier of the teacher to delete. The identifier can be one of the following: * the numeric identifier for the user * the email address of the user * the string literal `"me"`, indicating the requesting user"##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("teachers-get", + Some(r##"Returns a teacher of a course. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to view teachers of this course or for access errors. * `NOT_FOUND` if no teacher of this course has the requested ID or if the course does not exist."##), + "Details at http://byron.github.io/google-apis-rs/google_classroom1_cli/courses_teachers-get", + vec![ + (Some(r##"course-id"##), + None, + Some(r##"Identifier of the course. This identifier can be either the Classroom-assigned identifier or an alias."##), + Some(true), + Some(false)), + + (Some(r##"user-id"##), + None, + Some(r##"Identifier of the teacher to return. The identifier can be one of the following: * the numeric identifier for the user * the email address of the user * the string literal `"me"`, indicating the requesting user"##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("teachers-list", + Some(r##"Returns a list of teachers of this course that the requester is permitted to view. This method returns the following error codes: * `NOT_FOUND` if the course does not exist. * `PERMISSION_DENIED` for access errors."##), + "Details at http://byron.github.io/google-apis-rs/google_classroom1_cli/courses_teachers-list", + vec![ + (Some(r##"course-id"##), + None, + Some(r##"Identifier of the course. This identifier can be either the Classroom-assigned identifier or an alias."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("update", + Some(r##"Updates a course. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to modify the requested course or for access errors. * `NOT_FOUND` if no course exists with the requested ID. * `FAILED_PRECONDITION` for the following request errors: * CourseNotModifiable"##), + "Details at http://byron.github.io/google-apis-rs/google_classroom1_cli/courses_update", + vec![ + (Some(r##"id"##), + None, + Some(r##"Identifier of the course to update. This identifier can be either the Classroom-assigned identifier or an alias."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("invitations", "methods: 'accept', 'create', 'delete', 'get' and 'list'", vec![ + ("accept", + Some(r##"Accepts an invitation, removing it and adding the invited user to the teachers or students (as appropriate) of the specified course. Only the invited user may accept an invitation. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to accept the requested invitation or for access errors. * `FAILED_PRECONDITION` for the following request errors: * CourseMemberLimitReached * CourseNotModifiable * CourseTeacherLimitReached * UserGroupsMembershipLimitReached * `NOT_FOUND` if no invitation exists with the requested ID."##), + "Details at http://byron.github.io/google-apis-rs/google_classroom1_cli/invitations_accept", + vec![ + (Some(r##"id"##), + None, + Some(r##"Identifier of the invitation to accept."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("create", + Some(r##"Creates an invitation. Only one invitation for a user and course may exist at a time. Delete and re-create an invitation to make changes. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to create invitations for this course or for access errors. * `NOT_FOUND` if the course or the user does not exist. * `FAILED_PRECONDITION` if the requested user's account is disabled or if the user already has this role or a role with greater permissions. * `ALREADY_EXISTS` if an invitation for the specified user and course already exists."##), + "Details at http://byron.github.io/google-apis-rs/google_classroom1_cli/invitations_create", + vec![ + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("delete", + Some(r##"Deletes an invitation. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to delete the requested invitation or for access errors. * `NOT_FOUND` if no invitation exists with the requested ID."##), + "Details at http://byron.github.io/google-apis-rs/google_classroom1_cli/invitations_delete", + vec![ + (Some(r##"id"##), + None, + Some(r##"Identifier of the invitation to delete."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("get", + Some(r##"Returns an invitation. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to view the requested invitation or for access errors. * `NOT_FOUND` if no invitation exists with the requested ID."##), + "Details at http://byron.github.io/google-apis-rs/google_classroom1_cli/invitations_get", + vec![ + (Some(r##"id"##), + None, + Some(r##"Identifier of the invitation to return."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Returns a list of invitations that the requesting user is permitted to view, restricted to those that match the list request. *Note:* At least one of `user_id` or `course_id` must be supplied. Both fields can be supplied. This method returns the following error codes: * `PERMISSION_DENIED` for access errors."##), + "Details at http://byron.github.io/google-apis-rs/google_classroom1_cli/invitations_list", + vec![ + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("user-profiles", "methods: 'get'", vec![ + ("get", + Some(r##"Returns a user profile. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to access this user profile or if no profile exists with the requested ID or for access errors."##), + "Details at http://byron.github.io/google-apis-rs/google_classroom1_cli/user-profiles_get", + vec![ + (Some(r##"user-id"##), + None, + Some(r##"Identifier of the profile to return. The identifier can be one of the following: * the numeric identifier for the user * the email address of the user * the string literal `"me"`, indicating the requesting user"##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ]; + + let mut app = App::new("classroom1") + .author("Sebastian Thiel ") + .version("0.3.2+20151013") + .about("Google Classroom API") + .after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_classroom1_cli") + .arg(Arg::with_name("url") + .long("scope") + .help("Specify the authentication a method should be executed in. Each scope requires the user to grant this application permission to use it.If unset, it defaults to the shortest scope url for a particular method.") + .multiple(true) + .takes_value(true)) + .arg(Arg::with_name("folder") + .long("config-dir") + .help("A directory into which we will store our persistent data. Defaults to a user-writable directory that we will create during the first invocation.[default: ~/.google-service-cli") + .multiple(false) + .takes_value(true)) + .arg(Arg::with_name("debug") + .long("debug") + .help("Output all server communication to standard error. `tx` and `rx` are placed into the same stream.") + .multiple(false) + .takes_value(false)) + .arg(Arg::with_name("debug-auth") + .long("debug-auth") + .help("Output all communication related to authentication to standard error. `tx` and `rx` are placed into the same stream.") + .multiple(false) + .takes_value(false)); + + for &(main_command_name, ref about, ref subcommands) in arg_data.iter() { + let mut mcmd = SubCommand::with_name(main_command_name).about(about); + + for &(sub_command_name, ref desc, url_info, ref args) in subcommands { + let mut scmd = SubCommand::with_name(sub_command_name); + if let &Some(desc) = desc { + scmd = scmd.about(desc); + } + scmd = scmd.after_help(url_info); + + for &(ref arg_name, ref flag, ref desc, ref required, ref multi) in args { + let arg_name_str = + match (arg_name, flag) { + (&Some(an), _ ) => an, + (_ , &Some(f)) => f, + _ => unreachable!(), + }; + let mut arg = Arg::with_name(arg_name_str) + .empty_values(false); + if let &Some(short_flag) = flag { + arg = arg.short(short_flag); + } + if let &Some(desc) = desc { + arg = arg.help(desc); + } + if arg_name.is_some() && flag.is_some() { + arg = arg.takes_value(true); + } + if let &Some(required) = required { + arg = arg.required(required); + } + if let &Some(multi) = multi { + arg = arg.multiple(multi); + } + scmd = scmd.arg(arg); + } + mcmd = mcmd.subcommand(scmd); + } + app = app.subcommand(mcmd); + } + + let matches = app.get_matches(); + + let debug = matches.is_present("debug"); + match Engine::new(matches) { + Err(err) => { + exit_status = err.exit_code; + writeln!(io::stderr(), "{}", err).ok(); + }, + Ok(engine) => { + if let Err(doit_err) = engine.doit() { + exit_status = 1; + match doit_err { + DoitError::IoError(path, err) => { + writeln!(io::stderr(), "Failed to open output file '{}': {}", path, err).ok(); + }, + DoitError::ApiError(err) => { + if debug { + writeln!(io::stderr(), "{:#?}", err).ok(); + } else { + writeln!(io::stderr(), "{}", err).ok(); + } + } + } + } + } + } + + std::process::exit(exit_status); +} \ No newline at end of file diff --git a/gen/classroom1/Cargo.toml b/gen/classroom1/Cargo.toml new file mode 100644 index 0000000000..6ae154f818 --- /dev/null +++ b/gen/classroom1/Cargo.toml @@ -0,0 +1,29 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-classroom1" +version = "0.1.9+20151013" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with classroom (protocol v1)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/classroom1" +homepage = "https://developers.google.com/classroom/" +documentation = "http://byron.github.io/google-apis-rs/google_classroom1" +license = "MIT" +keywords = ["classroom", "google", "protocol", "web", "api"] +build = "src/build.rs" + + +[dependencies] +hyper = ">= 0.6.8" +mime = "0.1.0" +serde = ">= 0.6.0" +serde_json = ">= 0.6.0" +yup-oauth2 = "*" +url = "*" + +[build-dependencies] +syntex = { version = "*" } +serde_codegen = { version = "*" } + diff --git a/gen/classroom1/LICENSE.md b/gen/classroom1/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/classroom1/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/classroom1/README.md b/gen/classroom1/README.md new file mode 100644 index 0000000000..e1ff833563 --- /dev/null +++ b/gen/classroom1/README.md @@ -0,0 +1,197 @@ + +The `google-classroom1` library allows access to all features of the *Google classroom* service. + +This documentation was generated from *classroom* crate version *0.1.9+20151013*, where *20151013* is the exact revision of the *classroom:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. + +Everything else about the *classroom* *v1* API can be found at the +[official documentation site](https://developers.google.com/classroom/). +# Features + +Handle the following *Resources* with ease from the central [hub](http://byron.github.io/google-apis-rs/google_classroom1/struct.Classroom.html) ... + +* [courses](http://byron.github.io/google-apis-rs/google_classroom1/struct.Course.html) + * [*aliases create*](http://byron.github.io/google-apis-rs/google_classroom1/struct.CourseAliaseCreateCall.html), [*aliases delete*](http://byron.github.io/google-apis-rs/google_classroom1/struct.CourseAliaseDeleteCall.html), [*aliases list*](http://byron.github.io/google-apis-rs/google_classroom1/struct.CourseAliaseListCall.html), [*create*](http://byron.github.io/google-apis-rs/google_classroom1/struct.CourseCreateCall.html), [*delete*](http://byron.github.io/google-apis-rs/google_classroom1/struct.CourseDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google_classroom1/struct.CourseGetCall.html), [*list*](http://byron.github.io/google-apis-rs/google_classroom1/struct.CourseListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google_classroom1/struct.CoursePatchCall.html), [*students create*](http://byron.github.io/google-apis-rs/google_classroom1/struct.CourseStudentCreateCall.html), [*students delete*](http://byron.github.io/google-apis-rs/google_classroom1/struct.CourseStudentDeleteCall.html), [*students get*](http://byron.github.io/google-apis-rs/google_classroom1/struct.CourseStudentGetCall.html), [*students list*](http://byron.github.io/google-apis-rs/google_classroom1/struct.CourseStudentListCall.html), [*teachers create*](http://byron.github.io/google-apis-rs/google_classroom1/struct.CourseTeacherCreateCall.html), [*teachers delete*](http://byron.github.io/google-apis-rs/google_classroom1/struct.CourseTeacherDeleteCall.html), [*teachers get*](http://byron.github.io/google-apis-rs/google_classroom1/struct.CourseTeacherGetCall.html), [*teachers list*](http://byron.github.io/google-apis-rs/google_classroom1/struct.CourseTeacherListCall.html) and [*update*](http://byron.github.io/google-apis-rs/google_classroom1/struct.CourseUpdateCall.html) +* [invitations](http://byron.github.io/google-apis-rs/google_classroom1/struct.Invitation.html) + * [*accept*](http://byron.github.io/google-apis-rs/google_classroom1/struct.InvitationAcceptCall.html), [*create*](http://byron.github.io/google-apis-rs/google_classroom1/struct.InvitationCreateCall.html), [*delete*](http://byron.github.io/google-apis-rs/google_classroom1/struct.InvitationDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google_classroom1/struct.InvitationGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google_classroom1/struct.InvitationListCall.html) +* [user profiles](http://byron.github.io/google-apis-rs/google_classroom1/struct.UserProfile.html) + * [*get*](http://byron.github.io/google-apis-rs/google_classroom1/struct.UserProfileGetCall.html) + + + + +# Structure of this Library + +The API is structured into the following primary items: + +* **[Hub](http://byron.github.io/google-apis-rs/google_classroom1/struct.Classroom.html)** + * a central object to maintain state and allow accessing all *Activities* + * creates [*Method Builders*](http://byron.github.io/google-apis-rs/google_classroom1/trait.MethodsBuilder.html) which in turn + allow access to individual [*Call Builders*](http://byron.github.io/google-apis-rs/google_classroom1/trait.CallBuilder.html) +* **[Resources](http://byron.github.io/google-apis-rs/google_classroom1/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_classroom1/trait.Part.html)** + * a collection of properties + * never directly used in *Activities* +* **[Activities](http://byron.github.io/google-apis-rs/google_classroom1/trait.CallBuilder.html)** + * operations to apply to *Resources* + +All *structures* are marked with applicable traits to further categorize them and ease browsing. + +Generally speaking, you can invoke *Activities* like this: + +```Rust,ignore +let r = hub.resource().activity(...).doit() +``` + +Or specifically ... + +```ignore +let r = hub.courses().update(...).doit() +let r = hub.courses().list(...).doit() +let r = hub.courses().teachers_list(...).doit() +let r = hub.courses().get(...).doit() +let r = hub.courses().students_delete(...).doit() +let r = hub.courses().patch(...).doit() +let r = hub.courses().aliases_create(...).doit() +let r = hub.courses().teachers_delete(...).doit() +let r = hub.courses().students_create(...).doit() +let r = hub.courses().students_get(...).doit() +let r = hub.courses().aliases_delete(...).doit() +let r = hub.courses().teachers_create(...).doit() +let r = hub.courses().teachers_get(...).doit() +let r = hub.courses().create(...).doit() +let r = hub.courses().students_list(...).doit() +let r = hub.courses().aliases_list(...).doit() +let r = hub.courses().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-classroom1 = "*" +``` + +## A complete example + +```Rust +extern crate hyper; +extern crate yup_oauth2 as oauth2; +extern crate google_classroom1 as classroom1; +use classroom1::{Result, Error}; +use std::default::Default; +use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +use classroom1::Classroom; + +// 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 = Classroom::new(hyper::Client::new(), auth); +// You can configure optional parameters by calling the respective setters at will, and +// execute the final call using `doit()`. +// Values shown here are possibly random and not representative ! +let result = hub.courses().list() + .teacher_id("eirmod") + .student_id("sit") + .page_token("Stet") + .page_size(-42) + .doit(); + +match result { + Err(e) => match e { + // The Error enum provides details about what exactly happened. + // You can also just use its `Debug`, `Display` or `Error` traits + Error::HttpError(_) + |Error::MissingAPIKey + |Error::MissingToken(_) + |Error::Cancelled + |Error::UploadSizeLimitExceeded(_, _) + |Error::Failure(_) + |Error::BadRequest(_) + |Error::FieldClash(_) + |Error::JsonDecodeError(_, _) => println!("{}", e), + }, + Ok(res) => println!("Success: {:?}", res), +} + +``` +## Handling Errors + +All errors produced by the system are provided either as [Result](http://byron.github.io/google-apis-rs/google_classroom1/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_classroom1/trait.Delegate.html), or the [Authenticator Delegate](http://byron.github.io/google-apis-rs/google_classroom1/../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 Downloads +If a method supports downloads, the response body, which is part of the [Result](http://byron.github.io/google-apis-rs/google_classroom1/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_classroom1/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_classroom1/trait.Delegate.html) to the +[Method Builder](http://byron.github.io/google-apis-rs/google_classroom1/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_classroom1/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_classroom1/trait.RequestValue.html) and +[decodable](http://byron.github.io/google-apis-rs/google_classroom1/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_classroom1/trait.Part.html) which are identifiable 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_classroom1/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_classroom1/trait.RequestValue.html) are moved + +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 **classroom1** 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/classroom1/src/build.rs b/gen/classroom1/src/build.rs new file mode 100644 index 0000000000..dd7a4b945c --- /dev/null +++ b/gen/classroom1/src/build.rs @@ -0,0 +1,16 @@ +extern crate syntex; +extern crate serde_codegen; + +use std::env; +use std::path::Path; + +pub fn main() { + let out_dir = env::var_os("OUT_DIR").unwrap(); + + let src = Path::new("src/lib.rs.in"); + let dst = Path::new(&out_dir).join("lib.rs"); + + let mut registry = syntex::Registry::new(); + serde_codegen::register(&mut registry); + registry.expand("google-classroom1", &src, &dst).unwrap(); +} diff --git a/gen/classroom1/src/cmn.rs b/gen/classroom1/src/cmn.rs new file mode 100644 index 0000000000..0e31353ba3 --- /dev/null +++ b/gen/classroom1/src/cmn.rs @@ -0,0 +1,762 @@ +// COPY OF 'src/rust/api/cmn.rs' +// DO NOT EDIT +use std::io::{self, Read, Seek, Cursor, Write, SeekFrom}; +use std; +use std::fmt::{self, Display}; +use std::str::FromStr; +use std::error; +use std::thread::sleep_ms; + +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::h1::LINE_ENDING; +use hyper::method::Method; +use hyper::status::StatusCode; + +use serde_json as json; + +/// 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 {} + +/// Identifies types for building methods of a particular resource type +pub trait MethodsBuilder {} + +/// Identifies types which represent builders for a particular resource method +pub trait CallBuilder {} + +/// Identifies types which can be inserted and deleted. +/// Types with this trait are most commonly used by clients of this API. +pub trait Resource {} + +/// Identifies types which are used in API responses. +pub trait ResponseResult {} + +/// Identifies types which are used in API requests. +pub trait RequestValue {} + +/// Identifies types which are not actually used by the API +/// This might be a bug within the google API schema. +pub trait UnusedType {} + +/// Identifies types which are only used as part of other types, which +/// usually are carrying the `Resource` trait. +pub trait Part {} + +/// 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 {} + +/// 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 +} + +/// A utility to represent detailed errors we might see in case there are BadRequests. +/// The latter happen if the sent parameters or request structures are unsound +#[derive(Deserialize, Serialize, Debug)] +pub struct ErrorResponse { + error: ServerError, +} + +#[derive(Deserialize, Serialize, Debug)] +pub struct ServerError { + errors: Vec, + code: u16, + message: String, +} + +#[derive(Deserialize, Serialize, Debug)] +pub struct ServerMessage { + domain: String, + reason: String, + message: String, + #[serde(rename="locationType")] + location_type: Option, + location: 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 successful. That way, the delegate 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. + /// + /// If you choose to retry after a duration, the duration should be chosen using the + /// [exponential backoff algorithm](http://en.wikipedia.org/wiki/Exponential_backoff). + /// + /// Return retry information. + fn http_error(&mut self, &hyper::Error) -> 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 it as a general information about the + /// impending failure. + /// The given Error provides information about why the token couldn't be acquired in the + /// first place + fn token(&mut self, err: &error::Error) -> Option { + let _ = err; + 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/canceled, 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()`. + /// It will also be called with None after a successful upload, which allows the delegate + /// to forget the URL. That way, we will not attempt to resume an upload that has already + /// finished. + fn store_upload_url(&mut self, url: Option<&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: &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. + /// + /// If you choose to retry after a duration, the duration should be chosen using the + /// [exponential backoff algorithm](http://en.wikipedia.org/wiki/Exponential_backoff). + fn http_failure(&mut self, _: &hyper::client::Response, Option, _: 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 {} + + +#[derive(Debug)] +pub enum Error { + /// The http connection failed + HttpError(hyper::Error), + + /// 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), + + /// Represents information about a request that was not understood by the server. + /// Details are included. + BadRequest(ErrorResponse), + + /// 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(Box), + + /// 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(String, json::Error), + + /// Indicates an HTTP repsonse with a non-success status code + Failure(hyper::client::Response), +} + + +impl Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + Error::HttpError(ref err) => err.fmt(f), + Error::UploadSizeLimitExceeded(ref resource_size, ref max_size) => + writeln!(f, "The media size {} exceeds the maximum allowed upload size of {}" + , resource_size, max_size), + Error::MissingAPIKey => { + (writeln!(f, "The application's API key was not found in the configuration")).ok(); + writeln!(f, "It is used as there are no Scopes defined for this method.") + }, + Error::BadRequest(ref err) => { + try!(writeln!(f, "Bad Requst ({}): {}", err.error.code, err.error.message)); + for err in err.error.errors.iter() { + try!(writeln!(f, " {}: {}, {}{}", + err.domain, + err.message, + err.reason, + match &err.location { + &Some(ref loc) => format!("@{}", loc), + &None => String::new(), + })); + } + Ok(()) + }, + Error::MissingToken(ref err) => + writeln!(f, "Token retrieval failed with error: {}", err), + Error::Cancelled => + writeln!(f, "Operation cancelled by delegate"), + Error::FieldClash(field) => + writeln!(f, "The custom parameter '{}' is already provided natively by the CallBuilder.", field), + Error::JsonDecodeError(ref json_str, ref err) + => writeln!(f, "{}: {}", err, json_str), + Error::Failure(ref response) => + writeln!(f, "Http status indicates failure: {:?}", response), + } + } +} + +impl error::Error for Error { + fn description(&self) -> &str { + match *self { + Error::HttpError(ref err) => err.description(), + Error::JsonDecodeError(_, ref err) => err.description(), + _ => "NO DESCRIPTION POSSIBLE - use `Display.fmt()` instead" + } + } + + fn cause(&self) -> Option<&error::Error> { + match *self { + Error::HttpError(ref err) => err.cause(), + Error::JsonDecodeError(_, ref err) => err.cause(), + _ => None + } + } +} + +/// A universal result type used as return for all calls. +pub type Result = std::result::Result; + +/// 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 + 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 following macro invocation needs to be expanded, as `include!` +// doens't support external macros +// header!{ +// #[doc="The `X-Upload-Content-Type` header."] +// (XUploadContentType, "X-Upload-Content-Type") => [Mime] + +// xupload_content_type { +// test_header!( +// test1, +// vec![b"text/plain"], +// Some(HeaderField( +// vec![Mime(TopLevel::Text, SubLevel::Plain, Vec::new())] +// ))); + +// } +// } + +/// The `X-Upload-Content-Type` header. +/// +/// Generated via rustc --pretty expanded -Z unstable-options, and manually +/// processed to be more readable. +#[derive(PartialEq, Debug, Clone)] +pub struct XUploadContentType(pub Mime); + +impl ::std::ops::Deref for XUploadContentType { + type Target = Mime; + fn deref<'a>(&'a self) -> &'a Mime { &self.0 } +} +impl ::std::ops::DerefMut for XUploadContentType { + fn deref_mut<'a>(&'a mut self) -> &'a mut Mime { &mut self.0 } +} +impl Header for XUploadContentType { + fn header_name() -> &'static str { "X-Upload-Content-Type" } + fn parse_header(raw: &[Vec]) -> hyper::error::Result { + hyper::header::parsing::from_one_raw_str(raw).map(XUploadContentType) + } +} +impl HeaderFormat for XUploadContentType { + fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { + Display::fmt(&**self, f) + } +} +impl Display for XUploadContentType { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Display::fmt(&**self, f) + } +} + +#[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]) -> hyper::error::Result { + Err(hyper::error::Error::Method) + } +} + + +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]) -> hyper::error::Result { + if raw.len() > 0 { + let v = &raw[0]; + if let Ok(s) = std::str::from_utf8(v) { + const PREFIX: &'static str = "bytes "; + if s.starts_with(PREFIX) { + if let Ok(c) = ::from_str(&s[PREFIX.len()..]) { + return Ok(RangeResponseHeader(c)) + } + } + } + } + Err(hyper::error::Error::Method) + } +} + +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, 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, A> ResumableUploadHelper<'a, A> + where A: oauth2::GetToken { + + fn query_transfer_status(&mut self) -> std::result::Result> { + 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, None) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + return Err(Ok(r)) + } + }; + return Ok(h.0.last) + } + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + return Err(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() { + Ok(s) => s, + Err(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 + }; + + self.reader.seek(SeekFrom::Start(start)).unwrap(); + loop { + let request_size = match self.content_length - start { + rs if rs > chunk_size => chunk_size, + rs => rs + }; + + 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 + } + // workaround https://github.com/rust-lang/rust/issues/22252 + let res = 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(); + match res { + 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, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + } + return Some(Ok(res)) + }, + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + return Some(Err(err)) + } + } + } + } +} + +// Copy of src/rust/cli/cmn.rs +// TODO(ST): Allow sharing common code between program types +pub fn remove_json_null_values(value: &mut json::value::Value) { + match *value { + json::value::Value::Object(ref mut map) => { + let mut for_removal = Vec::new(); + + for (key, mut value) in map.iter_mut() { + if value.is_null() { + for_removal.push(key.clone()); + } else { + remove_json_null_values(&mut value); + } + } + + for key in &for_removal { + map.remove(key); + } + } + _ => {} + } +} diff --git a/gen/classroom1/src/lib.rs b/gen/classroom1/src/lib.rs new file mode 100644 index 0000000000..79096c6958 --- /dev/null +++ b/gen/classroom1/src/lib.rs @@ -0,0 +1,201 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/api/lib.rs.mako' +// DO NOT EDIT ! + +//! This documentation was generated from *classroom* crate version *0.1.9+20151013*, where *20151013* is the exact revision of the *classroom:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +//! +//! Everything else about the *classroom* *v1* API can be found at the +//! [official documentation site](https://developers.google.com/classroom/). +//! The original source code is [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/classroom1). +//! # Features +//! +//! Handle the following *Resources* with ease from the central [hub](struct.Classroom.html) ... +//! +//! * [courses](struct.Course.html) +//! * [*aliases create*](struct.CourseAliaseCreateCall.html), [*aliases delete*](struct.CourseAliaseDeleteCall.html), [*aliases list*](struct.CourseAliaseListCall.html), [*create*](struct.CourseCreateCall.html), [*delete*](struct.CourseDeleteCall.html), [*get*](struct.CourseGetCall.html), [*list*](struct.CourseListCall.html), [*patch*](struct.CoursePatchCall.html), [*students create*](struct.CourseStudentCreateCall.html), [*students delete*](struct.CourseStudentDeleteCall.html), [*students get*](struct.CourseStudentGetCall.html), [*students list*](struct.CourseStudentListCall.html), [*teachers create*](struct.CourseTeacherCreateCall.html), [*teachers delete*](struct.CourseTeacherDeleteCall.html), [*teachers get*](struct.CourseTeacherGetCall.html), [*teachers list*](struct.CourseTeacherListCall.html) and [*update*](struct.CourseUpdateCall.html) +//! * [invitations](struct.Invitation.html) +//! * [*accept*](struct.InvitationAcceptCall.html), [*create*](struct.InvitationCreateCall.html), [*delete*](struct.InvitationDeleteCall.html), [*get*](struct.InvitationGetCall.html) and [*list*](struct.InvitationListCall.html) +//! * [user profiles](struct.UserProfile.html) +//! * [*get*](struct.UserProfileGetCall.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.Classroom.html)** +//! * a central object to maintain state and allow accessing all *Activities* +//! * creates [*Method Builders*](trait.MethodsBuilder.html) which in turn +//! allow access to individual [*Call Builders*](trait.CallBuilder.html) +//! * **[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* +//! +//! All *structures* are marked with applicable traits to further categorize them and ease browsing. +//! +//! Generally speaking, you can invoke *Activities* like this: +//! +//! ```Rust,ignore +//! let r = hub.resource().activity(...).doit() +//! ``` +//! +//! Or specifically ... +//! +//! ```ignore +//! let r = hub.courses().update(...).doit() +//! let r = hub.courses().list(...).doit() +//! let r = hub.courses().teachers_list(...).doit() +//! let r = hub.courses().get(...).doit() +//! let r = hub.courses().students_delete(...).doit() +//! let r = hub.courses().patch(...).doit() +//! let r = hub.courses().aliases_create(...).doit() +//! let r = hub.courses().teachers_delete(...).doit() +//! let r = hub.courses().students_create(...).doit() +//! let r = hub.courses().students_get(...).doit() +//! let r = hub.courses().aliases_delete(...).doit() +//! let r = hub.courses().teachers_create(...).doit() +//! let r = hub.courses().teachers_get(...).doit() +//! let r = hub.courses().create(...).doit() +//! let r = hub.courses().students_list(...).doit() +//! let r = hub.courses().aliases_list(...).doit() +//! let r = hub.courses().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-classroom1 = "*" +//! ``` +//! +//! ## A complete example +//! +//! ```test_harness,no_run +//! extern crate hyper; +//! extern crate yup_oauth2 as oauth2; +//! extern crate google_classroom1 as classroom1; +//! use classroom1::{Result, Error}; +//! # #[test] fn egal() { +//! use std::default::Default; +//! use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +//! use classroom1::Classroom; +//! +//! // 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 = Classroom::new(hyper::Client::new(), auth); +//! // You can configure optional parameters by calling the respective setters at will, and +//! // execute the final call using `doit()`. +//! // Values shown here are possibly random and not representative ! +//! let result = hub.courses().list() +//! .teacher_id("sea") +//! .student_id("et") +//! .page_token("duo") +//! .page_size(-21) +//! .doit(); +//! +//! match result { +//! Err(e) => match e { +//! // The Error enum provides details about what exactly happened. +//! // You can also just use its `Debug`, `Display` or `Error` traits +//! Error::HttpError(_) +//! |Error::MissingAPIKey +//! |Error::MissingToken(_) +//! |Error::Cancelled +//! |Error::UploadSizeLimitExceeded(_, _) +//! |Error::Failure(_) +//! |Error::BadRequest(_) +//! |Error::FieldClash(_) +//! |Error::JsonDecodeError(_, _) => println!("{}", e), +//! }, +//! Ok(res) => println!("Success: {:?}", res), +//! } +//! # } +//! ``` +//! ## 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 Downloads +//! 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 identifiable 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 moved +//! +//! 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 +//! +//! + +// 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)] + +include!(concat!(env!("OUT_DIR"), "/lib.rs")); \ No newline at end of file diff --git a/gen/classroom1/src/lib.rs.in b/gen/classroom1/src/lib.rs.in new file mode 100644 index 0000000000..ee83a72388 --- /dev/null +++ b/gen/classroom1/src/lib.rs.in @@ -0,0 +1,6990 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/api/lib.rs.in.mako' +// DO NOT EDIT ! + +extern crate hyper; +extern crate serde; +extern crate serde_json; +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 serde_json as json; +use std::io; +use std::fs; +use std::thread::sleep_ms; + +pub use cmn::{MultiPartReader, ToParts, MethodInfo, Result, Error, CallBuilder, Hub, ReadSeek, Part, + ResponseResult, RequestValue, NestedType, Delegate, DefaultDelegate, MethodsBuilder, + Resource, ErrorResponse, remove_json_null_values}; + + +// ############## +// 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 the email addresses of people in your classes + ProfileEmail, + + /// View your Google Classroom class rosters + RosterReadonly, + + /// Manage your Google Classroom classes + Course, + + /// Manage your Google Classroom class rosters + Roster, + + /// View your Google Classroom classes + CourseReadonly, + + /// View the profile photos of people in your classes + ProfilePhoto, +} + +impl AsRef for Scope { + fn as_ref(&self) -> &str { + match *self { + Scope::ProfileEmail => "https://www.googleapis.com/auth/classroom.profile.emails", + Scope::RosterReadonly => "https://www.googleapis.com/auth/classroom.rosters.readonly", + Scope::Course => "https://www.googleapis.com/auth/classroom.courses", + Scope::Roster => "https://www.googleapis.com/auth/classroom.rosters", + Scope::CourseReadonly => "https://www.googleapis.com/auth/classroom.courses.readonly", + Scope::ProfilePhoto => "https://www.googleapis.com/auth/classroom.profile.photos", + } + } +} + +impl Default for Scope { + fn default() -> Scope { + Scope::RosterReadonly + } +} + + + +// ######## +// HUB ### +// ###### + +/// Central instance to access all Classroom related resource activities +/// +/// # Examples +/// +/// Instantiate a new hub +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate yup_oauth2 as oauth2; +/// extern crate google_classroom1 as classroom1; +/// use classroom1::{Result, Error}; +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use classroom1::Classroom; +/// +/// // 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 = Classroom::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.courses().list() +/// .teacher_id("et") +/// .student_id("dolores") +/// .page_token("kasd") +/// .page_size(-22) +/// .doit(); +/// +/// match result { +/// Err(e) => match e { +/// // The Error enum provides details about what exactly happened. +/// // You can also just use its `Debug`, `Display` or `Error` traits +/// Error::HttpError(_) +/// |Error::MissingAPIKey +/// |Error::MissingToken(_) +/// |Error::Cancelled +/// |Error::UploadSizeLimitExceeded(_, _) +/// |Error::Failure(_) +/// |Error::BadRequest(_) +/// |Error::FieldClash(_) +/// |Error::JsonDecodeError(_, _) => println!("{}", e), +/// }, +/// Ok(res) => println!("Success: {:?}", res), +/// } +/// # } +/// ``` +pub struct Classroom { + client: RefCell, + auth: RefCell, + _user_agent: String, +} + +impl<'a, C, A> Hub for Classroom {} + +impl<'a, C, A> Classroom + where C: BorrowMut, A: oauth2::GetToken { + + pub fn new(client: C, authenticator: A) -> Classroom { + Classroom { + client: RefCell::new(client), + auth: RefCell::new(authenticator), + _user_agent: "google-api-rust-client/0.1.9".to_string(), + } + } + + pub fn courses(&'a self) -> CourseMethods<'a, C, A> { + CourseMethods { hub: &self } + } + pub fn invitations(&'a self) -> InvitationMethods<'a, C, A> { + InvitationMethods { hub: &self } + } + pub fn user_profiles(&'a self) -> UserProfileMethods<'a, C, A> { + UserProfileMethods { 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.9`. + /// + /// 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 when listing course aliases. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where 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 courses](struct.CourseAliaseListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ListCourseAliasesResponse { + /// Token identifying the next page of results to return. If empty, no further results are available. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// The course aliases. + pub aliases: Option>, +} + +impl ResponseResult for ListCourseAliasesResponse {} + + +/// Response when listing invitations. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where 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 invitations](struct.InvitationListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ListInvitationsResponse { + /// Token identifying the next page of results to return. If empty, no further results are available. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// Invitations that match the list request. + pub invitations: Option>, +} + +impl ResponseResult for ListInvitationsResponse {} + + +/// An invitation to join a course. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where 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 invitations](struct.InvitationListCall.html) (none) +/// * [delete invitations](struct.InvitationDeleteCall.html) (none) +/// * [create invitations](struct.InvitationCreateCall.html) (request|response) +/// * [get invitations](struct.InvitationGetCall.html) (response) +/// * [accept invitations](struct.InvitationAcceptCall.html) (none) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Invitation { + /// Identifier of the course to invite the user to. + #[serde(rename="courseId")] + pub course_id: Option, + /// Identifier of the invited user. When specified as a parameter of a request, this identifier can be set to one of the following: * the numeric identifier for the user * the email address of the user * the string literal `"me"`, indicating the requesting user + #[serde(rename="userId")] + pub user_id: Option, + /// Role to invite the user to have. Must not be `COURSE_ROLE_UNSPECIFIED`. + pub role: Option, + /// Identifier assigned by Classroom. Read-only. + pub id: Option, +} + +impl RequestValue for Invitation {} +impl Resource for Invitation {} +impl ResponseResult for Invitation {} + + +/// Response when listing teachers. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [teachers list courses](struct.CourseTeacherListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ListTeachersResponse { + /// Token identifying the next page of results to return. If empty, no further results are available. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// Teachers who match the list request. + pub teachers: Option>, +} + +impl ResponseResult for ListTeachersResponse {} + + +/// A Course in Classroom. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where 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 courses](struct.CourseUpdateCall.html) (request|response) +/// * [list courses](struct.CourseListCall.html) (none) +/// * [teachers list courses](struct.CourseTeacherListCall.html) (none) +/// * [get courses](struct.CourseGetCall.html) (response) +/// * [students delete courses](struct.CourseStudentDeleteCall.html) (none) +/// * [patch courses](struct.CoursePatchCall.html) (request|response) +/// * [aliases create courses](struct.CourseAliaseCreateCall.html) (none) +/// * [teachers delete courses](struct.CourseTeacherDeleteCall.html) (none) +/// * [students create courses](struct.CourseStudentCreateCall.html) (none) +/// * [students get courses](struct.CourseStudentGetCall.html) (none) +/// * [aliases delete courses](struct.CourseAliaseDeleteCall.html) (none) +/// * [teachers create courses](struct.CourseTeacherCreateCall.html) (none) +/// * [teachers get courses](struct.CourseTeacherGetCall.html) (none) +/// * [create courses](struct.CourseCreateCall.html) (request|response) +/// * [students list courses](struct.CourseStudentListCall.html) (none) +/// * [aliases list courses](struct.CourseAliaseListCall.html) (none) +/// * [delete courses](struct.CourseDeleteCall.html) (none) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Course { + /// Time of the most recent update to this course. Specifying this field in a course update mask will result in an error. Read-only. + #[serde(rename="updateTime")] + pub update_time: Option, + /// Optional description. For example, "We'll be learning about the structure of living creatures from a combination of textbooks, guest lectures, and lab work. Expect to be excited!" If set, this field must be a valid UTF-8 string and no longer than 30,000 characters. + pub description: Option, + /// Absolute link to this course in the Classroom web UI. Read-only. + #[serde(rename="alternateLink")] + pub alternate_link: Option, + /// Enrollment code to use when joining this course. Specifying this field in a course update mask will result in an error. Read-only. + #[serde(rename="enrollmentCode")] + pub enrollment_code: Option, + /// Section of the course. For example, "Period 2". If set, this field must be a valid UTF-8 string and no longer than 2800 characters. + pub section: Option, + /// Creation time of the course. Specifying this field in a course update mask will result in an error. Read-only. + #[serde(rename="creationTime")] + pub creation_time: Option, + /// Optional room location. For example, "301". If set, this field must be a valid UTF-8 string and no longer than 650 characters. + pub room: Option, + /// The identifier of the owner of a course. When specified as a parameter of a create course request, this field is required. The identifier can be one of the following: * the numeric identifier for the user * the email address of the user * the string literal `"me"`, indicating the requesting user This must be set in a create request. Specifying this field in a course update mask will result in an `INVALID_ARGUMENT` error. + #[serde(rename="ownerId")] + pub owner_id: Option, + /// State of the course. If unspecified, the default state is `PROVISIONED`. + #[serde(rename="courseState")] + pub course_state: Option, + /// Identifier for this course assigned by Classroom. When creating a course, you may optionally set this identifier to an alias string in the request to create a corresponding alias. The `id` is still assigned by Classroom and cannot be updated after the course is created. Specifying this field in a course update mask will result in an error. + pub id: Option, + /// Optional heading for the description. For example, "Welcome to 10th Grade Biology." If set, this field must be a valid UTF-8 string and no longer than 3600 characters. + #[serde(rename="descriptionHeading")] + pub description_heading: Option, + /// Name of the course. For example, "10th Grade Biology". The name is required. It must be between 1 and 750 characters and a valid UTF-8 string. + pub name: Option, +} + +impl RequestValue for Course {} +impl Resource for Course {} +impl ResponseResult for Course {} + + +/// Alternative identifier for a course. An alias uniquely identifies a course. It must be unique within one of the following scopes: * domain: A domain-scoped alias is visible to all users within the alias creator's domain and can be created only by a domain admin. A domain-scoped alias is often used when a course has an identifier external to Classroom. * project: A project-scoped alias is visible to any request from an application using the Developer Console project ID that created the alias and can be created by any project. A project-scoped alias is often used when an application has alternative identifiers. A random value can also be used to avoid duplicate courses in the event of transmission failures, as retrying a request will return `ALREADY_EXISTS` if a previous one has succeeded. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where 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 create courses](struct.CourseAliaseCreateCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct CourseAlias { + /// Alias string. The format of the string indicates the desired alias scoping. * `d:` indicates a domain-scoped alias. Example: `d:math_101` * `p:` indicates a project-scoped alias. Example: `p:abc123` This field has a maximum length of 256 characters. + pub alias: Option, +} + +impl RequestValue for CourseAlias {} +impl ResponseResult for CourseAlias {} + + +/// Student in a course. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [students create courses](struct.CourseStudentCreateCall.html) (request|response) +/// * [students get courses](struct.CourseStudentGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Student { + /// Identifier of the course. Read-only. + #[serde(rename="courseId")] + pub course_id: Option, + /// Global user information for the student. Read-only. + pub profile: Option, + /// Identifier of the user. When specified as a parameter of a request, this identifier can be one of the following: * the numeric identifier for the user * the email address of the user * the string literal `"me"`, indicating the requesting user + #[serde(rename="userId")] + pub user_id: Option, +} + +impl RequestValue for Student {} +impl ResponseResult for Student {} + + +/// Global user permission 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 GlobalPermission { + /// Permission value. + pub permission: Option, +} + +impl Part for GlobalPermission {} + + +/// Response when listing students. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [students list courses](struct.CourseStudentListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ListStudentsResponse { + /// Students who match the list request. + pub students: Option>, + /// Token identifying the next page of results to return. If empty, no further results are available. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, +} + +impl ResponseResult for ListStudentsResponse {} + + +/// Global information 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*). +/// +/// * [get user profiles](struct.UserProfileGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct UserProfile { + /// URL of user's profile photo. Read-only. + #[serde(rename="photoUrl")] + pub photo_url: Option, + /// Email address of the user. Read-only. + #[serde(rename="emailAddress")] + pub email_address: Option, + /// Identifier of the user. Read-only. + pub id: Option, + /// Name of the user. Read-only. + pub name: Option, + /// Global permissions of the user. Read-only. + pub permissions: Option>, +} + +impl Resource for UserProfile {} +impl ResponseResult for UserProfile {} + + +/// Response when listing courses. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where 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 courses](struct.CourseListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ListCoursesResponse { + /// Token identifying the next page of results to return. If empty, no further results are available. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// Courses that match the list request. + pub courses: Option>, +} + +impl ResponseResult for ListCoursesResponse {} + + +/// Teacher of a course. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [teachers create courses](struct.CourseTeacherCreateCall.html) (request|response) +/// * [teachers get courses](struct.CourseTeacherGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Teacher { + /// Identifier of the course. Read-only. + #[serde(rename="courseId")] + pub course_id: Option, + /// Global user information for the teacher. Read-only. + pub profile: Option, + /// Identifier of the user. When specified as a parameter of a request, this identifier can be one of the following: * the numeric identifier for the user * the email address of the user * the string literal `"me"`, indicating the requesting user + #[serde(rename="userId")] + pub user_id: Option, +} + +impl RequestValue for Teacher {} +impl ResponseResult for Teacher {} + + +/// A generic empty message that you can re-use to avoid defining duplicated empty messages in your APIs. A typical example is to use it as the request or the response type of an API method. For instance: service Foo { rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); } The JSON representation for `Empty` is empty JSON object `{}`. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where 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 invitations](struct.InvitationDeleteCall.html) (response) +/// * [teachers delete courses](struct.CourseTeacherDeleteCall.html) (response) +/// * [students delete courses](struct.CourseStudentDeleteCall.html) (response) +/// * [aliases delete courses](struct.CourseAliaseDeleteCall.html) (response) +/// * [delete courses](struct.CourseDeleteCall.html) (response) +/// * [accept invitations](struct.InvitationAcceptCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Empty; + +impl ResponseResult for Empty {} + + +/// Details of the user's name. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Name { + /// The user's full name formed by concatenating the first and last name values. Read-only. + #[serde(rename="fullName")] + pub full_name: Option, + /// The user's first name. Read-only. + #[serde(rename="givenName")] + pub given_name: Option, + /// The user's last name. Read-only. + #[serde(rename="familyName")] + pub family_name: Option, +} + +impl Part for Name {} + + + +// ################### +// MethodBuilders ### +// ################# + +/// A builder providing access to all methods supported on *course* resources. +/// It is not used directly, but through the `Classroom` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate yup_oauth2 as oauth2; +/// extern crate google_classroom1 as classroom1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use classroom1::Classroom; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Classroom::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `aliases_create(...)`, `aliases_delete(...)`, `aliases_list(...)`, `create(...)`, `delete(...)`, `get(...)`, `list(...)`, `patch(...)`, `students_create(...)`, `students_delete(...)`, `students_get(...)`, `students_list(...)`, `teachers_create(...)`, `teachers_delete(...)`, `teachers_get(...)`, `teachers_list(...)` and `update(...)` +/// // to build up your call. +/// let rb = hub.courses(); +/// # } +/// ``` +pub struct CourseMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Classroom, +} + +impl<'a, C, A> MethodsBuilder for CourseMethods<'a, C, A> {} + +impl<'a, C, A> CourseMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Returns a list of teachers of this course that the requester is permitted to view. This method returns the following error codes: * `NOT_FOUND` if the course does not exist. * `PERMISSION_DENIED` for access errors. + /// + /// # Arguments + /// + /// * `courseId` - Identifier of the course. This identifier can be either the Classroom-assigned identifier or an alias. + pub fn teachers_list(&self, course_id: &str) -> CourseTeacherListCall<'a, C, A> { + CourseTeacherListCall { + hub: self.hub, + _course_id: course_id.to_string(), + _page_token: Default::default(), + _page_size: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Returns a course. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to access the requested course or for access errors. * `NOT_FOUND` if no course exists with the requested ID. + /// + /// # Arguments + /// + /// * `id` - Identifier of the course to return. This identifier can be either the Classroom-assigned identifier or an alias. + pub fn get(&self, id: &str) -> CourseGetCall<'a, C, A> { + CourseGetCall { + hub: self.hub, + _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 a student of a course. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to delete students of this course or for access errors. * `NOT_FOUND` if no student of this course has the requested ID or if the course does not exist. + /// + /// # Arguments + /// + /// * `courseId` - Identifier of the course. This identifier can be either the Classroom-assigned identifier or an alias. + /// * `userId` - Identifier of the student to delete. The identifier can be one of the following: * the numeric identifier for the user * the email address of the user * the string literal `"me"`, indicating the requesting user + pub fn students_delete(&self, course_id: &str, user_id: &str) -> CourseStudentDeleteCall<'a, C, A> { + CourseStudentDeleteCall { + hub: self.hub, + _course_id: course_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: + /// + /// Returns a teacher of a course. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to view teachers of this course or for access errors. * `NOT_FOUND` if no teacher of this course has the requested ID or if the course does not exist. + /// + /// # Arguments + /// + /// * `courseId` - Identifier of the course. This identifier can be either the Classroom-assigned identifier or an alias. + /// * `userId` - Identifier of the teacher to return. The identifier can be one of the following: * the numeric identifier for the user * the email address of the user * the string literal `"me"`, indicating the requesting user + pub fn teachers_get(&self, course_id: &str, user_id: &str) -> CourseTeacherGetCall<'a, C, A> { + CourseTeacherGetCall { + hub: self.hub, + _course_id: course_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: + /// + /// Returns a list of aliases for a course. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to access the course or for access errors. * `NOT_FOUND` if the course does not exist. + /// + /// # Arguments + /// + /// * `courseId` - The identifier of the course. This identifier can be either the Classroom-assigned identifier or an alias. + pub fn aliases_list(&self, course_id: &str) -> CourseAliaseListCall<'a, C, A> { + CourseAliaseListCall { + hub: self.hub, + _course_id: course_id.to_string(), + _page_token: Default::default(), + _page_size: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates a course. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to modify the requested course or for access errors. * `NOT_FOUND` if no course exists with the requested ID. * `FAILED_PRECONDITION` for the following request errors: * CourseNotModifiable + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `id` - Identifier of the course to update. This identifier can be either the Classroom-assigned identifier or an alias. + pub fn update(&self, request: Course, id: &str) -> CourseUpdateCall<'a, C, A> { + CourseUpdateCall { + hub: self.hub, + _request: request, + _id: id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Creates an alias for a course. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to create the alias or for access errors. * `NOT_FOUND` if the course does not exist. * `ALREADY_EXISTS` if the alias already exists. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `courseId` - Identifier of the course to alias. This identifier can be either the Classroom-assigned identifier or an alias. + pub fn aliases_create(&self, request: CourseAlias, course_id: &str) -> CourseAliaseCreateCall<'a, C, A> { + CourseAliaseCreateCall { + hub: self.hub, + _request: request, + _course_id: course_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 list of courses that the requesting user is permitted to view, restricted to those that match the request. This method returns the following error codes: * `PERMISSION_DENIED` for access errors. * `INVALID_ARGUMENT` if the query argument is malformed. * `NOT_FOUND` if any users specified in the query arguments do not exist. + pub fn list(&self) -> CourseListCall<'a, C, A> { + CourseListCall { + hub: self.hub, + _teacher_id: Default::default(), + _student_id: Default::default(), + _page_token: Default::default(), + _page_size: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Adds a user as a student of a course. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to create students in this course or for access errors. * `NOT_FOUND` if the requested course ID does not exist. * `FAILED_PRECONDITION` if the requested user's account is disabled, for the following request errors: * CourseMemberLimitReached * CourseNotModifiable * UserGroupsMembershipLimitReached * `ALREADY_EXISTS` if the user is already a student or teacher in the course. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `courseId` - Identifier of the course to create the student in. This identifier can be either the Classroom-assigned identifier or an alias. + pub fn students_create(&self, request: Student, course_id: &str) -> CourseStudentCreateCall<'a, C, A> { + CourseStudentCreateCall { + hub: self.hub, + _request: request, + _course_id: course_id.to_string(), + _enrollment_code: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Deletes an alias of a course. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to remove the alias or for access errors. * `NOT_FOUND` if the alias does not exist. + /// + /// # Arguments + /// + /// * `courseId` - Identifier of the course whose alias should be deleted. This identifier can be either the Classroom-assigned identifier or an alias. + /// * `alias` - Alias to delete. This may not be the Classroom-assigned identifier. + pub fn aliases_delete(&self, course_id: &str, alias: &str) -> CourseAliaseDeleteCall<'a, C, A> { + CourseAliaseDeleteCall { + hub: self.hub, + _course_id: course_id.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: + /// + /// Creates a course. The user specified in `ownerId` is the owner of the created course and added as a teacher. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to create courses or for access errors. * `NOT_FOUND` if the primary teacher is not a valid user. * `FAILED_PRECONDITION` if the course owner's account is disabled or for the following request errors: * UserGroupsMembershipLimitReached * `ALREADY_EXISTS` if an alias was specified in the `id` and already exists. + /// + /// # Arguments + /// + /// * `request` - No description provided. + pub fn create(&self, request: Course) -> CourseCreateCall<'a, C, A> { + CourseCreateCall { + hub: self.hub, + _request: request, + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Returns a list of students of this course that the requester is permitted to view. This method returns the following error codes: * `NOT_FOUND` if the course does not exist. * `PERMISSION_DENIED` for access errors. + /// + /// # Arguments + /// + /// * `courseId` - Identifier of the course. This identifier can be either the Classroom-assigned identifier or an alias. + pub fn students_list(&self, course_id: &str) -> CourseStudentListCall<'a, C, A> { + CourseStudentListCall { + hub: self.hub, + _course_id: course_id.to_string(), + _page_token: Default::default(), + _page_size: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Deletes a course. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to delete the requested course or for access errors. * `NOT_FOUND` if no course exists with the requested ID. + /// + /// # Arguments + /// + /// * `id` - Identifier of the course to delete. This identifier can be either the Classroom-assigned identifier or an alias. + pub fn delete(&self, id: &str) -> CourseDeleteCall<'a, C, A> { + CourseDeleteCall { + hub: self.hub, + _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 one or more fields in a course. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to modify the requested course or for access errors. * `NOT_FOUND` if no course exists with the requested ID. * `INVALID_ARGUMENT` if invalid fields are specified in the update mask or if no update mask is supplied. * `FAILED_PRECONDITION` for the following request errors: * CourseNotModifiable + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `id` - Identifier of the course to update. This identifier can be either the Classroom-assigned identifier or an alias. + pub fn patch(&self, request: Course, id: &str) -> CoursePatchCall<'a, C, A> { + CoursePatchCall { + hub: self.hub, + _request: request, + _id: id.to_string(), + _update_mask: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Returns a student of a course. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to view students of this course or for access errors. * `NOT_FOUND` if no student of this course has the requested ID or if the course does not exist. + /// + /// # Arguments + /// + /// * `courseId` - Identifier of the course. This identifier can be either the Classroom-assigned identifier or an alias. + /// * `userId` - Identifier of the student to return. The identifier can be one of the following: * the numeric identifier for the user * the email address of the user * the string literal `"me"`, indicating the requesting user + pub fn students_get(&self, course_id: &str, user_id: &str) -> CourseStudentGetCall<'a, C, A> { + CourseStudentGetCall { + hub: self.hub, + _course_id: course_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: + /// + /// Deletes a teacher of a course. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to delete teachers of this course or for access errors. * `NOT_FOUND` if no teacher of this course has the requested ID or if the course does not exist. * `FAILED_PRECONDITION` if the requested ID belongs to the primary teacher of this course. + /// + /// # Arguments + /// + /// * `courseId` - Identifier of the course. This identifier can be either the Classroom-assigned identifier or an alias. + /// * `userId` - Identifier of the teacher to delete. The identifier can be one of the following: * the numeric identifier for the user * the email address of the user * the string literal `"me"`, indicating the requesting user + pub fn teachers_delete(&self, course_id: &str, user_id: &str) -> CourseTeacherDeleteCall<'a, C, A> { + CourseTeacherDeleteCall { + hub: self.hub, + _course_id: course_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: + /// + /// Creates a teacher of a course. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to create teachers in this course or for access errors. * `NOT_FOUND` if the requested course ID does not exist. * `FAILED_PRECONDITION` if the requested user's account is disabled, for the following request errors: * CourseMemberLimitReached * CourseNotModifiable * CourseTeacherLimitReached * UserGroupsMembershipLimitReached * `ALREADY_EXISTS` if the user is already a teacher or student in the course. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `courseId` - Identifier of the course. This identifier can be either the Classroom-assigned identifier or an alias. + pub fn teachers_create(&self, request: Teacher, course_id: &str) -> CourseTeacherCreateCall<'a, C, A> { + CourseTeacherCreateCall { + hub: self.hub, + _request: request, + _course_id: course_id.to_string(), + _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 `Classroom` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate yup_oauth2 as oauth2; +/// extern crate google_classroom1 as classroom1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use classroom1::Classroom; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Classroom::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_profiles(); +/// # } +/// ``` +pub struct UserProfileMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Classroom, +} + +impl<'a, C, A> MethodsBuilder for UserProfileMethods<'a, C, A> {} + +impl<'a, C, A> UserProfileMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Returns a user profile. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to access this user profile or if no profile exists with the requested ID or for access errors. + /// + /// # Arguments + /// + /// * `userId` - Identifier of the profile to return. The identifier can be one of the following: * the numeric identifier for the user * the email address of the user * the string literal `"me"`, indicating the requesting user + pub fn get(&self, user_id: &str) -> UserProfileGetCall<'a, C, A> { + UserProfileGetCall { + 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 *invitation* resources. +/// It is not used directly, but through the `Classroom` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate yup_oauth2 as oauth2; +/// extern crate google_classroom1 as classroom1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use classroom1::Classroom; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Classroom::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `accept(...)`, `create(...)`, `delete(...)`, `get(...)` and `list(...)` +/// // to build up your call. +/// let rb = hub.invitations(); +/// # } +/// ``` +pub struct InvitationMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Classroom, +} + +impl<'a, C, A> MethodsBuilder for InvitationMethods<'a, C, A> {} + +impl<'a, C, A> InvitationMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Deletes an invitation. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to delete the requested invitation or for access errors. * `NOT_FOUND` if no invitation exists with the requested ID. + /// + /// # Arguments + /// + /// * `id` - Identifier of the invitation to delete. + pub fn delete(&self, id: &str) -> InvitationDeleteCall<'a, C, A> { + InvitationDeleteCall { + hub: self.hub, + _id: id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Creates an invitation. Only one invitation for a user and course may exist at a time. Delete and re-create an invitation to make changes. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to create invitations for this course or for access errors. * `NOT_FOUND` if the course or the user does not exist. * `FAILED_PRECONDITION` if the requested user's account is disabled or if the user already has this role or a role with greater permissions. * `ALREADY_EXISTS` if an invitation for the specified user and course already exists. + /// + /// # Arguments + /// + /// * `request` - No description provided. + pub fn create(&self, request: Invitation) -> InvitationCreateCall<'a, C, A> { + InvitationCreateCall { + hub: self.hub, + _request: request, + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Returns a list of invitations that the requesting user is permitted to view, restricted to those that match the list request. *Note:* At least one of `user_id` or `course_id` must be supplied. Both fields can be supplied. This method returns the following error codes: * `PERMISSION_DENIED` for access errors. + pub fn list(&self) -> InvitationListCall<'a, C, A> { + InvitationListCall { + hub: self.hub, + _user_id: Default::default(), + _page_token: Default::default(), + _page_size: Default::default(), + _course_id: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Returns an invitation. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to view the requested invitation or for access errors. * `NOT_FOUND` if no invitation exists with the requested ID. + /// + /// # Arguments + /// + /// * `id` - Identifier of the invitation to return. + pub fn get(&self, id: &str) -> InvitationGetCall<'a, C, A> { + InvitationGetCall { + hub: self.hub, + _id: id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Accepts an invitation, removing it and adding the invited user to the teachers or students (as appropriate) of the specified course. Only the invited user may accept an invitation. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to accept the requested invitation or for access errors. * `FAILED_PRECONDITION` for the following request errors: * CourseMemberLimitReached * CourseNotModifiable * CourseTeacherLimitReached * UserGroupsMembershipLimitReached * `NOT_FOUND` if no invitation exists with the requested ID. + /// + /// # Arguments + /// + /// * `id` - Identifier of the invitation to accept. + pub fn accept(&self, id: &str) -> InvitationAcceptCall<'a, C, A> { + InvitationAcceptCall { + hub: self.hub, + _id: id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + + + +// ################### +// CallBuilders ### +// ################# + +/// Returns a list of teachers of this course that the requester is permitted to view. This method returns the following error codes: * `NOT_FOUND` if the course does not exist. * `PERMISSION_DENIED` for access errors. +/// +/// A builder for the *teachers.list* method supported by a *course* resource. +/// It is not used directly, but through a `CourseMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_classroom1 as classroom1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use classroom1::Classroom; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Classroom::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.courses().teachers_list("courseId") +/// .page_token("justo") +/// .page_size(-1) +/// .doit(); +/// # } +/// ``` +pub struct CourseTeacherListCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Classroom, + _course_id: String, + _page_token: Option, + _page_size: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for CourseTeacherListCall<'a, C, A> {} + +impl<'a, C, A> CourseTeacherListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ListTeachersResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "classroom.courses.teachers.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("courseId", self._course_id.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())); + } + for &field in ["alt", "courseId", "pageToken", "pageSize"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://classroom.googleapis.com/v1/courses/{courseId}/teachers".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::RosterReadonly.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{courseId}", "courseId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["courseId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Identifier of the course. This identifier can be either the Classroom-assigned identifier or an alias. + /// + /// Sets the *course id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn course_id(mut self, new_value: &str) -> CourseTeacherListCall<'a, C, A> { + self._course_id = new_value.to_string(); + self + } + /// nextPageToken value returned from a previous list call, indicating that the subsequent page of results should be returned. The list request must be otherwise identical to the one that resulted in this token. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> CourseTeacherListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Maximum number of items to return. Zero means no maximum. The server may return fewer than the specified number of results. + /// + /// Sets the *page size* query property to the given value. + pub fn page_size(mut self, new_value: i32) -> CourseTeacherListCall<'a, C, A> { + self._page_size = Some(new_value); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CourseTeacherListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> CourseTeacherListCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::RosterReadonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CourseTeacherListCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Returns a course. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to access the requested course or for access errors. * `NOT_FOUND` if no course exists with the requested ID. +/// +/// A builder for the *get* method supported by a *course* resource. +/// It is not used directly, but through a `CourseMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_classroom1 as classroom1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use classroom1::Classroom; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Classroom::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.courses().get("id") +/// .doit(); +/// # } +/// ``` +pub struct CourseGetCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Classroom, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for CourseGetCall<'a, C, A> {} + +impl<'a, C, A> CourseGetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Course)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "classroom.courses.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 Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://classroom.googleapis.com/v1/courses/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CourseReadonly.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Identifier of the course to return. This identifier can be either the Classroom-assigned identifier or an alias. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> CourseGetCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CourseGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> CourseGetCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CourseReadonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CourseGetCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Deletes a student of a course. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to delete students of this course or for access errors. * `NOT_FOUND` if no student of this course has the requested ID or if the course does not exist. +/// +/// A builder for the *students.delete* method supported by a *course* resource. +/// It is not used directly, but through a `CourseMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_classroom1 as classroom1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use classroom1::Classroom; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Classroom::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.courses().students_delete("courseId", "userId") +/// .doit(); +/// # } +/// ``` +pub struct CourseStudentDeleteCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Classroom, + _course_id: String, + _user_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for CourseStudentDeleteCall<'a, C, A> {} + +impl<'a, C, A> CourseStudentDeleteCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Empty)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "classroom.courses.students.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("courseId", self._course_id.to_string())); + params.push(("userId", self._user_id.to_string())); + for &field in ["alt", "courseId", "userId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://classroom.googleapis.com/v1/courses/{courseId}/students/{userId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Roster.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{courseId}", "courseId"), ("{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 ["userId", "courseId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Identifier of the course. This identifier can be either the Classroom-assigned identifier or an alias. + /// + /// Sets the *course id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn course_id(mut self, new_value: &str) -> CourseStudentDeleteCall<'a, C, A> { + self._course_id = new_value.to_string(); + self + } + /// Identifier of the student to delete. The identifier can be one of the following: * the numeric identifier for the user * the email address of the user * the string literal `"me"`, indicating the requesting user + /// + /// 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. + pub fn user_id(mut self, new_value: &str) -> CourseStudentDeleteCall<'a, C, A> { + self._user_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CourseStudentDeleteCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> CourseStudentDeleteCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Roster`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CourseStudentDeleteCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Returns a teacher of a course. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to view teachers of this course or for access errors. * `NOT_FOUND` if no teacher of this course has the requested ID or if the course does not exist. +/// +/// A builder for the *teachers.get* method supported by a *course* resource. +/// It is not used directly, but through a `CourseMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_classroom1 as classroom1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use classroom1::Classroom; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Classroom::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.courses().teachers_get("courseId", "userId") +/// .doit(); +/// # } +/// ``` +pub struct CourseTeacherGetCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Classroom, + _course_id: String, + _user_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for CourseTeacherGetCall<'a, C, A> {} + +impl<'a, C, A> CourseTeacherGetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Teacher)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "classroom.courses.teachers.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("courseId", self._course_id.to_string())); + params.push(("userId", self._user_id.to_string())); + for &field in ["alt", "courseId", "userId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://classroom.googleapis.com/v1/courses/{courseId}/teachers/{userId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::RosterReadonly.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{courseId}", "courseId"), ("{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 ["userId", "courseId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Identifier of the course. This identifier can be either the Classroom-assigned identifier or an alias. + /// + /// Sets the *course id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn course_id(mut self, new_value: &str) -> CourseTeacherGetCall<'a, C, A> { + self._course_id = new_value.to_string(); + self + } + /// Identifier of the teacher to return. The identifier can be one of the following: * the numeric identifier for the user * the email address of the user * the string literal `"me"`, indicating the requesting user + /// + /// 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. + pub fn user_id(mut self, new_value: &str) -> CourseTeacherGetCall<'a, C, A> { + self._user_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CourseTeacherGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> CourseTeacherGetCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::RosterReadonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CourseTeacherGetCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Returns a list of aliases for a course. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to access the course or for access errors. * `NOT_FOUND` if the course does not exist. +/// +/// A builder for the *aliases.list* method supported by a *course* resource. +/// It is not used directly, but through a `CourseMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_classroom1 as classroom1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use classroom1::Classroom; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Classroom::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.courses().aliases_list("courseId") +/// .page_token("sadipscing") +/// .page_size(-31) +/// .doit(); +/// # } +/// ``` +pub struct CourseAliaseListCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Classroom, + _course_id: String, + _page_token: Option, + _page_size: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for CourseAliaseListCall<'a, C, A> {} + +impl<'a, C, A> CourseAliaseListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ListCourseAliasesResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "classroom.courses.aliases.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("courseId", self._course_id.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())); + } + for &field in ["alt", "courseId", "pageToken", "pageSize"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://classroom.googleapis.com/v1/courses/{courseId}/aliases".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CourseReadonly.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{courseId}", "courseId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["courseId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The identifier of the course. This identifier can be either the Classroom-assigned identifier or an alias. + /// + /// Sets the *course id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn course_id(mut self, new_value: &str) -> CourseAliaseListCall<'a, C, A> { + self._course_id = new_value.to_string(); + self + } + /// nextPageToken value returned from a previous list call, indicating that the subsequent page of results should be returned. The list request must be otherwise identical to the one that resulted in this token. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> CourseAliaseListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Maximum number of items to return. Zero or unspecified indicates that the server may assign a maximum. The server may return fewer than the specified number of results. + /// + /// Sets the *page size* query property to the given value. + pub fn page_size(mut self, new_value: i32) -> CourseAliaseListCall<'a, C, A> { + self._page_size = Some(new_value); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CourseAliaseListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> CourseAliaseListCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CourseReadonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CourseAliaseListCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Updates a course. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to modify the requested course or for access errors. * `NOT_FOUND` if no course exists with the requested ID. * `FAILED_PRECONDITION` for the following request errors: * CourseNotModifiable +/// +/// A builder for the *update* method supported by a *course* resource. +/// It is not used directly, but through a `CourseMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_classroom1 as classroom1; +/// use classroom1::Course; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use classroom1::Classroom; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Classroom::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req = Course::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.courses().update(req, "id") +/// .doit(); +/// # } +/// ``` +pub struct CourseUpdateCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Classroom, + _request: Course, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for CourseUpdateCall<'a, C, A> {} + +impl<'a, C, A> CourseUpdateCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Course)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "classroom.courses.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 Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://classroom.googleapis.com/v1/courses/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Course.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: Course) -> CourseUpdateCall<'a, C, A> { + self._request = new_value; + self + } + /// Identifier of the course to update. This identifier can be either the Classroom-assigned identifier or an alias. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> CourseUpdateCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CourseUpdateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> CourseUpdateCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Course`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CourseUpdateCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Creates an alias for a course. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to create the alias or for access errors. * `NOT_FOUND` if the course does not exist. * `ALREADY_EXISTS` if the alias already exists. +/// +/// A builder for the *aliases.create* method supported by a *course* resource. +/// It is not used directly, but through a `CourseMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_classroom1 as classroom1; +/// use classroom1::CourseAlias; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use classroom1::Classroom; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Classroom::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req = CourseAlias::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.courses().aliases_create(req, "courseId") +/// .doit(); +/// # } +/// ``` +pub struct CourseAliaseCreateCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Classroom, + _request: CourseAlias, + _course_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for CourseAliaseCreateCall<'a, C, A> {} + +impl<'a, C, A> CourseAliaseCreateCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, CourseAlias)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "classroom.courses.aliases.create", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("courseId", self._course_id.to_string())); + for &field in ["alt", "courseId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://classroom.googleapis.com/v1/courses/{courseId}/aliases".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Course.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{courseId}", "courseId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["courseId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: CourseAlias) -> CourseAliaseCreateCall<'a, C, A> { + self._request = new_value; + self + } + /// Identifier of the course to alias. This identifier can be either the Classroom-assigned identifier or an alias. + /// + /// Sets the *course id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn course_id(mut self, new_value: &str) -> CourseAliaseCreateCall<'a, C, A> { + self._course_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CourseAliaseCreateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> CourseAliaseCreateCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Course`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CourseAliaseCreateCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Returns a list of courses that the requesting user is permitted to view, restricted to those that match the request. This method returns the following error codes: * `PERMISSION_DENIED` for access errors. * `INVALID_ARGUMENT` if the query argument is malformed. * `NOT_FOUND` if any users specified in the query arguments do not exist. +/// +/// A builder for the *list* method supported by a *course* resource. +/// It is not used directly, but through a `CourseMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_classroom1 as classroom1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use classroom1::Classroom; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Classroom::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.courses().list() +/// .teacher_id("justo") +/// .student_id("justo") +/// .page_token("et") +/// .page_size(-17) +/// .doit(); +/// # } +/// ``` +pub struct CourseListCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Classroom, + _teacher_id: Option, + _student_id: Option, + _page_token: Option, + _page_size: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for CourseListCall<'a, C, A> {} + +impl<'a, C, A> CourseListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ListCoursesResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "classroom.courses.list", + 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._teacher_id { + params.push(("teacherId", value.to_string())); + } + if let Some(value) = self._student_id { + params.push(("studentId", 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())); + } + for &field in ["alt", "teacherId", "studentId", "pageToken", "pageSize"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://classroom.googleapis.com/v1/courses".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CourseReadonly.as_ref().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Restricts returned courses to those having a teacher with the specified identifier. The identifier can be one of the following: * the numeric identifier for the user * the email address of the user * the string literal `"me"`, indicating the requesting user + /// + /// Sets the *teacher id* query property to the given value. + pub fn teacher_id(mut self, new_value: &str) -> CourseListCall<'a, C, A> { + self._teacher_id = Some(new_value.to_string()); + self + } + /// Restricts returned courses to those having a student with the specified identifier. The identifier can be one of the following: * the numeric identifier for the user * the email address of the user * the string literal `"me"`, indicating the requesting user + /// + /// Sets the *student id* query property to the given value. + pub fn student_id(mut self, new_value: &str) -> CourseListCall<'a, C, A> { + self._student_id = Some(new_value.to_string()); + self + } + /// nextPageToken value returned from a previous list call, indicating that the subsequent page of results should be returned. The list request must be otherwise identical to the one that resulted in this token. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> CourseListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Maximum number of items to return. Zero or unspecified indicates that the server may assign a maximum. The server may return fewer than the specified number of results. + /// + /// Sets the *page size* query property to the given value. + pub fn page_size(mut self, new_value: i32) -> CourseListCall<'a, C, A> { + self._page_size = Some(new_value); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CourseListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> CourseListCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CourseReadonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CourseListCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Adds a user as a student of a course. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to create students in this course or for access errors. * `NOT_FOUND` if the requested course ID does not exist. * `FAILED_PRECONDITION` if the requested user's account is disabled, for the following request errors: * CourseMemberLimitReached * CourseNotModifiable * UserGroupsMembershipLimitReached * `ALREADY_EXISTS` if the user is already a student or teacher in the course. +/// +/// A builder for the *students.create* method supported by a *course* resource. +/// It is not used directly, but through a `CourseMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_classroom1 as classroom1; +/// use classroom1::Student; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use classroom1::Classroom; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Classroom::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req = Student::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.courses().students_create(req, "courseId") +/// .enrollment_code("ipsum") +/// .doit(); +/// # } +/// ``` +pub struct CourseStudentCreateCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Classroom, + _request: Student, + _course_id: String, + _enrollment_code: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for CourseStudentCreateCall<'a, C, A> {} + +impl<'a, C, A> CourseStudentCreateCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Student)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "classroom.courses.students.create", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("courseId", self._course_id.to_string())); + if let Some(value) = self._enrollment_code { + params.push(("enrollmentCode", value.to_string())); + } + for &field in ["alt", "courseId", "enrollmentCode"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://classroom.googleapis.com/v1/courses/{courseId}/students".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::ProfileEmail.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{courseId}", "courseId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["courseId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: Student) -> CourseStudentCreateCall<'a, C, A> { + self._request = new_value; + self + } + /// Identifier of the course to create the student in. This identifier can be either the Classroom-assigned identifier or an alias. + /// + /// Sets the *course id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn course_id(mut self, new_value: &str) -> CourseStudentCreateCall<'a, C, A> { + self._course_id = new_value.to_string(); + self + } + /// Enrollment code of the course to create the student in. This code is required if userId corresponds to the requesting user; it may be omitted if the requesting user has administrative permissions to create students for any user. + /// + /// Sets the *enrollment code* query property to the given value. + pub fn enrollment_code(mut self, new_value: &str) -> CourseStudentCreateCall<'a, C, A> { + self._enrollment_code = Some(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CourseStudentCreateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> CourseStudentCreateCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::ProfileEmail`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CourseStudentCreateCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Deletes an alias of a course. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to remove the alias or for access errors. * `NOT_FOUND` if the alias does not exist. +/// +/// A builder for the *aliases.delete* method supported by a *course* resource. +/// It is not used directly, but through a `CourseMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_classroom1 as classroom1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use classroom1::Classroom; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Classroom::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.courses().aliases_delete("courseId", "alias") +/// .doit(); +/// # } +/// ``` +pub struct CourseAliaseDeleteCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Classroom, + _course_id: String, + _alias: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for CourseAliaseDeleteCall<'a, C, A> {} + +impl<'a, C, A> CourseAliaseDeleteCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Empty)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "classroom.courses.aliases.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("courseId", self._course_id.to_string())); + params.push(("alias", self._alias.to_string())); + for &field in ["alt", "courseId", "alias"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://classroom.googleapis.com/v1/courses/{courseId}/aliases/{alias}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Course.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{courseId}", "courseId"), ("{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 ["alias", "courseId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Identifier of the course whose alias should be deleted. This identifier can be either the Classroom-assigned identifier or an alias. + /// + /// Sets the *course id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn course_id(mut self, new_value: &str) -> CourseAliaseDeleteCall<'a, C, A> { + self._course_id = new_value.to_string(); + self + } + /// Alias to delete. This may not be the Classroom-assigned identifier. + /// + /// 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. + pub fn alias(mut self, new_value: &str) -> CourseAliaseDeleteCall<'a, C, A> { + self._alias = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CourseAliaseDeleteCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> CourseAliaseDeleteCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Course`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CourseAliaseDeleteCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Creates a course. The user specified in `ownerId` is the owner of the created course and added as a teacher. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to create courses or for access errors. * `NOT_FOUND` if the primary teacher is not a valid user. * `FAILED_PRECONDITION` if the course owner's account is disabled or for the following request errors: * UserGroupsMembershipLimitReached * `ALREADY_EXISTS` if an alias was specified in the `id` and already exists. +/// +/// A builder for the *create* method supported by a *course* resource. +/// It is not used directly, but through a `CourseMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_classroom1 as classroom1; +/// use classroom1::Course; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use classroom1::Classroom; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Classroom::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req = Course::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.courses().create(req) +/// .doit(); +/// # } +/// ``` +pub struct CourseCreateCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Classroom, + _request: Course, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for CourseCreateCall<'a, C, A> {} + +impl<'a, C, A> CourseCreateCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Course)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "classroom.courses.create", + 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 Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://classroom.googleapis.com/v1/courses".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Course.as_ref().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: Course) -> CourseCreateCall<'a, C, A> { + self._request = new_value; + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CourseCreateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> CourseCreateCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Course`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CourseCreateCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Returns a list of students of this course that the requester is permitted to view. This method returns the following error codes: * `NOT_FOUND` if the course does not exist. * `PERMISSION_DENIED` for access errors. +/// +/// A builder for the *students.list* method supported by a *course* resource. +/// It is not used directly, but through a `CourseMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_classroom1 as classroom1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use classroom1::Classroom; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Classroom::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.courses().students_list("courseId") +/// .page_token("aliquyam") +/// .page_size(-9) +/// .doit(); +/// # } +/// ``` +pub struct CourseStudentListCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Classroom, + _course_id: String, + _page_token: Option, + _page_size: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for CourseStudentListCall<'a, C, A> {} + +impl<'a, C, A> CourseStudentListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ListStudentsResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "classroom.courses.students.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("courseId", self._course_id.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())); + } + for &field in ["alt", "courseId", "pageToken", "pageSize"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://classroom.googleapis.com/v1/courses/{courseId}/students".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::RosterReadonly.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{courseId}", "courseId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["courseId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Identifier of the course. This identifier can be either the Classroom-assigned identifier or an alias. + /// + /// Sets the *course id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn course_id(mut self, new_value: &str) -> CourseStudentListCall<'a, C, A> { + self._course_id = new_value.to_string(); + self + } + /// nextPageToken value returned from a previous list call, indicating that the subsequent page of results should be returned. The list request must be otherwise identical to the one that resulted in this token. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> CourseStudentListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Maximum number of items to return. Zero means no maximum. The server may return fewer than the specified number of results. + /// + /// Sets the *page size* query property to the given value. + pub fn page_size(mut self, new_value: i32) -> CourseStudentListCall<'a, C, A> { + self._page_size = Some(new_value); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CourseStudentListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> CourseStudentListCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::RosterReadonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CourseStudentListCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Deletes a course. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to delete the requested course or for access errors. * `NOT_FOUND` if no course exists with the requested ID. +/// +/// A builder for the *delete* method supported by a *course* resource. +/// It is not used directly, but through a `CourseMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_classroom1 as classroom1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use classroom1::Classroom; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Classroom::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.courses().delete("id") +/// .doit(); +/// # } +/// ``` +pub struct CourseDeleteCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Classroom, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for CourseDeleteCall<'a, C, A> {} + +impl<'a, C, A> CourseDeleteCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Empty)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "classroom.courses.delete", + http_method: hyper::method::Method::Delete }); + 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 Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://classroom.googleapis.com/v1/courses/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Course.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Identifier of the course to delete. This identifier can be either the Classroom-assigned identifier or an alias. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> CourseDeleteCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CourseDeleteCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> CourseDeleteCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Course`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CourseDeleteCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Updates one or more fields in a course. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to modify the requested course or for access errors. * `NOT_FOUND` if no course exists with the requested ID. * `INVALID_ARGUMENT` if invalid fields are specified in the update mask or if no update mask is supplied. * `FAILED_PRECONDITION` for the following request errors: * CourseNotModifiable +/// +/// A builder for the *patch* method supported by a *course* resource. +/// It is not used directly, but through a `CourseMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_classroom1 as classroom1; +/// use classroom1::Course; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use classroom1::Classroom; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Classroom::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req = Course::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.courses().patch(req, "id") +/// .update_mask("erat") +/// .doit(); +/// # } +/// ``` +pub struct CoursePatchCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Classroom, + _request: Course, + _id: String, + _update_mask: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for CoursePatchCall<'a, C, A> {} + +impl<'a, C, A> CoursePatchCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Course)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "classroom.courses.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("id", self._id.to_string())); + if let Some(value) = self._update_mask { + params.push(("updateMask", value.to_string())); + } + for &field in ["alt", "id", "updateMask"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://classroom.googleapis.com/v1/courses/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Course.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: Course) -> CoursePatchCall<'a, C, A> { + self._request = new_value; + self + } + /// Identifier of the course to update. This identifier can be either the Classroom-assigned identifier or an alias. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> CoursePatchCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// Mask that identifies which fields on the course to update. This field is required to do an update. The update will fail if invalid fields are specified. The following fields are valid: * `name` * `section` * `descriptionHeading` * `description` * `room` * `courseState` When set in a query parameter, this field should be specified as `updateMask=,,...` + /// + /// Sets the *update mask* query property to the given value. + pub fn update_mask(mut self, new_value: &str) -> CoursePatchCall<'a, C, A> { + self._update_mask = Some(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CoursePatchCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> CoursePatchCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Course`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CoursePatchCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Returns a student of a course. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to view students of this course or for access errors. * `NOT_FOUND` if no student of this course has the requested ID or if the course does not exist. +/// +/// A builder for the *students.get* method supported by a *course* resource. +/// It is not used directly, but through a `CourseMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_classroom1 as classroom1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use classroom1::Classroom; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Classroom::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.courses().students_get("courseId", "userId") +/// .doit(); +/// # } +/// ``` +pub struct CourseStudentGetCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Classroom, + _course_id: String, + _user_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for CourseStudentGetCall<'a, C, A> {} + +impl<'a, C, A> CourseStudentGetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Student)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "classroom.courses.students.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("courseId", self._course_id.to_string())); + params.push(("userId", self._user_id.to_string())); + for &field in ["alt", "courseId", "userId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://classroom.googleapis.com/v1/courses/{courseId}/students/{userId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::RosterReadonly.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{courseId}", "courseId"), ("{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 ["userId", "courseId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Identifier of the course. This identifier can be either the Classroom-assigned identifier or an alias. + /// + /// Sets the *course id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn course_id(mut self, new_value: &str) -> CourseStudentGetCall<'a, C, A> { + self._course_id = new_value.to_string(); + self + } + /// Identifier of the student to return. The identifier can be one of the following: * the numeric identifier for the user * the email address of the user * the string literal `"me"`, indicating the requesting user + /// + /// 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. + pub fn user_id(mut self, new_value: &str) -> CourseStudentGetCall<'a, C, A> { + self._user_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CourseStudentGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> CourseStudentGetCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::RosterReadonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CourseStudentGetCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Deletes a teacher of a course. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to delete teachers of this course or for access errors. * `NOT_FOUND` if no teacher of this course has the requested ID or if the course does not exist. * `FAILED_PRECONDITION` if the requested ID belongs to the primary teacher of this course. +/// +/// A builder for the *teachers.delete* method supported by a *course* resource. +/// It is not used directly, but through a `CourseMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_classroom1 as classroom1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use classroom1::Classroom; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Classroom::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.courses().teachers_delete("courseId", "userId") +/// .doit(); +/// # } +/// ``` +pub struct CourseTeacherDeleteCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Classroom, + _course_id: String, + _user_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for CourseTeacherDeleteCall<'a, C, A> {} + +impl<'a, C, A> CourseTeacherDeleteCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Empty)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "classroom.courses.teachers.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("courseId", self._course_id.to_string())); + params.push(("userId", self._user_id.to_string())); + for &field in ["alt", "courseId", "userId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://classroom.googleapis.com/v1/courses/{courseId}/teachers/{userId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Roster.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{courseId}", "courseId"), ("{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 ["userId", "courseId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Identifier of the course. This identifier can be either the Classroom-assigned identifier or an alias. + /// + /// Sets the *course id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn course_id(mut self, new_value: &str) -> CourseTeacherDeleteCall<'a, C, A> { + self._course_id = new_value.to_string(); + self + } + /// Identifier of the teacher to delete. The identifier can be one of the following: * the numeric identifier for the user * the email address of the user * the string literal `"me"`, indicating the requesting user + /// + /// 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. + pub fn user_id(mut self, new_value: &str) -> CourseTeacherDeleteCall<'a, C, A> { + self._user_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CourseTeacherDeleteCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> CourseTeacherDeleteCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Roster`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CourseTeacherDeleteCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Creates a teacher of a course. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to create teachers in this course or for access errors. * `NOT_FOUND` if the requested course ID does not exist. * `FAILED_PRECONDITION` if the requested user's account is disabled, for the following request errors: * CourseMemberLimitReached * CourseNotModifiable * CourseTeacherLimitReached * UserGroupsMembershipLimitReached * `ALREADY_EXISTS` if the user is already a teacher or student in the course. +/// +/// A builder for the *teachers.create* method supported by a *course* resource. +/// It is not used directly, but through a `CourseMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_classroom1 as classroom1; +/// use classroom1::Teacher; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use classroom1::Classroom; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Classroom::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req = Teacher::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.courses().teachers_create(req, "courseId") +/// .doit(); +/// # } +/// ``` +pub struct CourseTeacherCreateCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Classroom, + _request: Teacher, + _course_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for CourseTeacherCreateCall<'a, C, A> {} + +impl<'a, C, A> CourseTeacherCreateCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Teacher)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "classroom.courses.teachers.create", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("courseId", self._course_id.to_string())); + for &field in ["alt", "courseId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://classroom.googleapis.com/v1/courses/{courseId}/teachers".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::ProfileEmail.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{courseId}", "courseId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["courseId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: Teacher) -> CourseTeacherCreateCall<'a, C, A> { + self._request = new_value; + self + } + /// Identifier of the course. This identifier can be either the Classroom-assigned identifier or an alias. + /// + /// Sets the *course id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn course_id(mut self, new_value: &str) -> CourseTeacherCreateCall<'a, C, A> { + self._course_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CourseTeacherCreateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> CourseTeacherCreateCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::ProfileEmail`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> CourseTeacherCreateCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Returns a user profile. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to access this user profile or if no profile exists with the requested ID or for access errors. +/// +/// A builder for the *get* method supported by a *userProfile* resource. +/// It is not used directly, but through a `UserProfileMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_classroom1 as classroom1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use classroom1::Classroom; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Classroom::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling 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("userId") +/// .doit(); +/// # } +/// ``` +pub struct UserProfileGetCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Classroom, + _user_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for UserProfileGetCall<'a, C, A> {} + +impl<'a, C, A> UserProfileGetCall<'a, C, A> where 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: "classroom.userProfiles.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 Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://classroom.googleapis.com/v1/userProfiles/{userId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::RosterReadonly.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Identifier of the profile to return. The identifier can be one of the following: * the numeric identifier for the user * the email address of the user * the string literal `"me"`, indicating the requesting user + /// + /// 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. + pub fn user_id(mut self, new_value: &str) -> UserProfileGetCall<'a, C, A> { + self._user_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserProfileGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> UserProfileGetCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::RosterReadonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Deletes an invitation. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to delete the requested invitation or for access errors. * `NOT_FOUND` if no invitation exists with the requested ID. +/// +/// A builder for the *delete* method supported by a *invitation* resource. +/// It is not used directly, but through a `InvitationMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_classroom1 as classroom1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use classroom1::Classroom; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Classroom::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.invitations().delete("id") +/// .doit(); +/// # } +/// ``` +pub struct InvitationDeleteCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Classroom, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for InvitationDeleteCall<'a, C, A> {} + +impl<'a, C, A> InvitationDeleteCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Empty)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "classroom.invitations.delete", + http_method: hyper::method::Method::Delete }); + 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 Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://classroom.googleapis.com/v1/invitations/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Roster.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Identifier of the invitation to delete. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> InvitationDeleteCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> InvitationDeleteCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> InvitationDeleteCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Roster`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> InvitationDeleteCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Creates an invitation. Only one invitation for a user and course may exist at a time. Delete and re-create an invitation to make changes. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to create invitations for this course or for access errors. * `NOT_FOUND` if the course or the user does not exist. * `FAILED_PRECONDITION` if the requested user's account is disabled or if the user already has this role or a role with greater permissions. * `ALREADY_EXISTS` if an invitation for the specified user and course already exists. +/// +/// A builder for the *create* method supported by a *invitation* resource. +/// It is not used directly, but through a `InvitationMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_classroom1 as classroom1; +/// use classroom1::Invitation; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use classroom1::Classroom; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Classroom::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req = Invitation::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.invitations().create(req) +/// .doit(); +/// # } +/// ``` +pub struct InvitationCreateCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Classroom, + _request: Invitation, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for InvitationCreateCall<'a, C, A> {} + +impl<'a, C, A> InvitationCreateCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Invitation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "classroom.invitations.create", + 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 Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://classroom.googleapis.com/v1/invitations".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Roster.as_ref().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: Invitation) -> InvitationCreateCall<'a, C, A> { + self._request = new_value; + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> InvitationCreateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> InvitationCreateCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Roster`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> InvitationCreateCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Returns a list of invitations that the requesting user is permitted to view, restricted to those that match the list request. *Note:* At least one of `user_id` or `course_id` must be supplied. Both fields can be supplied. This method returns the following error codes: * `PERMISSION_DENIED` for access errors. +/// +/// A builder for the *list* method supported by a *invitation* resource. +/// It is not used directly, but through a `InvitationMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_classroom1 as classroom1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use classroom1::Classroom; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Classroom::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.invitations().list() +/// .user_id("eirmod") +/// .page_token("dolore") +/// .page_size(-37) +/// .course_id("aliquyam") +/// .doit(); +/// # } +/// ``` +pub struct InvitationListCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Classroom, + _user_id: Option, + _page_token: Option, + _page_size: Option, + _course_id: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for InvitationListCall<'a, C, A> {} + +impl<'a, C, A> InvitationListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ListInvitationsResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "classroom.invitations.list", + 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._user_id { + params.push(("userId", 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._course_id { + params.push(("courseId", value.to_string())); + } + for &field in ["alt", "userId", "pageToken", "pageSize", "courseId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://classroom.googleapis.com/v1/invitations".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::RosterReadonly.as_ref().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Restricts returned invitations to those for a specific user. The identifier can be one of the following: * the numeric identifier for the user * the email address of the user * the string literal `"me"`, indicating the requesting user + /// + /// Sets the *user id* query property to the given value. + pub fn user_id(mut self, new_value: &str) -> InvitationListCall<'a, C, A> { + self._user_id = Some(new_value.to_string()); + self + } + /// nextPageToken value returned from a previous list call, indicating that the subsequent page of results should be returned. The list request must be otherwise identical to the one that resulted in this token. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> InvitationListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Maximum number of items to return. Zero means no maximum. The server may return fewer than the specified number of results. + /// + /// Sets the *page size* query property to the given value. + pub fn page_size(mut self, new_value: i32) -> InvitationListCall<'a, C, A> { + self._page_size = Some(new_value); + self + } + /// Restricts returned invitations to those for a course with the specified identifier. + /// + /// Sets the *course id* query property to the given value. + pub fn course_id(mut self, new_value: &str) -> InvitationListCall<'a, C, A> { + self._course_id = Some(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> InvitationListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> InvitationListCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::RosterReadonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> InvitationListCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Returns an invitation. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to view the requested invitation or for access errors. * `NOT_FOUND` if no invitation exists with the requested ID. +/// +/// A builder for the *get* method supported by a *invitation* resource. +/// It is not used directly, but through a `InvitationMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_classroom1 as classroom1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use classroom1::Classroom; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Classroom::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.invitations().get("id") +/// .doit(); +/// # } +/// ``` +pub struct InvitationGetCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Classroom, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for InvitationGetCall<'a, C, A> {} + +impl<'a, C, A> InvitationGetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Invitation)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "classroom.invitations.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 Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://classroom.googleapis.com/v1/invitations/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::RosterReadonly.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Identifier of the invitation to return. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> InvitationGetCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> InvitationGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> InvitationGetCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::RosterReadonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> InvitationGetCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Accepts an invitation, removing it and adding the invited user to the teachers or students (as appropriate) of the specified course. Only the invited user may accept an invitation. This method returns the following error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to accept the requested invitation or for access errors. * `FAILED_PRECONDITION` for the following request errors: * CourseMemberLimitReached * CourseNotModifiable * CourseTeacherLimitReached * UserGroupsMembershipLimitReached * `NOT_FOUND` if no invitation exists with the requested ID. +/// +/// A builder for the *accept* method supported by a *invitation* resource. +/// It is not used directly, but through a `InvitationMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_classroom1 as classroom1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use classroom1::Classroom; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Classroom::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.invitations().accept("id") +/// .doit(); +/// # } +/// ``` +pub struct InvitationAcceptCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Classroom, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for InvitationAcceptCall<'a, C, A> {} + +impl<'a, C, A> InvitationAcceptCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Empty)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "classroom.invitations.accept", + http_method: hyper::method::Method::Post }); + 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 Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://classroom.googleapis.com/v1/invitations/{id}:accept".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Roster.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Identifier of the invitation to accept. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> InvitationAcceptCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> InvitationAcceptCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> InvitationAcceptCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Roster`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> InvitationAcceptCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + diff --git a/gen/cloudbilling1-cli/Cargo.toml b/gen/cloudbilling1-cli/Cargo.toml new file mode 100644 index 0000000000..2097c3b4db --- /dev/null +++ b/gen/cloudbilling1-cli/Cargo.toml @@ -0,0 +1,35 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-cloudbilling1-cli" +version = "0.3.2+20150903" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with cloudbilling (protocol v1)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/cloudbilling1-cli" +homepage = "https://cloud.google.com/billing/" +documentation = "http://byron.github.io/google-apis-rs/google_cloudbilling1_cli" +license = "MIT" +keywords = ["cloudbilling", "google", "cli"] + +[[bin]] +name = "cloudbilling1" + +[dependencies] +hyper = ">= 0.6.8" +mime = "0.1.0" +serde = ">= 0.6.0" +serde_json = ">= 0.6.0" +yup-oauth2 = "*" +strsim = "*" +yup-hyper-mock = ">=1.0.0" +clap = ">= 1.0.3" + +[build-dependencies] +syntex = { version = "*" } +serde_codegen = { version = "*" } + + +[dependencies.google-cloudbilling1] +path = "../cloudbilling1" diff --git a/gen/cloudbilling1-cli/LICENSE.md b/gen/cloudbilling1-cli/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/cloudbilling1-cli/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/cloudbilling1-cli/README.md b/gen/cloudbilling1-cli/README.md new file mode 100644 index 0000000000..96a0c71dc9 --- /dev/null +++ b/gen/cloudbilling1-cli/README.md @@ -0,0 +1,118 @@ + +The `cloudbilling1` command-line interface *(CLI)* allows to use most features of the *Google cloudbilling* service from the comfort of your terminal. + +By default all output is printed to standard out, but flags can be set to direct it into a file independent of your shell's +capabilities. Errors will be printed to standard error, and cause the program's exit code to be non-zero. + +If data-structures are requested, these will be returned as pretty-printed JSON, to be useful as input to other tools. + +Everything else about the *cloudbilling* API can be found at the +[official documentation site](https://cloud.google.com/billing/). + +# Downloads + +You can download the pre-compiled 64bit binaries for the following platforms: + +* ![icon](http://megaicons.net/static/img/icons_sizes/6/140/16/ubuntu-icon.png) [ubuntu](http://dl.byronimo.de/google.rs/cli/0.3.2/ubuntu/cloudbilling1.tar.gz) +* ![icon](http://hydra-media.cursecdn.com/wow.gamepedia.com/a/a2/Apple-icon-16x16.png?version=25ddd67ac3dd3b634478e3978b76cb74) [osx](http://dl.byronimo.de/google.rs/cli/0.3.2/osx/cloudbilling1.tar.gz) + +Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/cloudbilling1-cli). + +# Usage + +This documentation was generated from the *cloudbilling* API at revision *20150903*. The CLI is at version *0.3.2*. + +```bash +cloudbilling1 [options] + billing-accounts + get [-p ]... [-o ] + list [-p ]... [-o ] + projects-list [-p ]... [-o ] + projects + get-billing-info [-p ]... [-o ] + update-billing-info (-r )... [-p ]... [-o ] + cloudbilling1 --help + +Configuration: + [--scope ]... + Specify the authentication a method should be executed in. Each scope + requires the user to grant this application permission to use it. + If unset, it defaults to the shortest scope url for a particular method. + --config-dir + A directory into which we will store our persistent data. Defaults to + a user-writable directory that we will create during the first invocation. + [default: ~/.google-service-cli] + --debug + Output all server communication to standard error. `tx` and `rx` are placed + into the same stream. + --debug-auth + Output all communication related to authentication to standard error. `tx` + and `rx` are placed into the same stream. + +``` + +# Configuration + +The program will store all persistent data in the `~/.google-service-cli` directory in *JSON* files prefixed with `cloudbilling1-`. You can change the directory used to store configuration with the `--config-dir` flag on a per-invocation basis. + +More information about the various kinds of persistent data are given in the following paragraphs. + +# Authentication + +Most APIs require a user to authenticate any request. If this is the case, the [scope][scopes] determines the +set of permissions granted. The granularity of these is usually no more than *read-only* or *full-access*. + +If not set, the system will automatically select the smallest feasible scope, e.g. when invoking a +method that is read-only, it will ask only for a read-only scope. +You may use the `--scope` flag to specify a scope directly. +All applicable scopes are documented in the respective method's CLI documentation. + +The first time a scope is used, the user is asked for permission. Follow the instructions given +by the CLI to grant permissions, or to decline. + +If a scope was authenticated by the user, the respective information will be stored as *JSON* in the configuration +directory, e.g. `~/.google-service-cli/cloudbilling1-token-.json`. No manual management of these tokens +is necessary. + +To revoke granted authentication, please refer to the [official documentation][revoke-access]. + +# Application Secrets + +In order to allow any application to use Google services, it will need to be registered using the +[Google Developer Console][google-dev-console]. APIs the application may use are then enabled for it +one by one. Most APIs can be used for free and have a daily quota. + +To allow more comfortable usage of the CLI without forcing anyone to register an own application, the CLI +comes with a default application secret that is configured accordingly. This also means that heavy usage +all around the world may deplete the daily quota. + +You can workaround this limitation by putting your own secrets file at this location: +`~/.google-service-cli/cloudbilling1-secret.json`, assuming that the required *cloudbilling* API +was enabled for it. Such a secret file can be downloaded in the *Google Developer Console* at +*APIs & auth -> Credentials -> Download JSON* and used as is. + +Learn more about how to setup Google projects and enable APIs using the [official documentation][google-project-new]. + + +# Debugging + +Even though the CLI does its best to provide usable error messages, sometimes it might be desirable to know +what exactly led to a particular issue. This is done by allowing all client-server communication to be +output to standard error *as-is*. + +The `--debug` flag will print all client-server communication to standard error, whereas the `--debug-auth` flag +will cause all communication related to authentication to standard error. +If the `--debug` flag is set, error-results will be debug-printed, possibly yielding more information about the +issue at hand. + +You may consider redirecting standard error into a file for ease of use, e.g. `cloudbilling1 --debug [options] 2>debug.txt`. + + +[scopes]: https://developers.google.com/+/api/oauth#scopes +[revoke-access]: http://webapps.stackexchange.com/a/30849 +[google-dev-console]: https://console.developers.google.com/ +[google-project-new]: https://developers.google.com/console/help/new/ \ No newline at end of file diff --git a/gen/cloudbilling1-cli/mkdocs.yml b/gen/cloudbilling1-cli/mkdocs.yml new file mode 100644 index 0000000000..0dd4bce2d5 --- /dev/null +++ b/gen/cloudbilling1-cli/mkdocs.yml @@ -0,0 +1,21 @@ +site_name: cloudbilling v0.3.2+20150903 +site_url: http://byron.github.io/google-apis-rs/google-cloudbilling1-cli +site_description: Write integrating applications with bcore + +repo_url: https://github.com/Byron/google-apis-rs/tree/master/gen/cloudbilling1-cli + +docs_dir: docs +site_dir: build_html + +pages: +- ['index.md', 'Home'] +- ['billing-accounts_get.md', 'Billing Accounts', 'Get'] +- ['billing-accounts_list.md', 'Billing Accounts', 'List'] +- ['billing-accounts_projects-list.md', 'Billing Accounts', 'Projects List'] +- ['projects_get-billing-info.md', 'Projects', 'Get Billing Info'] +- ['projects_update-billing-info.md', 'Projects', 'Update Billing Info'] + +theme: readthedocs + +copyright: Copyright © 2015, `Sebastian Thiel` + diff --git a/gen/cloudbilling1-cli/src/cmn.rs b/gen/cloudbilling1-cli/src/cmn.rs new file mode 100644 index 0000000000..8358f156fa --- /dev/null +++ b/gen/cloudbilling1-cli/src/cmn.rs @@ -0,0 +1,721 @@ +// COPY OF 'src/rust/cli/cmn.rs' +// DO NOT EDIT +use oauth2::{ApplicationSecret, ConsoleApplicationSecret, TokenStorage, Token}; +use serde_json as json; +use serde_json::value::Value; +use mime::Mime; +use clap::{App, SubCommand}; +use strsim; + +use std::fs; +use std::env; +use std::io; +use std::fmt; +use std::path::{Path, PathBuf}; +use std::str::FromStr; +use std::string::ToString; +use std::io::{Write, Read, stdout}; + +use std::default::Default; + +const FIELD_SEP: char = '.'; + + +pub enum ComplexType { + Pod, + Vec, + Map, +} + + // Null, + // Bool(bool), + // I64(i64), + // U64(u64), + // F64(f64), + // String(String), + +pub enum JsonType { + Boolean, + Int, + Uint, + Float, + String, +} + +pub struct JsonTypeInfo { + pub jtype: JsonType, + pub ctype: ComplexType, +} + +// Based on @erickt user comment. Thanks for the idea ! +// Remove all keys whose values are null from given value (changed in place) +pub fn remove_json_null_values(value: &mut Value) { + match *value { + Value::Object(ref mut map) => { + let mut for_removal = Vec::new(); + + for (key, mut value) in map.iter_mut() { + if value.is_null() { + for_removal.push(key.clone()); + } else { + remove_json_null_values(&mut value); + } + } + + for key in &for_removal { + map.remove(key); + } + } + _ => {} + } +} + +fn did_you_mean<'a>(v: &str, possible_values: &[&'a str]) -> Option<&'a str> { + + let mut candidate: Option<(f64, &str)> = None; + for pv in possible_values { + let confidence = strsim::jaro_winkler(v, pv); + if confidence > 0.8 && (candidate.is_none() || (candidate.as_ref().unwrap().0 < confidence)) { + candidate = Some((confidence, pv)); + } + } + match candidate { + None => None, + Some((_, candidate)) => Some(candidate), + } +} + +pub enum CallType { + Upload(UploadProtocol), + Standard, +} + +arg_enum!{ + pub enum UploadProtocol { + Simple, + Resumable + } +} + +impl AsRef for UploadProtocol { + fn as_ref(&self) -> &str { + match *self { + UploadProtocol::Simple => "simple", + UploadProtocol::Resumable => "resumable" + } + } +} + +impl AsRef for CallType { + fn as_ref(&self) -> &str { + match *self { + CallType::Upload(ref proto) => proto.as_ref(), + CallType::Standard => "standard-request" + } + } +} + +#[derive(Clone, Default)] +pub struct FieldCursor(Vec); + +impl ToString for FieldCursor { + fn to_string(&self) -> String { + self.0.join(".") + } +} + +impl From<&'static str> for FieldCursor { + fn from(value: &'static str) -> FieldCursor { + let mut res = FieldCursor::default(); + res.set(value).unwrap(); + res + } +} + +impl FieldCursor { + pub fn set(&mut self, value: &str) -> Result<(), CLIError> { + if value.len() == 0 { + return Err(CLIError::Field(FieldError::Empty)) + } + + let mut first_is_field_sep = false; + let mut char_count: usize = 0; + let mut last_c = FIELD_SEP; + let mut num_conscutive_field_seps = 0; + + let mut field = String::new(); + let mut fields = self.0.clone(); + + let push_field = |fs: &mut Vec, f: &mut String| { + if f.len() > 0 { + fs.push(f.clone()); + f.truncate(0); + } + }; + + for (cid, c) in value.chars().enumerate() { + char_count += 1; + + if c == FIELD_SEP { + if cid == 0 { + first_is_field_sep = true; + } + num_conscutive_field_seps += 1; + if cid > 0 && last_c == FIELD_SEP { + if fields.pop().is_none() { + return Err(CLIError::Field(FieldError::PopOnEmpty(value.to_string()))) + } + } else { + push_field(&mut fields, &mut field); + } + } else { + num_conscutive_field_seps = 0; + if cid == 1 { + if first_is_field_sep { + fields.truncate(0); + } + } + field.push(c); + } + + last_c = c; + } + + push_field(&mut fields, &mut field); + + if char_count == 1 && first_is_field_sep { + fields.truncate(0); + } + if char_count > 1 && num_conscutive_field_seps == 1 { + return Err(CLIError::Field(FieldError::TrailingFieldSep(value.to_string()))) + } + + self.0 = fields; + Ok(()) + } + + pub fn did_you_mean(value: &str, possible_values: &[&str]) -> Option { + if value.len() == 0 { + return None + } + + let mut last_c = FIELD_SEP; + + let mut field = String::new(); + let mut output = String::new(); + + let push_field = |fs: &mut String, f: &mut String| { + if f.len() > 0 { + fs.push_str( + match did_you_mean(&f, possible_values) { + Some(candidate) => candidate, + None => &f, + }); + f.truncate(0); + } + }; + + for (cid, c) in value.chars().enumerate() { + if c == FIELD_SEP { + if last_c != FIELD_SEP { + push_field(&mut output, &mut field); + } + output.push(c); + } else { + field.push(c); + } + + last_c = c; + } + + push_field(&mut output, &mut field); + + if &output == value { + None + } else { + Some(output) + } + } + + pub fn set_json_value(&self, mut object: &mut Value, + value: &str, type_info: JsonTypeInfo, + err: &mut InvalidOptionsError, + orig_cursor: &FieldCursor) { + assert!(self.0.len() > 0); + + for field in &self.0[..self.0.len()-1] { + let tmp = object; + object = + match *tmp { + Value::Object(ref mut mapping) => { + mapping.entry(field.to_owned()).or_insert( + Value::Object(Default::default()) + ) + }, + _ => panic!("We don't expect non-object Values here ...") + }; + } + + match *object { + Value::Object(ref mut mapping) => { + let field = &self.0[self.0.len()-1]; + let to_jval = + |value: &str, jtype: JsonType, err: &mut InvalidOptionsError| + -> Value { + match jtype { + JsonType::Boolean => + Value::Bool(arg_from_str(value, err, &field, "boolean")), + JsonType::Int => + Value::I64(arg_from_str(value, err, &field, "int")), + JsonType::Uint => + Value::U64(arg_from_str(value, err, &field, "uint")), + JsonType::Float => + Value::F64(arg_from_str(value, err, &field, "float")), + JsonType::String => + Value::String(value.to_owned()), + } + }; + + match type_info.ctype { + ComplexType::Pod => { + if mapping.insert(field.to_owned(), to_jval(value, type_info.jtype, err)).is_some() { + err.issues.push(CLIError::Field(FieldError::Duplicate(orig_cursor.to_string()))); + } + }, + ComplexType::Vec => { + match *mapping.entry(field.to_owned()) + .or_insert(Value::Array(Default::default())) { + Value::Array(ref mut values) => values.push(to_jval(value, type_info.jtype, err)), + _ => unreachable!() + } + }, + ComplexType::Map => { + let (key, value) = parse_kv_arg(value, err, true); + let jval = to_jval(value.unwrap_or(""), type_info.jtype, err); + + match *mapping.entry(field.to_owned()) + .or_insert(Value::Object(Default::default())) { + Value::Object(ref mut value_map) => { + if value_map.insert(key.to_owned(), jval).is_some() { + err.issues.push(CLIError::Field(FieldError::Duplicate(orig_cursor.to_string()))); + } + } + _ => unreachable!() + } + } + } + }, + _ => unreachable!() + } + } + + pub fn num_fields(&self) -> usize { + self.0.len() + } +} + +pub fn parse_kv_arg<'a>(kv: &'a str, err: &mut InvalidOptionsError, for_hashmap: bool) + -> (&'a str, Option<&'a str>) { + let mut add_err = || err.issues.push(CLIError::InvalidKeyValueSyntax(kv.to_string(),for_hashmap)); + match kv.find('=') { + None => { + add_err(); + return (kv, None) + }, + Some(pos) => { + let key = &kv[..pos]; + if kv.len() <= pos + 1 { + add_err(); + return (key, Some("")) + } + (key, Some(&kv[pos+1..])) + } + } +} + +pub fn calltype_from_str(name: &str, valid_protocols: Vec, err: &mut InvalidOptionsError) -> CallType { + CallType::Upload( + match UploadProtocol::from_str(name) { + Ok(up) => up, + Err(msg) => { + err.issues.push(CLIError::InvalidUploadProtocol(name.to_string(), valid_protocols)); + UploadProtocol::Simple + } + }) +} + +pub fn input_file_from_opts(file_path: &str, err: &mut InvalidOptionsError) -> Option { + match fs::File::open(file_path) { + Ok(f) => Some(f), + Err(io_err) => { + err.issues.push(CLIError::Input(InputError::IOError((file_path.to_string(), io_err)))); + None + } + } +} + +pub fn input_mime_from_opts(mime: &str, err: &mut InvalidOptionsError) -> Option { + match mime.parse() { + Ok(m) => Some(m), + Err(_) => { + err.issues.push(CLIError::Input(InputError::Mime(mime.to_string()))); + None + } + } +} + +pub fn writer_from_opts(arg: Option<&str>) -> Result, io::Error> { + let f = arg.unwrap_or("-"); + match f { + "-" => Ok(Box::new(stdout())), + _ => match fs::OpenOptions::new().create(true).write(true).open(f) { + Ok(f) => Ok(Box::new(f)), + Err(io_err) => Err(io_err), + } + } +} + + +pub fn arg_from_str<'a, T>(arg: &str, err: &mut InvalidOptionsError, + arg_name: &'a str, + arg_type: &'a str) -> T + where T: FromStr + Default, + ::Err: fmt::Display { + match FromStr::from_str(arg) { + Err(perr) => { + err.issues.push( + CLIError::ParseError(arg_name.to_owned(), arg_type.to_owned(), arg.to_string(), format!("{}", perr)) + ); + Default::default() + }, + Ok(v) => v, + } +} + +pub struct JsonTokenStorage { + pub program_name: &'static str, + pub db_dir: String, +} + +impl JsonTokenStorage { + fn path(&self, scope_hash: u64) -> PathBuf { + Path::new(&self.db_dir).join(&format!("{}-token-{}.json", self.program_name, scope_hash)) + } +} + +impl TokenStorage for JsonTokenStorage { + type Error = json::Error; + + // NOTE: logging might be interesting, currently we swallow all errors + fn set(&mut self, scope_hash: u64, _: &Vec<&str>, token: Option) -> Result<(), json::Error> { + match token { + None => { + match fs::remove_file(self.path(scope_hash)) { + Err(err) => + match err.kind() { + io::ErrorKind::NotFound => Ok(()), + _ => Err(json::Error::IoError(err)) + }, + Ok(_) => Ok(()), + } + } + Some(token) => { + match fs::OpenOptions::new().create(true).write(true).open(&self.path(scope_hash)) { + Ok(mut f) => { + match json::to_writer_pretty(&mut f, &token) { + Ok(_) => Ok(()), + Err(serde_err) => Err(serde_err), + } + }, + Err(io_err) => Err(json::Error::IoError(io_err)) + } + } + } + } + + fn get(&self, scope_hash: u64, _: &Vec<&str>) -> Result, json::Error> { + match fs::File::open(&self.path(scope_hash)) { + Ok(mut f) => { + match json::de::from_reader(f) { + Ok(token) => Ok(Some(token)), + Err(err) => Err(err), + } + }, + Err(io_err) => { + match io_err.kind() { + io::ErrorKind::NotFound => Ok(None), + _ => Err(json::Error::IoError(io_err)) + } + } + } + } +} + + +#[derive(Debug)] +pub enum ApplicationSecretError { + DecoderError((String, json::Error)), + FormatError(String), +} + +impl fmt::Display for ApplicationSecretError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + ApplicationSecretError::DecoderError((ref path, ref err)) + => writeln!(f, "Could not decode file at '{}' with error: {}.", + path, err), + ApplicationSecretError::FormatError(ref path) + => writeln!(f, "'installed' field is unset in secret file at '{}'.", + path), + } + } +} + +#[derive(Debug)] +pub enum ConfigurationError { + DirectoryCreationFailed((String, io::Error)), + DirectoryUnset, + HomeExpansionFailed(String), + Secret(ApplicationSecretError), + IOError((String, io::Error)), +} + +impl fmt::Display for ConfigurationError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + ConfigurationError::DirectoryCreationFailed((ref dir, ref err)) + => writeln!(f, "Directory '{}' could not be created with error: {}.", dir, err), + ConfigurationError::DirectoryUnset + => writeln!(f, "--config-dir was unset or empty."), + ConfigurationError::HomeExpansionFailed(ref dir) + => writeln!(f, "Couldn't find HOME directory of current user, failed to expand '{}'.", dir), + ConfigurationError::Secret(ref err) + => writeln!(f, "Secret -> {}", err), + ConfigurationError::IOError((ref path, ref err)) + => writeln!(f, "IO operation failed on path '{}' with error: {}.", path, err), + } + } +} + +#[derive(Debug)] +pub enum InputError { + IOError((String, io::Error)), + Mime(String), +} + +impl fmt::Display for InputError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + InputError::IOError((ref file_path, ref io_err)) + => writeln!(f, "Failed to open '{}' for reading with error: {}.", file_path, io_err), + InputError::Mime(ref mime) + => writeln!(f, "'{}' is not a known mime-type.", mime), + } + } +} + +#[derive(Debug)] +pub enum FieldError { + PopOnEmpty(String), + TrailingFieldSep(String), + Unknown(String, Option, Option), + Duplicate(String), + Empty, +} + + +impl fmt::Display for FieldError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + FieldError::PopOnEmpty(ref field) + => writeln!(f, "'{}': Cannot move up on empty field cursor.", field), + FieldError::TrailingFieldSep(ref field) + => writeln!(f, "'{}': Single field separator may not be last character.", field), + FieldError::Unknown(ref field, ref suggestion, ref value) => { + let suffix = + match *suggestion { + Some(ref s) => { + let kv = + match *value { + Some(ref v) => format!("{}={}", s, v), + None => s.clone(), + }; + format!(" Did you mean '{}' ?", kv) + }, + None => String::new(), + }; + writeln!(f, "Field '{}' does not exist.{}", field, suffix) + }, + FieldError::Duplicate(ref cursor) + => writeln!(f, "Value at '{}' was already set", cursor), + FieldError::Empty + => writeln!(f, "Field names must not be empty."), + } + } +} + + +#[derive(Debug)] +pub enum CLIError { + Configuration(ConfigurationError), + ParseError(String, String, String, String), + UnknownParameter(String, Vec<&'static str>), + InvalidUploadProtocol(String, Vec), + InvalidKeyValueSyntax(String, bool), + Input(InputError), + Field(FieldError), + MissingCommandError, + MissingMethodError(String), +} + +impl fmt::Display for CLIError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + CLIError::Configuration(ref err) => write!(f, "Configuration -> {}", err), + CLIError::Input(ref err) => write!(f, "Input -> {}", err), + CLIError::Field(ref err) => write!(f, "Field -> {}", err), + CLIError::InvalidUploadProtocol(ref proto_name, ref valid_names) + => writeln!(f, "'{}' is not a valid upload protocol. Choose from one of {}.", proto_name, valid_names.join(", ")), + CLIError::ParseError(ref arg_name, ref type_name, ref value, ref err_desc) + => writeln!(f, "Failed to parse argument '{}' with value '{}' as {} with error: {}.", + arg_name, value, type_name, err_desc), + CLIError::UnknownParameter(ref param_name, ref possible_values) => { + let mut suffix = + match did_you_mean(param_name, &possible_values) { + Some(v) => format!(" Did you mean '{}' ?", v), + None => String::new(), + }; + write!(f, "Parameter '{}' is unknown.{}\n", param_name, suffix) + }, + CLIError::InvalidKeyValueSyntax(ref kv, is_hashmap) => { + let hashmap_info = if is_hashmap { "hashmap " } else { "" }; + writeln!(f, "'{}' does not match {}pattern =.", kv, hashmap_info) + }, + CLIError::MissingCommandError => writeln!(f, "Please specify the main sub-command."), + CLIError::MissingMethodError(ref cmd) => writeln!(f, "Please specify the method to call on the '{}' command.", cmd), + } + } +} + +#[derive(Debug)] +pub struct InvalidOptionsError { + pub issues: Vec, + pub exit_code: i32, +} + +impl fmt::Display for InvalidOptionsError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + for issue in &self.issues { + try!(issue.fmt(f)); + } + Ok(()) + } +} + +impl InvalidOptionsError { + pub fn single(err: CLIError, exit_code: i32) -> InvalidOptionsError { + InvalidOptionsError { + issues: vec![err], + exit_code: exit_code, + } + } + + pub fn new() -> InvalidOptionsError { + InvalidOptionsError { + issues: Vec::new(), + exit_code: 1, + } + } +} + +pub fn assure_config_dir_exists(dir: &str) -> Result { + let trdir = dir.trim(); + if trdir.len() == 0 { + return Err(CLIError::Configuration(ConfigurationError::DirectoryUnset)) + } + + let expanded_config_dir = + if trdir.as_bytes()[0] == b'~' { + match env::var("HOME").ok().or(env::var("UserProfile").ok()) { + None => return Err(CLIError::Configuration(ConfigurationError::HomeExpansionFailed(trdir.to_string()))), + Some(mut user) => { + user.push_str(&trdir[1..]); + user + } + } + } else { + trdir.to_string() + }; + + if let Err(err) = fs::create_dir(&expanded_config_dir) { + if err.kind() != io::ErrorKind::AlreadyExists { + return Err(CLIError::Configuration( + ConfigurationError::DirectoryCreationFailed((expanded_config_dir, err)))) + } + } + + Ok(expanded_config_dir) +} + +pub fn application_secret_from_directory(dir: &str, + secret_basename: &str, + json_console_secret: &str) + -> Result { + let secret_path = Path::new(dir).join(secret_basename); + let secret_str = || secret_path.as_path().to_str().unwrap().to_string(); + let secret_io_error = |io_err: io::Error| { + Err(CLIError::Configuration(ConfigurationError::IOError( + (secret_str(), io_err) + ))) + }; + + for _ in 0..2 { + match fs::File::open(&secret_path) { + Err(mut err) => { + if err.kind() == io::ErrorKind::NotFound { + // Write our built-in one - user may adjust the written file at will + + err = match fs::OpenOptions::new().create(true).write(true).open(&secret_path) { + Err(cfe) => cfe, + Ok(mut f) => { + // Assure we convert 'ugly' json string into pretty one + let console_secret: ConsoleApplicationSecret + = json::from_str(json_console_secret).unwrap(); + match json::to_writer_pretty(&mut f, &console_secret) { + Err(serde_err) => match serde_err { + json::Error::IoError(err) => err, + _ => panic!("Unexpected serde error: {:#?}", serde_err) + }, + Ok(_) => continue, + } + } + }; + // fall through to IO error handling + } + return secret_io_error(err) + }, + Ok(mut f) => { + match json::de::from_reader::<_, ConsoleApplicationSecret>(f) { + Err(json::Error::IoError(err)) => + return secret_io_error(err), + Err(json_err) => + return Err(CLIError::Configuration( + ConfigurationError::Secret( + ApplicationSecretError::DecoderError( + (secret_str(), json_err) + )))), + Ok(console_secret) => + match console_secret.installed { + Some(secret) => return Ok(secret), + None => return Err( + CLIError::Configuration( + ConfigurationError::Secret( + ApplicationSecretError::FormatError(secret_str()) + ))) + }, + } + } + } + } + unreachable!(); +} diff --git a/gen/cloudbilling1-cli/src/main.rs b/gen/cloudbilling1-cli/src/main.rs new file mode 100644 index 0000000000..f748ea7057 --- /dev/null +++ b/gen/cloudbilling1-cli/src/main.rs @@ -0,0 +1,693 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/cli/main.rs.mako' +// DO NOT EDIT ! +#![allow(unused_variables, unused_imports, dead_code, unused_mut)] + +#[macro_use] +extern crate clap; +extern crate yup_oauth2 as oauth2; +extern crate yup_hyper_mock as mock; +extern crate serde; +extern crate serde_json; +extern crate hyper; +extern crate mime; +extern crate strsim; +extern crate google_cloudbilling1 as api; + +use std::env; +use std::io::{self, Write}; +use clap::{App, SubCommand, Arg}; + +mod cmn; + +use cmn::{InvalidOptionsError, CLIError, JsonTokenStorage, arg_from_str, writer_from_opts, parse_kv_arg, + input_file_from_opts, input_mime_from_opts, FieldCursor, FieldError, CallType, UploadProtocol, + calltype_from_str, remove_json_null_values, ComplexType, JsonType, JsonTypeInfo}; + +use std::default::Default; +use std::str::FromStr; + +use oauth2::{Authenticator, DefaultAuthenticatorDelegate}; +use serde_json as json; +use clap::ArgMatches; + +enum DoitError { + IoError(String, io::Error), + ApiError(api::Error), +} + +struct Engine<'n, 'a> { + opt: ArgMatches<'n, 'a>, + hub: api::Cloudbilling>, + gp: Vec<&'static str>, + gpm: Vec<(&'static str, &'static str)>, +} + + +impl<'n, 'a> Engine<'n, 'a> { + fn _billing_accounts_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.billing_accounts().get(opt.value_of("name").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _billing_accounts_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.billing_accounts().list(); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "page-size" => { + call = call.page_size(arg_from_str(value.unwrap_or("-0"), err, "page-size", "integer")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["page-token", "page-size"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _billing_accounts_projects_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.billing_accounts().projects_list(opt.value_of("name").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "page-size" => { + call = call.page_size(arg_from_str(value.unwrap_or("-0"), err, "page-size", "integer")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["page-token", "page-size"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _projects_get_billing_info(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.projects().get_billing_info(opt.value_of("name").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _projects_update_billing_info(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "project-id" => Some(("projectId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "billing-enabled" => Some(("billingEnabled", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "billing-account-name" => Some(("billingAccountName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["billing-account-name", "billing-enabled", "name", "project-id"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::ProjectBillingInfo = json::value::from_value(object).unwrap(); + let mut call = self.hub.projects().update_billing_info(request, opt.value_of("name").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _doit(&self, dry_run: bool) -> Result, Option> { + let mut err = InvalidOptionsError::new(); + let mut call_result: Result<(), DoitError> = Ok(()); + let mut err_opt: Option = None; + match self.opt.subcommand() { + ("billing-accounts", Some(opt)) => { + match opt.subcommand() { + ("get", Some(opt)) => { + call_result = self._billing_accounts_get(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._billing_accounts_list(opt, dry_run, &mut err); + }, + ("projects-list", Some(opt)) => { + call_result = self._billing_accounts_projects_list(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("billing-accounts".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("projects", Some(opt)) => { + match opt.subcommand() { + ("get-billing-info", Some(opt)) => { + call_result = self._projects_get_billing_info(opt, dry_run, &mut err); + }, + ("update-billing-info", Some(opt)) => { + call_result = self._projects_update_billing_info(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("projects".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + _ => { + err.issues.push(CLIError::MissingCommandError); + writeln!(io::stderr(), "{}\n", self.opt.usage()).ok(); + } + } + + if dry_run { + if err.issues.len() > 0 { + err_opt = Some(err); + } + Err(err_opt) + } else { + Ok(call_result) + } + } + + // Please note that this call will fail if any part of the opt can't be handled + fn new(opt: ArgMatches<'a, 'n>) -> Result, InvalidOptionsError> { + let (config_dir, secret) = { + let config_dir = match cmn::assure_config_dir_exists(opt.value_of("folder").unwrap_or("~/.google-service-cli")) { + Err(e) => return Err(InvalidOptionsError::single(e, 3)), + Ok(p) => p, + }; + + match cmn::application_secret_from_directory(&config_dir, "cloudbilling1-secret.json", + "{\"installed\":{\"auth_uri\":\"https://accounts.google.com/o/oauth2/auth\",\"client_secret\":\"hCsslbCUyfehWMmbkG8vTYxG\",\"token_uri\":\"https://accounts.google.com/o/oauth2/token\",\"client_email\":\"\",\"redirect_uris\":[\"urn:ietf:wg:oauth:2.0:oob\",\"oob\"],\"client_x509_cert_url\":\"\",\"client_id\":\"620010449518-9ngf7o4dhs0dka470npqvor6dc5lqb9b.apps.googleusercontent.com\",\"auth_provider_x509_cert_url\":\"https://www.googleapis.com/oauth2/v1/certs\"}}") { + Ok(secret) => (config_dir, secret), + Err(e) => return Err(InvalidOptionsError::single(e, 4)) + } + }; + + let auth = Authenticator::new( &secret, DefaultAuthenticatorDelegate, + if opt.is_present("debug-auth") { + hyper::Client::with_connector(mock::TeeConnector { + connector: hyper::net::HttpsConnector::::default() + }) + } else { + hyper::Client::new() + }, + JsonTokenStorage { + program_name: "cloudbilling1", + db_dir: config_dir.clone(), + }, None); + + let client = + if opt.is_present("debug") { + hyper::Client::with_connector(mock::TeeConnector { + connector: hyper::net::HttpsConnector::::default() + }) + } else { + hyper::Client::new() + }; + let engine = Engine { + opt: opt, + hub: api::Cloudbilling::new(client, auth), + gp: vec!["$-xgafv", "access-token", "alt", "bearer-token", "callback", "fields", "key", "oauth-token", "pp", "pretty-print", "quota-user", "upload-type", "upload-protocol"], + gpm: vec![ + ("$-xgafv", "$.xgafv"), + ("access-token", "access_token"), + ("bearer-token", "bearer_token"), + ("oauth-token", "oauth_token"), + ("pretty-print", "prettyPrint"), + ("quota-user", "quotaUser"), + ("upload-type", "uploadType"), + ("upload-protocol", "upload_protocol"), + ] + }; + + match engine._doit(true) { + Err(Some(err)) => Err(err), + Err(None) => Ok(engine), + Ok(_) => unreachable!(), + } + } + + fn doit(&self) -> Result<(), DoitError> { + match self._doit(false) { + Ok(res) => res, + Err(_) => unreachable!(), + } + } +} + +fn main() { + let mut exit_status = 0i32; + let arg_data = [ + ("billing-accounts", "methods: 'get', 'list' and 'projects-list'", vec![ + ("get", + Some(r##"Gets information about a billing account. The current authenticated user must be an [owner of the billing account](https://support.google.com/cloud/answer/4430947)."##), + "Details at http://byron.github.io/google-apis-rs/google_cloudbilling1_cli/billing-accounts_get", + vec![ + (Some(r##"name"##), + None, + Some(r##"The resource name of the billing account to retrieve. For example, `billingAccounts/012345-567890-ABCDEF`."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Lists the billing accounts that the current authenticated user [owns](https://support.google.com/cloud/answer/4430947)."##), + "Details at http://byron.github.io/google-apis-rs/google_cloudbilling1_cli/billing-accounts_list", + vec![ + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("projects-list", + Some(r##"Lists the projects associated with a billing account. The current authenticated user must be an [owner of the billing account](https://support.google.com/cloud/answer/4430947)."##), + "Details at http://byron.github.io/google-apis-rs/google_cloudbilling1_cli/billing-accounts_projects-list", + vec![ + (Some(r##"name"##), + None, + Some(r##"The resource name of the billing account associated with the projects that you want to list. For example, `billingAccounts/012345-567890-ABCDEF`."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("projects", "methods: 'get-billing-info' and 'update-billing-info'", vec![ + ("get-billing-info", + Some(r##"Gets the billing information for a project. The current authenticated user must have [permission to view the project](https://cloud.google.com/docs/permissions-overview#h.bgs0oxofvnoo )."##), + "Details at http://byron.github.io/google-apis-rs/google_cloudbilling1_cli/projects_get-billing-info", + vec![ + (Some(r##"name"##), + None, + Some(r##"The resource name of the project for which billing information is retrieved. For example, `projects/tokyo-rain-123`."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("update-billing-info", + Some(r##"Sets or updates the billing account associated with a project. You specify the new billing account by setting the `billing_account_name` in the `ProjectBillingInfo` resource to the resource name of a billing account. Associating a project with an open billing account enables billing on the project and allows charges for resource usage. If the project already had a billing account, this method changes the billing account used for resource usage charges. *Note:* Incurred charges that have not yet been reported in the transaction history of the Google Developers Console may be billed to the new billing account, even if the charge occurred before the new billing account was assigned to the project. The current authenticated user must have ownership privileges for both the [project](https://cloud.google.com/docs/permissions-overview#h.bgs0oxofvnoo ) and the [billing account](https://support.google.com/cloud/answer/4430947). You can disable billing on the project by setting the `billing_account_name` field to empty. This action disassociates the current billing account from the project. Any billable activity of your in-use services will stop, and your application could stop functioning as expected. Any unbilled charges to date will be billed to the previously associated account. The current authenticated user must be either an owner of the project or an owner of the billing account for the project. Note that associating a project with a *closed* billing account will have much the same effect as disabling billing on the project: any paid resources used by the project will be shut down. Thus, unless you wish to disable billing, you should always call this method with the name of an *open* billing account."##), + "Details at http://byron.github.io/google-apis-rs/google_cloudbilling1_cli/projects_update-billing-info", + vec![ + (Some(r##"name"##), + None, + Some(r##"The resource name of the project associated with the billing information that you want to update. For example, `projects/tokyo-rain-123`."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ]; + + let mut app = App::new("cloudbilling1") + .author("Sebastian Thiel ") + .version("0.3.2+20150903") + .about("Retrieves Google Developers Console billing accounts and associates them with projects.") + .after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_cloudbilling1_cli") + .arg(Arg::with_name("url") + .long("scope") + .help("Specify the authentication a method should be executed in. Each scope requires the user to grant this application permission to use it.If unset, it defaults to the shortest scope url for a particular method.") + .multiple(true) + .takes_value(true)) + .arg(Arg::with_name("folder") + .long("config-dir") + .help("A directory into which we will store our persistent data. Defaults to a user-writable directory that we will create during the first invocation.[default: ~/.google-service-cli") + .multiple(false) + .takes_value(true)) + .arg(Arg::with_name("debug") + .long("debug") + .help("Output all server communication to standard error. `tx` and `rx` are placed into the same stream.") + .multiple(false) + .takes_value(false)) + .arg(Arg::with_name("debug-auth") + .long("debug-auth") + .help("Output all communication related to authentication to standard error. `tx` and `rx` are placed into the same stream.") + .multiple(false) + .takes_value(false)); + + for &(main_command_name, ref about, ref subcommands) in arg_data.iter() { + let mut mcmd = SubCommand::with_name(main_command_name).about(about); + + for &(sub_command_name, ref desc, url_info, ref args) in subcommands { + let mut scmd = SubCommand::with_name(sub_command_name); + if let &Some(desc) = desc { + scmd = scmd.about(desc); + } + scmd = scmd.after_help(url_info); + + for &(ref arg_name, ref flag, ref desc, ref required, ref multi) in args { + let arg_name_str = + match (arg_name, flag) { + (&Some(an), _ ) => an, + (_ , &Some(f)) => f, + _ => unreachable!(), + }; + let mut arg = Arg::with_name(arg_name_str) + .empty_values(false); + if let &Some(short_flag) = flag { + arg = arg.short(short_flag); + } + if let &Some(desc) = desc { + arg = arg.help(desc); + } + if arg_name.is_some() && flag.is_some() { + arg = arg.takes_value(true); + } + if let &Some(required) = required { + arg = arg.required(required); + } + if let &Some(multi) = multi { + arg = arg.multiple(multi); + } + scmd = scmd.arg(arg); + } + mcmd = mcmd.subcommand(scmd); + } + app = app.subcommand(mcmd); + } + + let matches = app.get_matches(); + + let debug = matches.is_present("debug"); + match Engine::new(matches) { + Err(err) => { + exit_status = err.exit_code; + writeln!(io::stderr(), "{}", err).ok(); + }, + Ok(engine) => { + if let Err(doit_err) = engine.doit() { + exit_status = 1; + match doit_err { + DoitError::IoError(path, err) => { + writeln!(io::stderr(), "Failed to open output file '{}': {}", path, err).ok(); + }, + DoitError::ApiError(err) => { + if debug { + writeln!(io::stderr(), "{:#?}", err).ok(); + } else { + writeln!(io::stderr(), "{}", err).ok(); + } + } + } + } + } + } + + std::process::exit(exit_status); +} \ No newline at end of file diff --git a/gen/cloudbilling1/Cargo.toml b/gen/cloudbilling1/Cargo.toml new file mode 100644 index 0000000000..e51f98f187 --- /dev/null +++ b/gen/cloudbilling1/Cargo.toml @@ -0,0 +1,29 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-cloudbilling1" +version = "0.1.9+20150903" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with cloudbilling (protocol v1)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/cloudbilling1" +homepage = "https://cloud.google.com/billing/" +documentation = "http://byron.github.io/google-apis-rs/google_cloudbilling1" +license = "MIT" +keywords = ["cloudbilling", "google", "protocol", "web", "api"] +build = "src/build.rs" + + +[dependencies] +hyper = ">= 0.6.8" +mime = "0.1.0" +serde = ">= 0.6.0" +serde_json = ">= 0.6.0" +yup-oauth2 = "*" +url = "*" + +[build-dependencies] +syntex = { version = "*" } +serde_codegen = { version = "*" } + diff --git a/gen/cloudbilling1/LICENSE.md b/gen/cloudbilling1/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/cloudbilling1/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/cloudbilling1/README.md b/gen/cloudbilling1/README.md new file mode 100644 index 0000000000..be7202f11c --- /dev/null +++ b/gen/cloudbilling1/README.md @@ -0,0 +1,179 @@ + +The `google-cloudbilling1` library allows access to all features of the *Google cloudbilling* service. + +This documentation was generated from *cloudbilling* crate version *0.1.9+20150903*, where *20150903* is the exact revision of the *cloudbilling:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. + +Everything else about the *cloudbilling* *v1* API can be found at the +[official documentation site](https://cloud.google.com/billing/). +# Features + +Handle the following *Resources* with ease from the central [hub](http://byron.github.io/google-apis-rs/google_cloudbilling1/struct.Cloudbilling.html) ... + +* [billing accounts](http://byron.github.io/google-apis-rs/google_cloudbilling1/struct.BillingAccount.html) + * [*get*](http://byron.github.io/google-apis-rs/google_cloudbilling1/struct.BillingAccountGetCall.html), [*list*](http://byron.github.io/google-apis-rs/google_cloudbilling1/struct.BillingAccountListCall.html) and [*projects list*](http://byron.github.io/google-apis-rs/google_cloudbilling1/struct.BillingAccountProjectListCall.html) +* projects + * [*get billing info*](http://byron.github.io/google-apis-rs/google_cloudbilling1/struct.ProjectGetBillingInfoCall.html) and [*update billing info*](http://byron.github.io/google-apis-rs/google_cloudbilling1/struct.ProjectUpdateBillingInfoCall.html) + + + + +# Structure of this Library + +The API is structured into the following primary items: + +* **[Hub](http://byron.github.io/google-apis-rs/google_cloudbilling1/struct.Cloudbilling.html)** + * a central object to maintain state and allow accessing all *Activities* + * creates [*Method Builders*](http://byron.github.io/google-apis-rs/google_cloudbilling1/trait.MethodsBuilder.html) which in turn + allow access to individual [*Call Builders*](http://byron.github.io/google-apis-rs/google_cloudbilling1/trait.CallBuilder.html) +* **[Resources](http://byron.github.io/google-apis-rs/google_cloudbilling1/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_cloudbilling1/trait.Part.html)** + * a collection of properties + * never directly used in *Activities* +* **[Activities](http://byron.github.io/google-apis-rs/google_cloudbilling1/trait.CallBuilder.html)** + * operations to apply to *Resources* + +All *structures* are marked with applicable traits to further categorize them and ease browsing. + +Generally speaking, you can invoke *Activities* like this: + +```Rust,ignore +let r = hub.resource().activity(...).doit() +``` + +Or specifically ... + +```ignore +let r = hub.billing_accounts().get(...).doit() +let r = hub.billing_accounts().list(...).doit() +let r = hub.billing_accounts().projects_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-cloudbilling1 = "*" +``` + +## A complete example + +```Rust +extern crate hyper; +extern crate yup_oauth2 as oauth2; +extern crate google_cloudbilling1 as cloudbilling1; +use cloudbilling1::{Result, Error}; +use std::default::Default; +use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +use cloudbilling1::Cloudbilling; + +// 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 = Cloudbilling::new(hyper::Client::new(), auth); +// You can configure optional parameters by calling 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_accounts().projects_list("name") + .page_token("sit") + .page_size(-65) + .doit(); + +match result { + Err(e) => match e { + // The Error enum provides details about what exactly happened. + // You can also just use its `Debug`, `Display` or `Error` traits + Error::HttpError(_) + |Error::MissingAPIKey + |Error::MissingToken(_) + |Error::Cancelled + |Error::UploadSizeLimitExceeded(_, _) + |Error::Failure(_) + |Error::BadRequest(_) + |Error::FieldClash(_) + |Error::JsonDecodeError(_, _) => println!("{}", e), + }, + Ok(res) => println!("Success: {:?}", res), +} + +``` +## Handling Errors + +All errors produced by the system are provided either as [Result](http://byron.github.io/google-apis-rs/google_cloudbilling1/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_cloudbilling1/trait.Delegate.html), or the [Authenticator Delegate](http://byron.github.io/google-apis-rs/google_cloudbilling1/../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 Downloads +If a method supports downloads, the response body, which is part of the [Result](http://byron.github.io/google-apis-rs/google_cloudbilling1/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_cloudbilling1/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_cloudbilling1/trait.Delegate.html) to the +[Method Builder](http://byron.github.io/google-apis-rs/google_cloudbilling1/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_cloudbilling1/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_cloudbilling1/trait.RequestValue.html) and +[decodable](http://byron.github.io/google-apis-rs/google_cloudbilling1/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_cloudbilling1/trait.Part.html) which are identifiable 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_cloudbilling1/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_cloudbilling1/trait.RequestValue.html) are moved + +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 **cloudbilling1** 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/cloudbilling1/src/build.rs b/gen/cloudbilling1/src/build.rs new file mode 100644 index 0000000000..54927a0d94 --- /dev/null +++ b/gen/cloudbilling1/src/build.rs @@ -0,0 +1,16 @@ +extern crate syntex; +extern crate serde_codegen; + +use std::env; +use std::path::Path; + +pub fn main() { + let out_dir = env::var_os("OUT_DIR").unwrap(); + + let src = Path::new("src/lib.rs.in"); + let dst = Path::new(&out_dir).join("lib.rs"); + + let mut registry = syntex::Registry::new(); + serde_codegen::register(&mut registry); + registry.expand("google-cloudbilling1", &src, &dst).unwrap(); +} diff --git a/gen/cloudbilling1/src/cmn.rs b/gen/cloudbilling1/src/cmn.rs new file mode 100644 index 0000000000..0e31353ba3 --- /dev/null +++ b/gen/cloudbilling1/src/cmn.rs @@ -0,0 +1,762 @@ +// COPY OF 'src/rust/api/cmn.rs' +// DO NOT EDIT +use std::io::{self, Read, Seek, Cursor, Write, SeekFrom}; +use std; +use std::fmt::{self, Display}; +use std::str::FromStr; +use std::error; +use std::thread::sleep_ms; + +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::h1::LINE_ENDING; +use hyper::method::Method; +use hyper::status::StatusCode; + +use serde_json as json; + +/// 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 {} + +/// Identifies types for building methods of a particular resource type +pub trait MethodsBuilder {} + +/// Identifies types which represent builders for a particular resource method +pub trait CallBuilder {} + +/// Identifies types which can be inserted and deleted. +/// Types with this trait are most commonly used by clients of this API. +pub trait Resource {} + +/// Identifies types which are used in API responses. +pub trait ResponseResult {} + +/// Identifies types which are used in API requests. +pub trait RequestValue {} + +/// Identifies types which are not actually used by the API +/// This might be a bug within the google API schema. +pub trait UnusedType {} + +/// Identifies types which are only used as part of other types, which +/// usually are carrying the `Resource` trait. +pub trait Part {} + +/// 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 {} + +/// 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 +} + +/// A utility to represent detailed errors we might see in case there are BadRequests. +/// The latter happen if the sent parameters or request structures are unsound +#[derive(Deserialize, Serialize, Debug)] +pub struct ErrorResponse { + error: ServerError, +} + +#[derive(Deserialize, Serialize, Debug)] +pub struct ServerError { + errors: Vec, + code: u16, + message: String, +} + +#[derive(Deserialize, Serialize, Debug)] +pub struct ServerMessage { + domain: String, + reason: String, + message: String, + #[serde(rename="locationType")] + location_type: Option, + location: 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 successful. That way, the delegate 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. + /// + /// If you choose to retry after a duration, the duration should be chosen using the + /// [exponential backoff algorithm](http://en.wikipedia.org/wiki/Exponential_backoff). + /// + /// Return retry information. + fn http_error(&mut self, &hyper::Error) -> 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 it as a general information about the + /// impending failure. + /// The given Error provides information about why the token couldn't be acquired in the + /// first place + fn token(&mut self, err: &error::Error) -> Option { + let _ = err; + 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/canceled, 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()`. + /// It will also be called with None after a successful upload, which allows the delegate + /// to forget the URL. That way, we will not attempt to resume an upload that has already + /// finished. + fn store_upload_url(&mut self, url: Option<&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: &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. + /// + /// If you choose to retry after a duration, the duration should be chosen using the + /// [exponential backoff algorithm](http://en.wikipedia.org/wiki/Exponential_backoff). + fn http_failure(&mut self, _: &hyper::client::Response, Option, _: 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 {} + + +#[derive(Debug)] +pub enum Error { + /// The http connection failed + HttpError(hyper::Error), + + /// 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), + + /// Represents information about a request that was not understood by the server. + /// Details are included. + BadRequest(ErrorResponse), + + /// 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(Box), + + /// 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(String, json::Error), + + /// Indicates an HTTP repsonse with a non-success status code + Failure(hyper::client::Response), +} + + +impl Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + Error::HttpError(ref err) => err.fmt(f), + Error::UploadSizeLimitExceeded(ref resource_size, ref max_size) => + writeln!(f, "The media size {} exceeds the maximum allowed upload size of {}" + , resource_size, max_size), + Error::MissingAPIKey => { + (writeln!(f, "The application's API key was not found in the configuration")).ok(); + writeln!(f, "It is used as there are no Scopes defined for this method.") + }, + Error::BadRequest(ref err) => { + try!(writeln!(f, "Bad Requst ({}): {}", err.error.code, err.error.message)); + for err in err.error.errors.iter() { + try!(writeln!(f, " {}: {}, {}{}", + err.domain, + err.message, + err.reason, + match &err.location { + &Some(ref loc) => format!("@{}", loc), + &None => String::new(), + })); + } + Ok(()) + }, + Error::MissingToken(ref err) => + writeln!(f, "Token retrieval failed with error: {}", err), + Error::Cancelled => + writeln!(f, "Operation cancelled by delegate"), + Error::FieldClash(field) => + writeln!(f, "The custom parameter '{}' is already provided natively by the CallBuilder.", field), + Error::JsonDecodeError(ref json_str, ref err) + => writeln!(f, "{}: {}", err, json_str), + Error::Failure(ref response) => + writeln!(f, "Http status indicates failure: {:?}", response), + } + } +} + +impl error::Error for Error { + fn description(&self) -> &str { + match *self { + Error::HttpError(ref err) => err.description(), + Error::JsonDecodeError(_, ref err) => err.description(), + _ => "NO DESCRIPTION POSSIBLE - use `Display.fmt()` instead" + } + } + + fn cause(&self) -> Option<&error::Error> { + match *self { + Error::HttpError(ref err) => err.cause(), + Error::JsonDecodeError(_, ref err) => err.cause(), + _ => None + } + } +} + +/// A universal result type used as return for all calls. +pub type Result = std::result::Result; + +/// 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 + 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 following macro invocation needs to be expanded, as `include!` +// doens't support external macros +// header!{ +// #[doc="The `X-Upload-Content-Type` header."] +// (XUploadContentType, "X-Upload-Content-Type") => [Mime] + +// xupload_content_type { +// test_header!( +// test1, +// vec![b"text/plain"], +// Some(HeaderField( +// vec![Mime(TopLevel::Text, SubLevel::Plain, Vec::new())] +// ))); + +// } +// } + +/// The `X-Upload-Content-Type` header. +/// +/// Generated via rustc --pretty expanded -Z unstable-options, and manually +/// processed to be more readable. +#[derive(PartialEq, Debug, Clone)] +pub struct XUploadContentType(pub Mime); + +impl ::std::ops::Deref for XUploadContentType { + type Target = Mime; + fn deref<'a>(&'a self) -> &'a Mime { &self.0 } +} +impl ::std::ops::DerefMut for XUploadContentType { + fn deref_mut<'a>(&'a mut self) -> &'a mut Mime { &mut self.0 } +} +impl Header for XUploadContentType { + fn header_name() -> &'static str { "X-Upload-Content-Type" } + fn parse_header(raw: &[Vec]) -> hyper::error::Result { + hyper::header::parsing::from_one_raw_str(raw).map(XUploadContentType) + } +} +impl HeaderFormat for XUploadContentType { + fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { + Display::fmt(&**self, f) + } +} +impl Display for XUploadContentType { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Display::fmt(&**self, f) + } +} + +#[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]) -> hyper::error::Result { + Err(hyper::error::Error::Method) + } +} + + +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]) -> hyper::error::Result { + if raw.len() > 0 { + let v = &raw[0]; + if let Ok(s) = std::str::from_utf8(v) { + const PREFIX: &'static str = "bytes "; + if s.starts_with(PREFIX) { + if let Ok(c) = ::from_str(&s[PREFIX.len()..]) { + return Ok(RangeResponseHeader(c)) + } + } + } + } + Err(hyper::error::Error::Method) + } +} + +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, 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, A> ResumableUploadHelper<'a, A> + where A: oauth2::GetToken { + + fn query_transfer_status(&mut self) -> std::result::Result> { + 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, None) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + return Err(Ok(r)) + } + }; + return Ok(h.0.last) + } + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + return Err(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() { + Ok(s) => s, + Err(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 + }; + + self.reader.seek(SeekFrom::Start(start)).unwrap(); + loop { + let request_size = match self.content_length - start { + rs if rs > chunk_size => chunk_size, + rs => rs + }; + + 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 + } + // workaround https://github.com/rust-lang/rust/issues/22252 + let res = 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(); + match res { + 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, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + } + return Some(Ok(res)) + }, + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + return Some(Err(err)) + } + } + } + } +} + +// Copy of src/rust/cli/cmn.rs +// TODO(ST): Allow sharing common code between program types +pub fn remove_json_null_values(value: &mut json::value::Value) { + match *value { + json::value::Value::Object(ref mut map) => { + let mut for_removal = Vec::new(); + + for (key, mut value) in map.iter_mut() { + if value.is_null() { + for_removal.push(key.clone()); + } else { + remove_json_null_values(&mut value); + } + } + + for key in &for_removal { + map.remove(key); + } + } + _ => {} + } +} diff --git a/gen/cloudbilling1/src/lib.rs b/gen/cloudbilling1/src/lib.rs new file mode 100644 index 0000000000..4dcccbc91d --- /dev/null +++ b/gen/cloudbilling1/src/lib.rs @@ -0,0 +1,183 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/api/lib.rs.mako' +// DO NOT EDIT ! + +//! This documentation was generated from *cloudbilling* crate version *0.1.9+20150903*, where *20150903* is the exact revision of the *cloudbilling:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +//! +//! Everything else about the *cloudbilling* *v1* API can be found at the +//! [official documentation site](https://cloud.google.com/billing/). +//! The original source code is [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/cloudbilling1). +//! # Features +//! +//! Handle the following *Resources* with ease from the central [hub](struct.Cloudbilling.html) ... +//! +//! * [billing accounts](struct.BillingAccount.html) +//! * [*get*](struct.BillingAccountGetCall.html), [*list*](struct.BillingAccountListCall.html) and [*projects list*](struct.BillingAccountProjectListCall.html) +//! * projects +//! * [*get billing info*](struct.ProjectGetBillingInfoCall.html) and [*update billing info*](struct.ProjectUpdateBillingInfoCall.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.Cloudbilling.html)** +//! * a central object to maintain state and allow accessing all *Activities* +//! * creates [*Method Builders*](trait.MethodsBuilder.html) which in turn +//! allow access to individual [*Call Builders*](trait.CallBuilder.html) +//! * **[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* +//! +//! All *structures* are marked with applicable traits to further categorize them and ease browsing. +//! +//! Generally speaking, you can invoke *Activities* like this: +//! +//! ```Rust,ignore +//! let r = hub.resource().activity(...).doit() +//! ``` +//! +//! Or specifically ... +//! +//! ```ignore +//! let r = hub.billing_accounts().get(...).doit() +//! let r = hub.billing_accounts().list(...).doit() +//! let r = hub.billing_accounts().projects_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-cloudbilling1 = "*" +//! ``` +//! +//! ## A complete example +//! +//! ```test_harness,no_run +//! extern crate hyper; +//! extern crate yup_oauth2 as oauth2; +//! extern crate google_cloudbilling1 as cloudbilling1; +//! use cloudbilling1::{Result, Error}; +//! # #[test] fn egal() { +//! use std::default::Default; +//! use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +//! use cloudbilling1::Cloudbilling; +//! +//! // 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 = Cloudbilling::new(hyper::Client::new(), auth); +//! // You can configure optional parameters by calling 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_accounts().projects_list("name") +//! .page_token("dolores") +//! .page_size(-61) +//! .doit(); +//! +//! match result { +//! Err(e) => match e { +//! // The Error enum provides details about what exactly happened. +//! // You can also just use its `Debug`, `Display` or `Error` traits +//! Error::HttpError(_) +//! |Error::MissingAPIKey +//! |Error::MissingToken(_) +//! |Error::Cancelled +//! |Error::UploadSizeLimitExceeded(_, _) +//! |Error::Failure(_) +//! |Error::BadRequest(_) +//! |Error::FieldClash(_) +//! |Error::JsonDecodeError(_, _) => println!("{}", e), +//! }, +//! Ok(res) => println!("Success: {:?}", res), +//! } +//! # } +//! ``` +//! ## 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 Downloads +//! 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 identifiable 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 moved +//! +//! 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 +//! +//! + +// 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)] + +include!(concat!(env!("OUT_DIR"), "/lib.rs")); \ No newline at end of file diff --git a/gen/cloudbilling1/src/lib.rs.in b/gen/cloudbilling1/src/lib.rs.in new file mode 100644 index 0000000000..c9e0cdec46 --- /dev/null +++ b/gen/cloudbilling1/src/lib.rs.in @@ -0,0 +1,1706 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/api/lib.rs.in.mako' +// DO NOT EDIT ! + +extern crate hyper; +extern crate serde; +extern crate serde_json; +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 serde_json as json; +use std::io; +use std::fs; +use std::thread::sleep_ms; + +pub use cmn::{MultiPartReader, ToParts, MethodInfo, Result, Error, CallBuilder, Hub, ReadSeek, Part, + ResponseResult, RequestValue, NestedType, Delegate, DefaultDelegate, MethodsBuilder, + Resource, ErrorResponse, remove_json_null_values}; + + +// ############## +// 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 AsRef for Scope { + fn as_ref(&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 Cloudbilling related resource activities +/// +/// # Examples +/// +/// Instantiate a new hub +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate yup_oauth2 as oauth2; +/// extern crate google_cloudbilling1 as cloudbilling1; +/// use cloudbilling1::{Result, Error}; +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use cloudbilling1::Cloudbilling; +/// +/// // 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 = Cloudbilling::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling 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_accounts().projects_list("name") +/// .page_token("et") +/// .page_size(-18) +/// .doit(); +/// +/// match result { +/// Err(e) => match e { +/// // The Error enum provides details about what exactly happened. +/// // You can also just use its `Debug`, `Display` or `Error` traits +/// Error::HttpError(_) +/// |Error::MissingAPIKey +/// |Error::MissingToken(_) +/// |Error::Cancelled +/// |Error::UploadSizeLimitExceeded(_, _) +/// |Error::Failure(_) +/// |Error::BadRequest(_) +/// |Error::FieldClash(_) +/// |Error::JsonDecodeError(_, _) => println!("{}", e), +/// }, +/// Ok(res) => println!("Success: {:?}", res), +/// } +/// # } +/// ``` +pub struct Cloudbilling { + client: RefCell, + auth: RefCell, + _user_agent: String, +} + +impl<'a, C, A> Hub for Cloudbilling {} + +impl<'a, C, A> Cloudbilling + where C: BorrowMut, A: oauth2::GetToken { + + pub fn new(client: C, authenticator: A) -> Cloudbilling { + Cloudbilling { + client: RefCell::new(client), + auth: RefCell::new(authenticator), + _user_agent: "google-api-rust-client/0.1.9".to_string(), + } + } + + pub fn billing_accounts(&'a self) -> BillingAccountMethods<'a, C, A> { + BillingAccountMethods { hub: &self } + } + pub fn projects(&'a self) -> ProjectMethods<'a, C, 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.9`. + /// + /// 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 ### +// ########## +/// Encapsulation of billing information for a Developers Console project. A project has at most one associated billing account at a time (but a billing account can be assigned to multiple projects). +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where 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 billing info projects](struct.ProjectUpdateBillingInfoCall.html) (request|response) +/// * [get billing info projects](struct.ProjectGetBillingInfoCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ProjectBillingInfo { + /// The ID of the project that this `ProjectBillingInfo` represents, such as `tokyo-rain-123`. This is a convenience field so that you don't need to parse the `name` field to obtain a project ID. This field is read-only. + #[serde(rename="projectId")] + pub project_id: Option, + /// The resource name for the `ProjectBillingInfo`; has the form `projects/{project_id}/billingInfo`. For example, the resource name for the billing information for project `tokyo-rain-123` would be `projects/tokyo-rain-123/billingInfo`. This field is read-only. + pub name: Option, + /// True if the project is associated with an open billing account, to which usage on the project is charged. False if the project is associated with a closed billing account, or no billing account at all, and therefore cannot use paid services. This field is read-only. + #[serde(rename="billingEnabled")] + pub billing_enabled: Option, + /// The resource name of the billing account associated with the project, if any. For example, `billingAccounts/012345-567890-ABCDEF`. + #[serde(rename="billingAccountName")] + pub billing_account_name: Option, +} + +impl RequestValue for ProjectBillingInfo {} +impl ResponseResult for ProjectBillingInfo {} + + +/// Request message for `ListProjectBillingInfoResponse`. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [projects list billing accounts](struct.BillingAccountProjectListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ListProjectBillingInfoResponse { + /// A token to retrieve the next page of results. To retrieve the next page, call `ListProjectBillingInfo` again with the `page_token` field set to this value. This field is empty if there are no more results to retrieve. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// A list of `ProjectBillingInfo` resources representing the projects associated with the billing account. + #[serde(rename="projectBillingInfo")] + pub project_billing_info: Option>, +} + +impl ResponseResult for ListProjectBillingInfoResponse {} + + +/// A billing account in [Google Developers Console](https://console.developers.google.com/). You can assign a billing account to one or more projects. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where 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 accounts](struct.BillingAccountGetCall.html) (response) +/// * [list billing accounts](struct.BillingAccountListCall.html) (none) +/// * [projects list billing accounts](struct.BillingAccountProjectListCall.html) (none) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct BillingAccount { + /// True if the billing account is open, and will therefore be charged for any usage on associated projects. False if the billing account is closed, and therefore projects associated with it will be unable to use paid services. + pub open: Option, + /// The display name given to the billing account, such as `My Billing Account`. This name is displayed in the Google Developers Console. + #[serde(rename="displayName")] + pub display_name: Option, + /// The resource name of the billing account. The resource name has the form `billingAccounts/{billing_account_id}`. For example, `billingAccounts/012345-567890-ABCDEF` would be the resource name for billing account `012345-567890-ABCDEF`. + pub name: Option, +} + +impl Resource for BillingAccount {} +impl ResponseResult for BillingAccount {} + + +/// Response message for `ListBillingAccounts`. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where 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 accounts](struct.BillingAccountListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ListBillingAccountsResponse { + /// A token to retrieve the next page of results. To retrieve the next page, call `ListBillingAccounts` again with the `page_token` field set to this value. This field is empty if there are no more results to retrieve. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// A list of billing accounts. + #[serde(rename="billingAccounts")] + pub billing_accounts: Option>, +} + +impl ResponseResult for ListBillingAccountsResponse {} + + + +// ################### +// MethodBuilders ### +// ################# + +/// A builder providing access to all methods supported on *billingAccount* resources. +/// It is not used directly, but through the `Cloudbilling` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate yup_oauth2 as oauth2; +/// extern crate google_cloudbilling1 as cloudbilling1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use cloudbilling1::Cloudbilling; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Cloudbilling::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get(...)`, `list(...)` and `projects_list(...)` +/// // to build up your call. +/// let rb = hub.billing_accounts(); +/// # } +/// ``` +pub struct BillingAccountMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Cloudbilling, +} + +impl<'a, C, A> MethodsBuilder for BillingAccountMethods<'a, C, A> {} + +impl<'a, C, A> BillingAccountMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Gets information about a billing account. The current authenticated user must be an [owner of the billing account](https://support.google.com/cloud/answer/4430947). + /// + /// # Arguments + /// + /// * `name` - The resource name of the billing account to retrieve. For example, `billingAccounts/012345-567890-ABCDEF`. + pub fn get(&self, name: &str) -> BillingAccountGetCall<'a, C, A> { + BillingAccountGetCall { + hub: self.hub, + _name: name.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Lists the billing accounts that the current authenticated user [owns](https://support.google.com/cloud/answer/4430947). + pub fn list(&self) -> BillingAccountListCall<'a, C, A> { + BillingAccountListCall { + hub: self.hub, + _page_token: Default::default(), + _page_size: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Lists the projects associated with a billing account. The current authenticated user must be an [owner of the billing account](https://support.google.com/cloud/answer/4430947). + /// + /// # Arguments + /// + /// * `name` - The resource name of the billing account associated with the projects that you want to list. For example, `billingAccounts/012345-567890-ABCDEF`. + pub fn projects_list(&self, name: &str) -> BillingAccountProjectListCall<'a, C, A> { + BillingAccountProjectListCall { + hub: self.hub, + _name: name.to_string(), + _page_token: Default::default(), + _page_size: 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 `Cloudbilling` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate yup_oauth2 as oauth2; +/// extern crate google_cloudbilling1 as cloudbilling1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use cloudbilling1::Cloudbilling; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Cloudbilling::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get_billing_info(...)` and `update_billing_info(...)` +/// // to build up your call. +/// let rb = hub.projects(); +/// # } +/// ``` +pub struct ProjectMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Cloudbilling, +} + +impl<'a, C, A> MethodsBuilder for ProjectMethods<'a, C, A> {} + +impl<'a, C, A> ProjectMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Gets the billing information for a project. The current authenticated user must have [permission to view the project](https://cloud.google.com/docs/permissions-overview#h.bgs0oxofvnoo ). + /// + /// # Arguments + /// + /// * `name` - The resource name of the project for which billing information is retrieved. For example, `projects/tokyo-rain-123`. + pub fn get_billing_info(&self, name: &str) -> ProjectGetBillingInfoCall<'a, C, A> { + ProjectGetBillingInfoCall { + hub: self.hub, + _name: name.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Sets or updates the billing account associated with a project. You specify the new billing account by setting the `billing_account_name` in the `ProjectBillingInfo` resource to the resource name of a billing account. Associating a project with an open billing account enables billing on the project and allows charges for resource usage. If the project already had a billing account, this method changes the billing account used for resource usage charges. *Note:* Incurred charges that have not yet been reported in the transaction history of the Google Developers Console may be billed to the new billing account, even if the charge occurred before the new billing account was assigned to the project. The current authenticated user must have ownership privileges for both the [project](https://cloud.google.com/docs/permissions-overview#h.bgs0oxofvnoo ) and the [billing account](https://support.google.com/cloud/answer/4430947). You can disable billing on the project by setting the `billing_account_name` field to empty. This action disassociates the current billing account from the project. Any billable activity of your in-use services will stop, and your application could stop functioning as expected. Any unbilled charges to date will be billed to the previously associated account. The current authenticated user must be either an owner of the project or an owner of the billing account for the project. Note that associating a project with a *closed* billing account will have much the same effect as disabling billing on the project: any paid resources used by the project will be shut down. Thus, unless you wish to disable billing, you should always call this method with the name of an *open* billing account. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `name` - The resource name of the project associated with the billing information that you want to update. For example, `projects/tokyo-rain-123`. + pub fn update_billing_info(&self, request: ProjectBillingInfo, name: &str) -> ProjectUpdateBillingInfoCall<'a, C, A> { + ProjectUpdateBillingInfoCall { + hub: self.hub, + _request: request, + _name: name.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + + + +// ################### +// CallBuilders ### +// ################# + +/// Gets information about a billing account. The current authenticated user must be an [owner of the billing account](https://support.google.com/cloud/answer/4430947). +/// +/// A builder for the *get* method supported by a *billingAccount* resource. +/// It is not used directly, but through a `BillingAccountMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_cloudbilling1 as cloudbilling1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use cloudbilling1::Cloudbilling; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Cloudbilling::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling 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_accounts().get("name") +/// .doit(); +/// # } +/// ``` +pub struct BillingAccountGetCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Cloudbilling, + _name: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for BillingAccountGetCall<'a, C, A> {} + +impl<'a, C, A> BillingAccountGetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, BillingAccount)> { + use url::percent_encoding::{percent_encode, FORM_URLENCODED_ENCODE_SET}; + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "cloudbilling.billingAccounts.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("name", self._name.to_string())); + for &field in ["alt", "name"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://cloudbilling.googleapis.com/v1/{+name}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{+name}", "name")].iter() { + let mut replace_with = String::new(); + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = value.to_string(); + break; + } + } + if find_this.as_bytes()[1] == '+' as u8 { + replace_with = percent_encode(replace_with.as_bytes(), FORM_URLENCODED_ENCODE_SET); + } + url = url.replace(find_this, &replace_with); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["name"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The resource name of the billing account to retrieve. For example, `billingAccounts/012345-567890-ABCDEF`. + /// + /// Sets the *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 name(mut self, new_value: &str) -> BillingAccountGetCall<'a, C, A> { + self._name = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> BillingAccountGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> BillingAccountGetCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> BillingAccountGetCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Lists the billing accounts that the current authenticated user [owns](https://support.google.com/cloud/answer/4430947). +/// +/// A builder for the *list* method supported by a *billingAccount* resource. +/// It is not used directly, but through a `BillingAccountMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_cloudbilling1 as cloudbilling1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use cloudbilling1::Cloudbilling; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Cloudbilling::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling 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_accounts().list() +/// .page_token("accusam") +/// .page_size(-8) +/// .doit(); +/// # } +/// ``` +pub struct BillingAccountListCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Cloudbilling, + _page_token: Option, + _page_size: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for BillingAccountListCall<'a, C, A> {} + +impl<'a, C, A> BillingAccountListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ListBillingAccountsResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "cloudbilling.billingAccounts.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._page_size { + params.push(("pageSize", value.to_string())); + } + for &field in ["alt", "pageToken", "pageSize"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://cloudbilling.googleapis.com/v1/billingAccounts".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// A token identifying a page of results to return. This should be a `next_page_token` value returned from a previous `ListBillingAccounts` call. If unspecified, the first page of results is returned. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> BillingAccountListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Requested page size. The maximum page size is 100; this is also the default. + /// + /// Sets the *page size* query property to the given value. + pub fn page_size(mut self, new_value: i32) -> BillingAccountListCall<'a, C, A> { + self._page_size = Some(new_value); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> BillingAccountListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> BillingAccountListCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> BillingAccountListCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Lists the projects associated with a billing account. The current authenticated user must be an [owner of the billing account](https://support.google.com/cloud/answer/4430947). +/// +/// A builder for the *projects.list* method supported by a *billingAccount* resource. +/// It is not used directly, but through a `BillingAccountMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_cloudbilling1 as cloudbilling1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use cloudbilling1::Cloudbilling; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Cloudbilling::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling 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_accounts().projects_list("name") +/// .page_token("amet.") +/// .page_size(-81) +/// .doit(); +/// # } +/// ``` +pub struct BillingAccountProjectListCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Cloudbilling, + _name: String, + _page_token: Option, + _page_size: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for BillingAccountProjectListCall<'a, C, A> {} + +impl<'a, C, A> BillingAccountProjectListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ListProjectBillingInfoResponse)> { + use url::percent_encoding::{percent_encode, FORM_URLENCODED_ENCODE_SET}; + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "cloudbilling.billingAccounts.projects.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("name", self._name.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())); + } + for &field in ["alt", "name", "pageToken", "pageSize"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://cloudbilling.googleapis.com/v1/{+name}/projects".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{+name}", "name")].iter() { + let mut replace_with = String::new(); + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = value.to_string(); + break; + } + } + if find_this.as_bytes()[1] == '+' as u8 { + replace_with = percent_encode(replace_with.as_bytes(), FORM_URLENCODED_ENCODE_SET); + } + url = url.replace(find_this, &replace_with); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["name"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The resource name of the billing account associated with the projects that you want to list. For example, `billingAccounts/012345-567890-ABCDEF`. + /// + /// Sets the *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 name(mut self, new_value: &str) -> BillingAccountProjectListCall<'a, C, A> { + self._name = new_value.to_string(); + self + } + /// A token identifying a page of results to be returned. This should be a `next_page_token` value returned from a previous `ListProjectBillingInfo` call. If unspecified, the first page of results is returned. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> BillingAccountProjectListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Requested page size. The maximum page size is 100; this is also the default. + /// + /// Sets the *page size* query property to the given value. + pub fn page_size(mut self, new_value: i32) -> BillingAccountProjectListCall<'a, C, A> { + self._page_size = Some(new_value); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> BillingAccountProjectListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> BillingAccountProjectListCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> BillingAccountProjectListCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Gets the billing information for a project. The current authenticated user must have [permission to view the project](https://cloud.google.com/docs/permissions-overview#h.bgs0oxofvnoo ). +/// +/// A builder for the *getBillingInfo* method supported by a *project* resource. +/// It is not used directly, but through a `ProjectMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_cloudbilling1 as cloudbilling1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use cloudbilling1::Cloudbilling; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Cloudbilling::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling 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_billing_info("name") +/// .doit(); +/// # } +/// ``` +pub struct ProjectGetBillingInfoCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Cloudbilling, + _name: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ProjectGetBillingInfoCall<'a, C, A> {} + +impl<'a, C, A> ProjectGetBillingInfoCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ProjectBillingInfo)> { + use url::percent_encoding::{percent_encode, FORM_URLENCODED_ENCODE_SET}; + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "cloudbilling.projects.getBillingInfo", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("name", self._name.to_string())); + for &field in ["alt", "name"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://cloudbilling.googleapis.com/v1/{+name}/billingInfo".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{+name}", "name")].iter() { + let mut replace_with = String::new(); + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = value.to_string(); + break; + } + } + if find_this.as_bytes()[1] == '+' as u8 { + replace_with = percent_encode(replace_with.as_bytes(), FORM_URLENCODED_ENCODE_SET); + } + url = url.replace(find_this, &replace_with); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["name"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The resource name of the project for which billing information is retrieved. For example, `projects/tokyo-rain-123`. + /// + /// Sets the *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 name(mut self, new_value: &str) -> ProjectGetBillingInfoCall<'a, C, A> { + self._name = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectGetBillingInfoCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> ProjectGetBillingInfoCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProjectGetBillingInfoCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Sets or updates the billing account associated with a project. You specify the new billing account by setting the `billing_account_name` in the `ProjectBillingInfo` resource to the resource name of a billing account. Associating a project with an open billing account enables billing on the project and allows charges for resource usage. If the project already had a billing account, this method changes the billing account used for resource usage charges. *Note:* Incurred charges that have not yet been reported in the transaction history of the Google Developers Console may be billed to the new billing account, even if the charge occurred before the new billing account was assigned to the project. The current authenticated user must have ownership privileges for both the [project](https://cloud.google.com/docs/permissions-overview#h.bgs0oxofvnoo ) and the [billing account](https://support.google.com/cloud/answer/4430947). You can disable billing on the project by setting the `billing_account_name` field to empty. This action disassociates the current billing account from the project. Any billable activity of your in-use services will stop, and your application could stop functioning as expected. Any unbilled charges to date will be billed to the previously associated account. The current authenticated user must be either an owner of the project or an owner of the billing account for the project. Note that associating a project with a *closed* billing account will have much the same effect as disabling billing on the project: any paid resources used by the project will be shut down. Thus, unless you wish to disable billing, you should always call this method with the name of an *open* billing account. +/// +/// A builder for the *updateBillingInfo* method supported by a *project* resource. +/// It is not used directly, but through a `ProjectMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_cloudbilling1 as cloudbilling1; +/// use cloudbilling1::ProjectBillingInfo; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use cloudbilling1::Cloudbilling; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Cloudbilling::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req = ProjectBillingInfo::default(); +/// +/// // You can configure optional parameters by calling 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().update_billing_info(req, "name") +/// .doit(); +/// # } +/// ``` +pub struct ProjectUpdateBillingInfoCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Cloudbilling, + _request: ProjectBillingInfo, + _name: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ProjectUpdateBillingInfoCall<'a, C, A> {} + +impl<'a, C, A> ProjectUpdateBillingInfoCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ProjectBillingInfo)> { + use url::percent_encoding::{percent_encode, FORM_URLENCODED_ENCODE_SET}; + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "cloudbilling.projects.updateBillingInfo", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("name", self._name.to_string())); + for &field in ["alt", "name"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://cloudbilling.googleapis.com/v1/{+name}/billingInfo".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{+name}", "name")].iter() { + let mut replace_with = String::new(); + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = value.to_string(); + break; + } + } + if find_this.as_bytes()[1] == '+' as u8 { + replace_with = percent_encode(replace_with.as_bytes(), FORM_URLENCODED_ENCODE_SET); + } + url = url.replace(find_this, &replace_with); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["name"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: ProjectBillingInfo) -> ProjectUpdateBillingInfoCall<'a, C, A> { + self._request = new_value; + self + } + /// The resource name of the project associated with the billing information that you want to update. For example, `projects/tokyo-rain-123`. + /// + /// Sets the *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 name(mut self, new_value: &str) -> ProjectUpdateBillingInfoCall<'a, C, A> { + self._name = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectUpdateBillingInfoCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> ProjectUpdateBillingInfoCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProjectUpdateBillingInfoCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + diff --git a/gen/clouddebugger2-cli/Cargo.toml b/gen/clouddebugger2-cli/Cargo.toml new file mode 100644 index 0000000000..9a0551463a --- /dev/null +++ b/gen/clouddebugger2-cli/Cargo.toml @@ -0,0 +1,35 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-clouddebugger2-cli" +version = "0.3.2+20150725" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with clouddebugger (protocol v2)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/clouddebugger2-cli" +homepage = "https://cloud.google.com/tools/cloud-debugger" +documentation = "http://byron.github.io/google-apis-rs/google_clouddebugger2_cli" +license = "MIT" +keywords = ["clouddebugger", "google", "cli"] + +[[bin]] +name = "clouddebugger2" + +[dependencies] +hyper = ">= 0.6.8" +mime = "0.1.0" +serde = ">= 0.6.0" +serde_json = ">= 0.6.0" +yup-oauth2 = "*" +strsim = "*" +yup-hyper-mock = ">=1.0.0" +clap = ">= 1.0.3" + +[build-dependencies] +syntex = { version = "*" } +serde_codegen = { version = "*" } + + +[dependencies.google-clouddebugger2] +path = "../clouddebugger2" diff --git a/gen/clouddebugger2-cli/LICENSE.md b/gen/clouddebugger2-cli/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/clouddebugger2-cli/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/clouddebugger2-cli/README.md b/gen/clouddebugger2-cli/README.md new file mode 100644 index 0000000000..85ce8170ed --- /dev/null +++ b/gen/clouddebugger2-cli/README.md @@ -0,0 +1,121 @@ + +The `clouddebugger2` command-line interface *(CLI)* allows to use most features of the *Google clouddebugger* service from the comfort of your terminal. + +By default all output is printed to standard out, but flags can be set to direct it into a file independent of your shell's +capabilities. Errors will be printed to standard error, and cause the program's exit code to be non-zero. + +If data-structures are requested, these will be returned as pretty-printed JSON, to be useful as input to other tools. + +Everything else about the *clouddebugger* API can be found at the +[official documentation site](https://cloud.google.com/tools/cloud-debugger). + +# Downloads + +You can download the pre-compiled 64bit binaries for the following platforms: + +* ![icon](http://megaicons.net/static/img/icons_sizes/6/140/16/ubuntu-icon.png) [ubuntu](http://dl.byronimo.de/google.rs/cli/0.3.2/ubuntu/clouddebugger2.tar.gz) +* ![icon](http://hydra-media.cursecdn.com/wow.gamepedia.com/a/a2/Apple-icon-16x16.png?version=25ddd67ac3dd3b634478e3978b76cb74) [osx](http://dl.byronimo.de/google.rs/cli/0.3.2/osx/clouddebugger2.tar.gz) + +Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/clouddebugger2-cli). + +# Usage + +This documentation was generated from the *clouddebugger* API at revision *20150725*. The CLI is at version *0.3.2*. + +```bash +clouddebugger2 [options] + controller + debuggees-breakpoints-list [-p ]... [-o ] + debuggees-breakpoints-update (-r )... [-p ]... [-o ] + debuggees-register (-r )... [-p ]... [-o ] + debugger + debuggees-breakpoints-delete [-p ]... [-o ] + debuggees-breakpoints-get [-p ]... [-o ] + debuggees-breakpoints-list [-p ]... [-o ] + debuggees-breakpoints-set (-r )... [-p ]... [-o ] + debuggees-list [-p ]... [-o ] + clouddebugger2 --help + +Configuration: + [--scope ]... + Specify the authentication a method should be executed in. Each scope + requires the user to grant this application permission to use it. + If unset, it defaults to the shortest scope url for a particular method. + --config-dir + A directory into which we will store our persistent data. Defaults to + a user-writable directory that we will create during the first invocation. + [default: ~/.google-service-cli] + --debug + Output all server communication to standard error. `tx` and `rx` are placed + into the same stream. + --debug-auth + Output all communication related to authentication to standard error. `tx` + and `rx` are placed into the same stream. + +``` + +# Configuration + +The program will store all persistent data in the `~/.google-service-cli` directory in *JSON* files prefixed with `clouddebugger2-`. You can change the directory used to store configuration with the `--config-dir` flag on a per-invocation basis. + +More information about the various kinds of persistent data are given in the following paragraphs. + +# Authentication + +Most APIs require a user to authenticate any request. If this is the case, the [scope][scopes] determines the +set of permissions granted. The granularity of these is usually no more than *read-only* or *full-access*. + +If not set, the system will automatically select the smallest feasible scope, e.g. when invoking a +method that is read-only, it will ask only for a read-only scope. +You may use the `--scope` flag to specify a scope directly. +All applicable scopes are documented in the respective method's CLI documentation. + +The first time a scope is used, the user is asked for permission. Follow the instructions given +by the CLI to grant permissions, or to decline. + +If a scope was authenticated by the user, the respective information will be stored as *JSON* in the configuration +directory, e.g. `~/.google-service-cli/clouddebugger2-token-.json`. No manual management of these tokens +is necessary. + +To revoke granted authentication, please refer to the [official documentation][revoke-access]. + +# Application Secrets + +In order to allow any application to use Google services, it will need to be registered using the +[Google Developer Console][google-dev-console]. APIs the application may use are then enabled for it +one by one. Most APIs can be used for free and have a daily quota. + +To allow more comfortable usage of the CLI without forcing anyone to register an own application, the CLI +comes with a default application secret that is configured accordingly. This also means that heavy usage +all around the world may deplete the daily quota. + +You can workaround this limitation by putting your own secrets file at this location: +`~/.google-service-cli/clouddebugger2-secret.json`, assuming that the required *clouddebugger* API +was enabled for it. Such a secret file can be downloaded in the *Google Developer Console* at +*APIs & auth -> Credentials -> Download JSON* and used as is. + +Learn more about how to setup Google projects and enable APIs using the [official documentation][google-project-new]. + + +# Debugging + +Even though the CLI does its best to provide usable error messages, sometimes it might be desirable to know +what exactly led to a particular issue. This is done by allowing all client-server communication to be +output to standard error *as-is*. + +The `--debug` flag will print all client-server communication to standard error, whereas the `--debug-auth` flag +will cause all communication related to authentication to standard error. +If the `--debug` flag is set, error-results will be debug-printed, possibly yielding more information about the +issue at hand. + +You may consider redirecting standard error into a file for ease of use, e.g. `clouddebugger2 --debug [options] 2>debug.txt`. + + +[scopes]: https://developers.google.com/+/api/oauth#scopes +[revoke-access]: http://webapps.stackexchange.com/a/30849 +[google-dev-console]: https://console.developers.google.com/ +[google-project-new]: https://developers.google.com/console/help/new/ \ No newline at end of file diff --git a/gen/clouddebugger2-cli/mkdocs.yml b/gen/clouddebugger2-cli/mkdocs.yml new file mode 100644 index 0000000000..3b2c07e0e5 --- /dev/null +++ b/gen/clouddebugger2-cli/mkdocs.yml @@ -0,0 +1,24 @@ +site_name: clouddebugger v0.3.2+20150725 +site_url: http://byron.github.io/google-apis-rs/google-clouddebugger2-cli +site_description: Write integrating applications with bcore + +repo_url: https://github.com/Byron/google-apis-rs/tree/master/gen/clouddebugger2-cli + +docs_dir: docs +site_dir: build_html + +pages: +- ['index.md', 'Home'] +- ['controller_debuggees-breakpoints-list.md', 'Controller', 'Debuggees Breakpoints List'] +- ['controller_debuggees-breakpoints-update.md', 'Controller', 'Debuggees Breakpoints Update'] +- ['controller_debuggees-register.md', 'Controller', 'Debuggees Register'] +- ['debugger_debuggees-breakpoints-delete.md', 'Debugger', 'Debuggees Breakpoints Delete'] +- ['debugger_debuggees-breakpoints-get.md', 'Debugger', 'Debuggees Breakpoints Get'] +- ['debugger_debuggees-breakpoints-list.md', 'Debugger', 'Debuggees Breakpoints List'] +- ['debugger_debuggees-breakpoints-set.md', 'Debugger', 'Debuggees Breakpoints Set'] +- ['debugger_debuggees-list.md', 'Debugger', 'Debuggees List'] + +theme: readthedocs + +copyright: Copyright © 2015, `Sebastian Thiel` + diff --git a/gen/clouddebugger2-cli/src/cmn.rs b/gen/clouddebugger2-cli/src/cmn.rs new file mode 100644 index 0000000000..8358f156fa --- /dev/null +++ b/gen/clouddebugger2-cli/src/cmn.rs @@ -0,0 +1,721 @@ +// COPY OF 'src/rust/cli/cmn.rs' +// DO NOT EDIT +use oauth2::{ApplicationSecret, ConsoleApplicationSecret, TokenStorage, Token}; +use serde_json as json; +use serde_json::value::Value; +use mime::Mime; +use clap::{App, SubCommand}; +use strsim; + +use std::fs; +use std::env; +use std::io; +use std::fmt; +use std::path::{Path, PathBuf}; +use std::str::FromStr; +use std::string::ToString; +use std::io::{Write, Read, stdout}; + +use std::default::Default; + +const FIELD_SEP: char = '.'; + + +pub enum ComplexType { + Pod, + Vec, + Map, +} + + // Null, + // Bool(bool), + // I64(i64), + // U64(u64), + // F64(f64), + // String(String), + +pub enum JsonType { + Boolean, + Int, + Uint, + Float, + String, +} + +pub struct JsonTypeInfo { + pub jtype: JsonType, + pub ctype: ComplexType, +} + +// Based on @erickt user comment. Thanks for the idea ! +// Remove all keys whose values are null from given value (changed in place) +pub fn remove_json_null_values(value: &mut Value) { + match *value { + Value::Object(ref mut map) => { + let mut for_removal = Vec::new(); + + for (key, mut value) in map.iter_mut() { + if value.is_null() { + for_removal.push(key.clone()); + } else { + remove_json_null_values(&mut value); + } + } + + for key in &for_removal { + map.remove(key); + } + } + _ => {} + } +} + +fn did_you_mean<'a>(v: &str, possible_values: &[&'a str]) -> Option<&'a str> { + + let mut candidate: Option<(f64, &str)> = None; + for pv in possible_values { + let confidence = strsim::jaro_winkler(v, pv); + if confidence > 0.8 && (candidate.is_none() || (candidate.as_ref().unwrap().0 < confidence)) { + candidate = Some((confidence, pv)); + } + } + match candidate { + None => None, + Some((_, candidate)) => Some(candidate), + } +} + +pub enum CallType { + Upload(UploadProtocol), + Standard, +} + +arg_enum!{ + pub enum UploadProtocol { + Simple, + Resumable + } +} + +impl AsRef for UploadProtocol { + fn as_ref(&self) -> &str { + match *self { + UploadProtocol::Simple => "simple", + UploadProtocol::Resumable => "resumable" + } + } +} + +impl AsRef for CallType { + fn as_ref(&self) -> &str { + match *self { + CallType::Upload(ref proto) => proto.as_ref(), + CallType::Standard => "standard-request" + } + } +} + +#[derive(Clone, Default)] +pub struct FieldCursor(Vec); + +impl ToString for FieldCursor { + fn to_string(&self) -> String { + self.0.join(".") + } +} + +impl From<&'static str> for FieldCursor { + fn from(value: &'static str) -> FieldCursor { + let mut res = FieldCursor::default(); + res.set(value).unwrap(); + res + } +} + +impl FieldCursor { + pub fn set(&mut self, value: &str) -> Result<(), CLIError> { + if value.len() == 0 { + return Err(CLIError::Field(FieldError::Empty)) + } + + let mut first_is_field_sep = false; + let mut char_count: usize = 0; + let mut last_c = FIELD_SEP; + let mut num_conscutive_field_seps = 0; + + let mut field = String::new(); + let mut fields = self.0.clone(); + + let push_field = |fs: &mut Vec, f: &mut String| { + if f.len() > 0 { + fs.push(f.clone()); + f.truncate(0); + } + }; + + for (cid, c) in value.chars().enumerate() { + char_count += 1; + + if c == FIELD_SEP { + if cid == 0 { + first_is_field_sep = true; + } + num_conscutive_field_seps += 1; + if cid > 0 && last_c == FIELD_SEP { + if fields.pop().is_none() { + return Err(CLIError::Field(FieldError::PopOnEmpty(value.to_string()))) + } + } else { + push_field(&mut fields, &mut field); + } + } else { + num_conscutive_field_seps = 0; + if cid == 1 { + if first_is_field_sep { + fields.truncate(0); + } + } + field.push(c); + } + + last_c = c; + } + + push_field(&mut fields, &mut field); + + if char_count == 1 && first_is_field_sep { + fields.truncate(0); + } + if char_count > 1 && num_conscutive_field_seps == 1 { + return Err(CLIError::Field(FieldError::TrailingFieldSep(value.to_string()))) + } + + self.0 = fields; + Ok(()) + } + + pub fn did_you_mean(value: &str, possible_values: &[&str]) -> Option { + if value.len() == 0 { + return None + } + + let mut last_c = FIELD_SEP; + + let mut field = String::new(); + let mut output = String::new(); + + let push_field = |fs: &mut String, f: &mut String| { + if f.len() > 0 { + fs.push_str( + match did_you_mean(&f, possible_values) { + Some(candidate) => candidate, + None => &f, + }); + f.truncate(0); + } + }; + + for (cid, c) in value.chars().enumerate() { + if c == FIELD_SEP { + if last_c != FIELD_SEP { + push_field(&mut output, &mut field); + } + output.push(c); + } else { + field.push(c); + } + + last_c = c; + } + + push_field(&mut output, &mut field); + + if &output == value { + None + } else { + Some(output) + } + } + + pub fn set_json_value(&self, mut object: &mut Value, + value: &str, type_info: JsonTypeInfo, + err: &mut InvalidOptionsError, + orig_cursor: &FieldCursor) { + assert!(self.0.len() > 0); + + for field in &self.0[..self.0.len()-1] { + let tmp = object; + object = + match *tmp { + Value::Object(ref mut mapping) => { + mapping.entry(field.to_owned()).or_insert( + Value::Object(Default::default()) + ) + }, + _ => panic!("We don't expect non-object Values here ...") + }; + } + + match *object { + Value::Object(ref mut mapping) => { + let field = &self.0[self.0.len()-1]; + let to_jval = + |value: &str, jtype: JsonType, err: &mut InvalidOptionsError| + -> Value { + match jtype { + JsonType::Boolean => + Value::Bool(arg_from_str(value, err, &field, "boolean")), + JsonType::Int => + Value::I64(arg_from_str(value, err, &field, "int")), + JsonType::Uint => + Value::U64(arg_from_str(value, err, &field, "uint")), + JsonType::Float => + Value::F64(arg_from_str(value, err, &field, "float")), + JsonType::String => + Value::String(value.to_owned()), + } + }; + + match type_info.ctype { + ComplexType::Pod => { + if mapping.insert(field.to_owned(), to_jval(value, type_info.jtype, err)).is_some() { + err.issues.push(CLIError::Field(FieldError::Duplicate(orig_cursor.to_string()))); + } + }, + ComplexType::Vec => { + match *mapping.entry(field.to_owned()) + .or_insert(Value::Array(Default::default())) { + Value::Array(ref mut values) => values.push(to_jval(value, type_info.jtype, err)), + _ => unreachable!() + } + }, + ComplexType::Map => { + let (key, value) = parse_kv_arg(value, err, true); + let jval = to_jval(value.unwrap_or(""), type_info.jtype, err); + + match *mapping.entry(field.to_owned()) + .or_insert(Value::Object(Default::default())) { + Value::Object(ref mut value_map) => { + if value_map.insert(key.to_owned(), jval).is_some() { + err.issues.push(CLIError::Field(FieldError::Duplicate(orig_cursor.to_string()))); + } + } + _ => unreachable!() + } + } + } + }, + _ => unreachable!() + } + } + + pub fn num_fields(&self) -> usize { + self.0.len() + } +} + +pub fn parse_kv_arg<'a>(kv: &'a str, err: &mut InvalidOptionsError, for_hashmap: bool) + -> (&'a str, Option<&'a str>) { + let mut add_err = || err.issues.push(CLIError::InvalidKeyValueSyntax(kv.to_string(),for_hashmap)); + match kv.find('=') { + None => { + add_err(); + return (kv, None) + }, + Some(pos) => { + let key = &kv[..pos]; + if kv.len() <= pos + 1 { + add_err(); + return (key, Some("")) + } + (key, Some(&kv[pos+1..])) + } + } +} + +pub fn calltype_from_str(name: &str, valid_protocols: Vec, err: &mut InvalidOptionsError) -> CallType { + CallType::Upload( + match UploadProtocol::from_str(name) { + Ok(up) => up, + Err(msg) => { + err.issues.push(CLIError::InvalidUploadProtocol(name.to_string(), valid_protocols)); + UploadProtocol::Simple + } + }) +} + +pub fn input_file_from_opts(file_path: &str, err: &mut InvalidOptionsError) -> Option { + match fs::File::open(file_path) { + Ok(f) => Some(f), + Err(io_err) => { + err.issues.push(CLIError::Input(InputError::IOError((file_path.to_string(), io_err)))); + None + } + } +} + +pub fn input_mime_from_opts(mime: &str, err: &mut InvalidOptionsError) -> Option { + match mime.parse() { + Ok(m) => Some(m), + Err(_) => { + err.issues.push(CLIError::Input(InputError::Mime(mime.to_string()))); + None + } + } +} + +pub fn writer_from_opts(arg: Option<&str>) -> Result, io::Error> { + let f = arg.unwrap_or("-"); + match f { + "-" => Ok(Box::new(stdout())), + _ => match fs::OpenOptions::new().create(true).write(true).open(f) { + Ok(f) => Ok(Box::new(f)), + Err(io_err) => Err(io_err), + } + } +} + + +pub fn arg_from_str<'a, T>(arg: &str, err: &mut InvalidOptionsError, + arg_name: &'a str, + arg_type: &'a str) -> T + where T: FromStr + Default, + ::Err: fmt::Display { + match FromStr::from_str(arg) { + Err(perr) => { + err.issues.push( + CLIError::ParseError(arg_name.to_owned(), arg_type.to_owned(), arg.to_string(), format!("{}", perr)) + ); + Default::default() + }, + Ok(v) => v, + } +} + +pub struct JsonTokenStorage { + pub program_name: &'static str, + pub db_dir: String, +} + +impl JsonTokenStorage { + fn path(&self, scope_hash: u64) -> PathBuf { + Path::new(&self.db_dir).join(&format!("{}-token-{}.json", self.program_name, scope_hash)) + } +} + +impl TokenStorage for JsonTokenStorage { + type Error = json::Error; + + // NOTE: logging might be interesting, currently we swallow all errors + fn set(&mut self, scope_hash: u64, _: &Vec<&str>, token: Option) -> Result<(), json::Error> { + match token { + None => { + match fs::remove_file(self.path(scope_hash)) { + Err(err) => + match err.kind() { + io::ErrorKind::NotFound => Ok(()), + _ => Err(json::Error::IoError(err)) + }, + Ok(_) => Ok(()), + } + } + Some(token) => { + match fs::OpenOptions::new().create(true).write(true).open(&self.path(scope_hash)) { + Ok(mut f) => { + match json::to_writer_pretty(&mut f, &token) { + Ok(_) => Ok(()), + Err(serde_err) => Err(serde_err), + } + }, + Err(io_err) => Err(json::Error::IoError(io_err)) + } + } + } + } + + fn get(&self, scope_hash: u64, _: &Vec<&str>) -> Result, json::Error> { + match fs::File::open(&self.path(scope_hash)) { + Ok(mut f) => { + match json::de::from_reader(f) { + Ok(token) => Ok(Some(token)), + Err(err) => Err(err), + } + }, + Err(io_err) => { + match io_err.kind() { + io::ErrorKind::NotFound => Ok(None), + _ => Err(json::Error::IoError(io_err)) + } + } + } + } +} + + +#[derive(Debug)] +pub enum ApplicationSecretError { + DecoderError((String, json::Error)), + FormatError(String), +} + +impl fmt::Display for ApplicationSecretError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + ApplicationSecretError::DecoderError((ref path, ref err)) + => writeln!(f, "Could not decode file at '{}' with error: {}.", + path, err), + ApplicationSecretError::FormatError(ref path) + => writeln!(f, "'installed' field is unset in secret file at '{}'.", + path), + } + } +} + +#[derive(Debug)] +pub enum ConfigurationError { + DirectoryCreationFailed((String, io::Error)), + DirectoryUnset, + HomeExpansionFailed(String), + Secret(ApplicationSecretError), + IOError((String, io::Error)), +} + +impl fmt::Display for ConfigurationError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + ConfigurationError::DirectoryCreationFailed((ref dir, ref err)) + => writeln!(f, "Directory '{}' could not be created with error: {}.", dir, err), + ConfigurationError::DirectoryUnset + => writeln!(f, "--config-dir was unset or empty."), + ConfigurationError::HomeExpansionFailed(ref dir) + => writeln!(f, "Couldn't find HOME directory of current user, failed to expand '{}'.", dir), + ConfigurationError::Secret(ref err) + => writeln!(f, "Secret -> {}", err), + ConfigurationError::IOError((ref path, ref err)) + => writeln!(f, "IO operation failed on path '{}' with error: {}.", path, err), + } + } +} + +#[derive(Debug)] +pub enum InputError { + IOError((String, io::Error)), + Mime(String), +} + +impl fmt::Display for InputError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + InputError::IOError((ref file_path, ref io_err)) + => writeln!(f, "Failed to open '{}' for reading with error: {}.", file_path, io_err), + InputError::Mime(ref mime) + => writeln!(f, "'{}' is not a known mime-type.", mime), + } + } +} + +#[derive(Debug)] +pub enum FieldError { + PopOnEmpty(String), + TrailingFieldSep(String), + Unknown(String, Option, Option), + Duplicate(String), + Empty, +} + + +impl fmt::Display for FieldError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + FieldError::PopOnEmpty(ref field) + => writeln!(f, "'{}': Cannot move up on empty field cursor.", field), + FieldError::TrailingFieldSep(ref field) + => writeln!(f, "'{}': Single field separator may not be last character.", field), + FieldError::Unknown(ref field, ref suggestion, ref value) => { + let suffix = + match *suggestion { + Some(ref s) => { + let kv = + match *value { + Some(ref v) => format!("{}={}", s, v), + None => s.clone(), + }; + format!(" Did you mean '{}' ?", kv) + }, + None => String::new(), + }; + writeln!(f, "Field '{}' does not exist.{}", field, suffix) + }, + FieldError::Duplicate(ref cursor) + => writeln!(f, "Value at '{}' was already set", cursor), + FieldError::Empty + => writeln!(f, "Field names must not be empty."), + } + } +} + + +#[derive(Debug)] +pub enum CLIError { + Configuration(ConfigurationError), + ParseError(String, String, String, String), + UnknownParameter(String, Vec<&'static str>), + InvalidUploadProtocol(String, Vec), + InvalidKeyValueSyntax(String, bool), + Input(InputError), + Field(FieldError), + MissingCommandError, + MissingMethodError(String), +} + +impl fmt::Display for CLIError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + CLIError::Configuration(ref err) => write!(f, "Configuration -> {}", err), + CLIError::Input(ref err) => write!(f, "Input -> {}", err), + CLIError::Field(ref err) => write!(f, "Field -> {}", err), + CLIError::InvalidUploadProtocol(ref proto_name, ref valid_names) + => writeln!(f, "'{}' is not a valid upload protocol. Choose from one of {}.", proto_name, valid_names.join(", ")), + CLIError::ParseError(ref arg_name, ref type_name, ref value, ref err_desc) + => writeln!(f, "Failed to parse argument '{}' with value '{}' as {} with error: {}.", + arg_name, value, type_name, err_desc), + CLIError::UnknownParameter(ref param_name, ref possible_values) => { + let mut suffix = + match did_you_mean(param_name, &possible_values) { + Some(v) => format!(" Did you mean '{}' ?", v), + None => String::new(), + }; + write!(f, "Parameter '{}' is unknown.{}\n", param_name, suffix) + }, + CLIError::InvalidKeyValueSyntax(ref kv, is_hashmap) => { + let hashmap_info = if is_hashmap { "hashmap " } else { "" }; + writeln!(f, "'{}' does not match {}pattern =.", kv, hashmap_info) + }, + CLIError::MissingCommandError => writeln!(f, "Please specify the main sub-command."), + CLIError::MissingMethodError(ref cmd) => writeln!(f, "Please specify the method to call on the '{}' command.", cmd), + } + } +} + +#[derive(Debug)] +pub struct InvalidOptionsError { + pub issues: Vec, + pub exit_code: i32, +} + +impl fmt::Display for InvalidOptionsError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + for issue in &self.issues { + try!(issue.fmt(f)); + } + Ok(()) + } +} + +impl InvalidOptionsError { + pub fn single(err: CLIError, exit_code: i32) -> InvalidOptionsError { + InvalidOptionsError { + issues: vec![err], + exit_code: exit_code, + } + } + + pub fn new() -> InvalidOptionsError { + InvalidOptionsError { + issues: Vec::new(), + exit_code: 1, + } + } +} + +pub fn assure_config_dir_exists(dir: &str) -> Result { + let trdir = dir.trim(); + if trdir.len() == 0 { + return Err(CLIError::Configuration(ConfigurationError::DirectoryUnset)) + } + + let expanded_config_dir = + if trdir.as_bytes()[0] == b'~' { + match env::var("HOME").ok().or(env::var("UserProfile").ok()) { + None => return Err(CLIError::Configuration(ConfigurationError::HomeExpansionFailed(trdir.to_string()))), + Some(mut user) => { + user.push_str(&trdir[1..]); + user + } + } + } else { + trdir.to_string() + }; + + if let Err(err) = fs::create_dir(&expanded_config_dir) { + if err.kind() != io::ErrorKind::AlreadyExists { + return Err(CLIError::Configuration( + ConfigurationError::DirectoryCreationFailed((expanded_config_dir, err)))) + } + } + + Ok(expanded_config_dir) +} + +pub fn application_secret_from_directory(dir: &str, + secret_basename: &str, + json_console_secret: &str) + -> Result { + let secret_path = Path::new(dir).join(secret_basename); + let secret_str = || secret_path.as_path().to_str().unwrap().to_string(); + let secret_io_error = |io_err: io::Error| { + Err(CLIError::Configuration(ConfigurationError::IOError( + (secret_str(), io_err) + ))) + }; + + for _ in 0..2 { + match fs::File::open(&secret_path) { + Err(mut err) => { + if err.kind() == io::ErrorKind::NotFound { + // Write our built-in one - user may adjust the written file at will + + err = match fs::OpenOptions::new().create(true).write(true).open(&secret_path) { + Err(cfe) => cfe, + Ok(mut f) => { + // Assure we convert 'ugly' json string into pretty one + let console_secret: ConsoleApplicationSecret + = json::from_str(json_console_secret).unwrap(); + match json::to_writer_pretty(&mut f, &console_secret) { + Err(serde_err) => match serde_err { + json::Error::IoError(err) => err, + _ => panic!("Unexpected serde error: {:#?}", serde_err) + }, + Ok(_) => continue, + } + } + }; + // fall through to IO error handling + } + return secret_io_error(err) + }, + Ok(mut f) => { + match json::de::from_reader::<_, ConsoleApplicationSecret>(f) { + Err(json::Error::IoError(err)) => + return secret_io_error(err), + Err(json_err) => + return Err(CLIError::Configuration( + ConfigurationError::Secret( + ApplicationSecretError::DecoderError( + (secret_str(), json_err) + )))), + Ok(console_secret) => + match console_secret.installed { + Some(secret) => return Ok(secret), + None => return Err( + CLIError::Configuration( + ConfigurationError::Secret( + ApplicationSecretError::FormatError(secret_str()) + ))) + }, + } + } + } + } + unreachable!(); +} diff --git a/gen/clouddebugger2-cli/src/main.rs b/gen/clouddebugger2-cli/src/main.rs new file mode 100644 index 0000000000..be3d780c88 --- /dev/null +++ b/gen/clouddebugger2-cli/src/main.rs @@ -0,0 +1,1065 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/cli/main.rs.mako' +// DO NOT EDIT ! +#![allow(unused_variables, unused_imports, dead_code, unused_mut)] + +#[macro_use] +extern crate clap; +extern crate yup_oauth2 as oauth2; +extern crate yup_hyper_mock as mock; +extern crate serde; +extern crate serde_json; +extern crate hyper; +extern crate mime; +extern crate strsim; +extern crate google_clouddebugger2 as api; + +use std::env; +use std::io::{self, Write}; +use clap::{App, SubCommand, Arg}; + +mod cmn; + +use cmn::{InvalidOptionsError, CLIError, JsonTokenStorage, arg_from_str, writer_from_opts, parse_kv_arg, + input_file_from_opts, input_mime_from_opts, FieldCursor, FieldError, CallType, UploadProtocol, + calltype_from_str, remove_json_null_values, ComplexType, JsonType, JsonTypeInfo}; + +use std::default::Default; +use std::str::FromStr; + +use oauth2::{Authenticator, DefaultAuthenticatorDelegate}; +use serde_json as json; +use clap::ArgMatches; + +enum DoitError { + IoError(String, io::Error), + ApiError(api::Error), +} + +struct Engine<'n, 'a> { + opt: ArgMatches<'n, 'a>, + hub: api::Clouddebugger>, + gp: Vec<&'static str>, + gpm: Vec<(&'static str, &'static str)>, +} + + +impl<'n, 'a> Engine<'n, 'a> { + fn _controller_debuggees_breakpoints_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.controller().debuggees_breakpoints_list(opt.value_of("debuggee-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "wait-token" => { + call = call.wait_token(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["wait-token"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _controller_debuggees_breakpoints_update(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "breakpoint.status.is-error" => Some(("breakpoint.status.isError", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "breakpoint.status.refers-to" => Some(("breakpoint.status.refersTo", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "breakpoint.status.description.parameters" => Some(("breakpoint.status.description.parameters", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "breakpoint.status.description.format" => Some(("breakpoint.status.description.format", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "breakpoint.user-email" => Some(("breakpoint.userEmail", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "breakpoint.log-level" => Some(("breakpoint.logLevel", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "breakpoint.log-message-format" => Some(("breakpoint.logMessageFormat", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "breakpoint.create-time" => Some(("breakpoint.createTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "breakpoint.location.path" => Some(("breakpoint.location.path", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "breakpoint.location.line" => Some(("breakpoint.location.line", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "breakpoint.final-time" => Some(("breakpoint.finalTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "breakpoint.action" => Some(("breakpoint.action", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "breakpoint.expressions" => Some(("breakpoint.expressions", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "breakpoint.is-final-state" => Some(("breakpoint.isFinalState", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "breakpoint.id" => Some(("breakpoint.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "breakpoint.condition" => Some(("breakpoint.condition", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["action", "breakpoint", "condition", "create-time", "description", "expressions", "final-time", "format", "id", "is-error", "is-final-state", "line", "location", "log-level", "log-message-format", "parameters", "path", "refers-to", "status", "user-email"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::UpdateActiveBreakpointRequest = json::value::from_value(object).unwrap(); + let mut call = self.hub.controller().debuggees_breakpoints_update(request, opt.value_of("debuggee-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _controller_debuggees_register(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "debuggee.status.is-error" => Some(("debuggee.status.isError", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "debuggee.status.refers-to" => Some(("debuggee.status.refersTo", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "debuggee.status.description.parameters" => Some(("debuggee.status.description.parameters", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "debuggee.status.description.format" => Some(("debuggee.status.description.format", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "debuggee.description" => Some(("debuggee.description", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "debuggee.is-disabled" => Some(("debuggee.isDisabled", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "debuggee.labels" => Some(("debuggee.labels", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Map })), + "debuggee.uniquifier" => Some(("debuggee.uniquifier", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "debuggee.project" => Some(("debuggee.project", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "debuggee.agent-version" => Some(("debuggee.agentVersion", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "debuggee.is-inactive" => Some(("debuggee.isInactive", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "debuggee.id" => Some(("debuggee.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["agent-version", "debuggee", "description", "format", "id", "is-disabled", "is-error", "is-inactive", "labels", "parameters", "project", "refers-to", "status", "uniquifier"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::RegisterDebuggeeRequest = json::value::from_value(object).unwrap(); + let mut call = self.hub.controller().debuggees_register(request); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _debugger_debuggees_breakpoints_delete(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.debugger().debuggees_breakpoints_delete(opt.value_of("debuggee-id").unwrap_or(""), opt.value_of("breakpoint-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _debugger_debuggees_breakpoints_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.debugger().debuggees_breakpoints_get(opt.value_of("debuggee-id").unwrap_or(""), opt.value_of("breakpoint-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _debugger_debuggees_breakpoints_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.debugger().debuggees_breakpoints_list(opt.value_of("debuggee-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "wait-token" => { + call = call.wait_token(value.unwrap_or("")); + }, + "strip-results" => { + call = call.strip_results(arg_from_str(value.unwrap_or("false"), err, "strip-results", "boolean")); + }, + "include-inactive" => { + call = call.include_inactive(arg_from_str(value.unwrap_or("false"), err, "include-inactive", "boolean")); + }, + "include-all-users" => { + call = call.include_all_users(arg_from_str(value.unwrap_or("false"), err, "include-all-users", "boolean")); + }, + "action-value" => { + call = call.action_value(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["strip-results", "include-inactive", "action-value", "wait-token", "include-all-users"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _debugger_debuggees_breakpoints_set(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "status.is-error" => Some(("status.isError", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "status.refers-to" => Some(("status.refersTo", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "status.description.parameters" => Some(("status.description.parameters", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "status.description.format" => Some(("status.description.format", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "user-email" => Some(("userEmail", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "log-level" => Some(("logLevel", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "log-message-format" => Some(("logMessageFormat", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "create-time" => Some(("createTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "location.path" => Some(("location.path", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "location.line" => Some(("location.line", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "final-time" => Some(("finalTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "action" => Some(("action", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "expressions" => Some(("expressions", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "is-final-state" => Some(("isFinalState", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "condition" => Some(("condition", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["action", "condition", "create-time", "description", "expressions", "final-time", "format", "id", "is-error", "is-final-state", "line", "location", "log-level", "log-message-format", "parameters", "path", "refers-to", "status", "user-email"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::Breakpoint = json::value::from_value(object).unwrap(); + let mut call = self.hub.debugger().debuggees_breakpoints_set(request, opt.value_of("debuggee-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _debugger_debuggees_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.debugger().debuggees_list(); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "project" => { + call = call.project(value.unwrap_or("")); + }, + "include-inactive" => { + call = call.include_inactive(arg_from_str(value.unwrap_or("false"), err, "include-inactive", "boolean")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["project", "include-inactive"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _doit(&self, dry_run: bool) -> Result, Option> { + let mut err = InvalidOptionsError::new(); + let mut call_result: Result<(), DoitError> = Ok(()); + let mut err_opt: Option = None; + match self.opt.subcommand() { + ("controller", Some(opt)) => { + match opt.subcommand() { + ("debuggees-breakpoints-list", Some(opt)) => { + call_result = self._controller_debuggees_breakpoints_list(opt, dry_run, &mut err); + }, + ("debuggees-breakpoints-update", Some(opt)) => { + call_result = self._controller_debuggees_breakpoints_update(opt, dry_run, &mut err); + }, + ("debuggees-register", Some(opt)) => { + call_result = self._controller_debuggees_register(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("controller".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("debugger", Some(opt)) => { + match opt.subcommand() { + ("debuggees-breakpoints-delete", Some(opt)) => { + call_result = self._debugger_debuggees_breakpoints_delete(opt, dry_run, &mut err); + }, + ("debuggees-breakpoints-get", Some(opt)) => { + call_result = self._debugger_debuggees_breakpoints_get(opt, dry_run, &mut err); + }, + ("debuggees-breakpoints-list", Some(opt)) => { + call_result = self._debugger_debuggees_breakpoints_list(opt, dry_run, &mut err); + }, + ("debuggees-breakpoints-set", Some(opt)) => { + call_result = self._debugger_debuggees_breakpoints_set(opt, dry_run, &mut err); + }, + ("debuggees-list", Some(opt)) => { + call_result = self._debugger_debuggees_list(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("debugger".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + _ => { + err.issues.push(CLIError::MissingCommandError); + writeln!(io::stderr(), "{}\n", self.opt.usage()).ok(); + } + } + + if dry_run { + if err.issues.len() > 0 { + err_opt = Some(err); + } + Err(err_opt) + } else { + Ok(call_result) + } + } + + // Please note that this call will fail if any part of the opt can't be handled + fn new(opt: ArgMatches<'a, 'n>) -> Result, InvalidOptionsError> { + let (config_dir, secret) = { + let config_dir = match cmn::assure_config_dir_exists(opt.value_of("folder").unwrap_or("~/.google-service-cli")) { + Err(e) => return Err(InvalidOptionsError::single(e, 3)), + Ok(p) => p, + }; + + match cmn::application_secret_from_directory(&config_dir, "clouddebugger2-secret.json", + "{\"installed\":{\"auth_uri\":\"https://accounts.google.com/o/oauth2/auth\",\"client_secret\":\"hCsslbCUyfehWMmbkG8vTYxG\",\"token_uri\":\"https://accounts.google.com/o/oauth2/token\",\"client_email\":\"\",\"redirect_uris\":[\"urn:ietf:wg:oauth:2.0:oob\",\"oob\"],\"client_x509_cert_url\":\"\",\"client_id\":\"620010449518-9ngf7o4dhs0dka470npqvor6dc5lqb9b.apps.googleusercontent.com\",\"auth_provider_x509_cert_url\":\"https://www.googleapis.com/oauth2/v1/certs\"}}") { + Ok(secret) => (config_dir, secret), + Err(e) => return Err(InvalidOptionsError::single(e, 4)) + } + }; + + let auth = Authenticator::new( &secret, DefaultAuthenticatorDelegate, + if opt.is_present("debug-auth") { + hyper::Client::with_connector(mock::TeeConnector { + connector: hyper::net::HttpsConnector::::default() + }) + } else { + hyper::Client::new() + }, + JsonTokenStorage { + program_name: "clouddebugger2", + db_dir: config_dir.clone(), + }, None); + + let client = + if opt.is_present("debug") { + hyper::Client::with_connector(mock::TeeConnector { + connector: hyper::net::HttpsConnector::::default() + }) + } else { + hyper::Client::new() + }; + let engine = Engine { + opt: opt, + hub: api::Clouddebugger::new(client, auth), + gp: vec!["$-xgafv", "access-token", "alt", "bearer-token", "callback", "fields", "key", "oauth-token", "pp", "pretty-print", "quota-user", "upload-type", "upload-protocol"], + gpm: vec![ + ("$-xgafv", "$.xgafv"), + ("access-token", "access_token"), + ("bearer-token", "bearer_token"), + ("oauth-token", "oauth_token"), + ("pretty-print", "prettyPrint"), + ("quota-user", "quotaUser"), + ("upload-type", "uploadType"), + ("upload-protocol", "upload_protocol"), + ] + }; + + match engine._doit(true) { + Err(Some(err)) => Err(err), + Err(None) => Ok(engine), + Ok(_) => unreachable!(), + } + } + + fn doit(&self) -> Result<(), DoitError> { + match self._doit(false) { + Ok(res) => res, + Err(_) => unreachable!(), + } + } +} + +fn main() { + let mut exit_status = 0i32; + let arg_data = [ + ("controller", "methods: 'debuggees-breakpoints-list', 'debuggees-breakpoints-update' and 'debuggees-register'", vec![ + ("debuggees-breakpoints-list", + Some(r##"Returns the list of all active breakpoints for the specified debuggee. The breakpoint specification (location, condition, and expression fields) is semantically immutable, although the field values may change. For example, an agent may update the location line number to reflect the actual line the breakpoint was set to, but that doesn't change the breakpoint semantics. Thus, an agent does not need to check if a breakpoint has changed when it encounters the same breakpoint on a successive call. Moreover, an agent should remember breakpoints that are complete until the controller removes them from the active list to avoid setting those breakpoints again."##), + "Details at http://byron.github.io/google-apis-rs/google_clouddebugger2_cli/controller_debuggees-breakpoints-list", + vec![ + (Some(r##"debuggee-id"##), + None, + Some(r##"Identifies the debuggee."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("debuggees-breakpoints-update", + Some(r##"Updates the breakpoint state or mutable fields. The entire Breakpoint protobuf must be sent back to the controller. Updates to active breakpoint fields are only allowed if the new value does not change the breakpoint specification. Updates to the 'location', 'condition' and 'expression' fields should not alter the breakpoint semantics. They are restricted to changes such as canonicalizing a value or snapping the location to the correct line of code."##), + "Details at http://byron.github.io/google-apis-rs/google_clouddebugger2_cli/controller_debuggees-breakpoints-update", + vec![ + (Some(r##"debuggee-id"##), + None, + Some(r##"Identifies the debuggee being debugged."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"Breakpoint identifier, unique in the scope of the debuggee."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("debuggees-register", + Some(r##"Registers the debuggee with the controller. All agents should call this API with the same request content to get back the same stable 'debuggee_id'. Agents should call this API again whenever ListActiveBreakpoints or UpdateActiveBreakpoint return the error google.rpc.Code.NOT_FOUND. It allows the server to disable the agent or recover from any registration loss. If the debuggee is disabled server, the response will have is_disabled' set to true."##), + "Details at http://byron.github.io/google-apis-rs/google_clouddebugger2_cli/controller_debuggees-register", + vec![ + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("debugger", "methods: 'debuggees-breakpoints-delete', 'debuggees-breakpoints-get', 'debuggees-breakpoints-list', 'debuggees-breakpoints-set' and 'debuggees-list'", vec![ + ("debuggees-breakpoints-delete", + Some(r##"Deletes the breakpoint from the debuggee."##), + "Details at http://byron.github.io/google-apis-rs/google_clouddebugger2_cli/debugger_debuggees-breakpoints-delete", + vec![ + (Some(r##"debuggee-id"##), + None, + Some(r##"The debuggee id to delete the breakpoint from."##), + Some(true), + Some(false)), + + (Some(r##"breakpoint-id"##), + None, + Some(r##"The breakpoint to delete."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("debuggees-breakpoints-get", + Some(r##"Gets breakpoint information."##), + "Details at http://byron.github.io/google-apis-rs/google_clouddebugger2_cli/debugger_debuggees-breakpoints-get", + vec![ + (Some(r##"debuggee-id"##), + None, + Some(r##"The debuggee id to get the breakpoint from."##), + Some(true), + Some(false)), + + (Some(r##"breakpoint-id"##), + None, + Some(r##"The breakpoint to get."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("debuggees-breakpoints-list", + Some(r##"Lists all breakpoints of the debuggee that the user has access to."##), + "Details at http://byron.github.io/google-apis-rs/google_clouddebugger2_cli/debugger_debuggees-breakpoints-list", + vec![ + (Some(r##"debuggee-id"##), + None, + Some(r##"The debuggee id to list breakpoint from."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("debuggees-breakpoints-set", + Some(r##"Sets the breakpoint to the debuggee."##), + "Details at http://byron.github.io/google-apis-rs/google_clouddebugger2_cli/debugger_debuggees-breakpoints-set", + vec![ + (Some(r##"debuggee-id"##), + None, + Some(r##"The debuggee id to set the breakpoint to."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("debuggees-list", + Some(r##"Lists all the debuggees that the user can set breakpoints to."##), + "Details at http://byron.github.io/google-apis-rs/google_clouddebugger2_cli/debugger_debuggees-list", + vec![ + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ]; + + let mut app = App::new("clouddebugger2") + .author("Sebastian Thiel ") + .version("0.3.2+20150725") + .about("Lets you examine the stack and variables of your running application without stopping or slowing it down.") + .after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_clouddebugger2_cli") + .arg(Arg::with_name("url") + .long("scope") + .help("Specify the authentication a method should be executed in. Each scope requires the user to grant this application permission to use it.If unset, it defaults to the shortest scope url for a particular method.") + .multiple(true) + .takes_value(true)) + .arg(Arg::with_name("folder") + .long("config-dir") + .help("A directory into which we will store our persistent data. Defaults to a user-writable directory that we will create during the first invocation.[default: ~/.google-service-cli") + .multiple(false) + .takes_value(true)) + .arg(Arg::with_name("debug") + .long("debug") + .help("Output all server communication to standard error. `tx` and `rx` are placed into the same stream.") + .multiple(false) + .takes_value(false)) + .arg(Arg::with_name("debug-auth") + .long("debug-auth") + .help("Output all communication related to authentication to standard error. `tx` and `rx` are placed into the same stream.") + .multiple(false) + .takes_value(false)); + + for &(main_command_name, ref about, ref subcommands) in arg_data.iter() { + let mut mcmd = SubCommand::with_name(main_command_name).about(about); + + for &(sub_command_name, ref desc, url_info, ref args) in subcommands { + let mut scmd = SubCommand::with_name(sub_command_name); + if let &Some(desc) = desc { + scmd = scmd.about(desc); + } + scmd = scmd.after_help(url_info); + + for &(ref arg_name, ref flag, ref desc, ref required, ref multi) in args { + let arg_name_str = + match (arg_name, flag) { + (&Some(an), _ ) => an, + (_ , &Some(f)) => f, + _ => unreachable!(), + }; + let mut arg = Arg::with_name(arg_name_str) + .empty_values(false); + if let &Some(short_flag) = flag { + arg = arg.short(short_flag); + } + if let &Some(desc) = desc { + arg = arg.help(desc); + } + if arg_name.is_some() && flag.is_some() { + arg = arg.takes_value(true); + } + if let &Some(required) = required { + arg = arg.required(required); + } + if let &Some(multi) = multi { + arg = arg.multiple(multi); + } + scmd = scmd.arg(arg); + } + mcmd = mcmd.subcommand(scmd); + } + app = app.subcommand(mcmd); + } + + let matches = app.get_matches(); + + let debug = matches.is_present("debug"); + match Engine::new(matches) { + Err(err) => { + exit_status = err.exit_code; + writeln!(io::stderr(), "{}", err).ok(); + }, + Ok(engine) => { + if let Err(doit_err) = engine.doit() { + exit_status = 1; + match doit_err { + DoitError::IoError(path, err) => { + writeln!(io::stderr(), "Failed to open output file '{}': {}", path, err).ok(); + }, + DoitError::ApiError(err) => { + if debug { + writeln!(io::stderr(), "{:#?}", err).ok(); + } else { + writeln!(io::stderr(), "{}", err).ok(); + } + } + } + } + } + } + + std::process::exit(exit_status); +} \ No newline at end of file diff --git a/gen/clouddebugger2/Cargo.toml b/gen/clouddebugger2/Cargo.toml new file mode 100644 index 0000000000..94e3d71676 --- /dev/null +++ b/gen/clouddebugger2/Cargo.toml @@ -0,0 +1,29 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-clouddebugger2" +version = "0.1.9+20150725" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with clouddebugger (protocol v2)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/clouddebugger2" +homepage = "https://cloud.google.com/tools/cloud-debugger" +documentation = "http://byron.github.io/google-apis-rs/google_clouddebugger2" +license = "MIT" +keywords = ["clouddebugger", "google", "protocol", "web", "api"] +build = "src/build.rs" + + +[dependencies] +hyper = ">= 0.6.8" +mime = "0.1.0" +serde = ">= 0.6.0" +serde_json = ">= 0.6.0" +yup-oauth2 = "*" +url = "*" + +[build-dependencies] +syntex = { version = "*" } +serde_codegen = { version = "*" } + diff --git a/gen/clouddebugger2/LICENSE.md b/gen/clouddebugger2/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/clouddebugger2/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/clouddebugger2/README.md b/gen/clouddebugger2/README.md new file mode 100644 index 0000000000..b302a3afe7 --- /dev/null +++ b/gen/clouddebugger2/README.md @@ -0,0 +1,181 @@ + +The `google-clouddebugger2` library allows access to all features of the *Google clouddebugger* service. + +This documentation was generated from *clouddebugger* crate version *0.1.9+20150725*, where *20150725* is the exact revision of the *clouddebugger:v2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. + +Everything else about the *clouddebugger* *v2* API can be found at the +[official documentation site](https://cloud.google.com/tools/cloud-debugger). +# Features + +Handle the following *Resources* with ease from the central [hub](http://byron.github.io/google-apis-rs/google_clouddebugger2/struct.Clouddebugger.html) ... + +* controller + * [*debuggees breakpoints list*](http://byron.github.io/google-apis-rs/google_clouddebugger2/struct.ControllerDebuggeeBreakpointListCall.html), [*debuggees breakpoints update*](http://byron.github.io/google-apis-rs/google_clouddebugger2/struct.ControllerDebuggeeBreakpointUpdateCall.html) and [*debuggees register*](http://byron.github.io/google-apis-rs/google_clouddebugger2/struct.ControllerDebuggeeRegisterCall.html) +* debugger + * [*debuggees breakpoints delete*](http://byron.github.io/google-apis-rs/google_clouddebugger2/struct.DebuggerDebuggeeBreakpointDeleteCall.html), [*debuggees breakpoints get*](http://byron.github.io/google-apis-rs/google_clouddebugger2/struct.DebuggerDebuggeeBreakpointGetCall.html), [*debuggees breakpoints list*](http://byron.github.io/google-apis-rs/google_clouddebugger2/struct.DebuggerDebuggeeBreakpointListCall.html), [*debuggees breakpoints set*](http://byron.github.io/google-apis-rs/google_clouddebugger2/struct.DebuggerDebuggeeBreakpointSetCall.html) and [*debuggees list*](http://byron.github.io/google-apis-rs/google_clouddebugger2/struct.DebuggerDebuggeeListCall.html) + + + + +# Structure of this Library + +The API is structured into the following primary items: + +* **[Hub](http://byron.github.io/google-apis-rs/google_clouddebugger2/struct.Clouddebugger.html)** + * a central object to maintain state and allow accessing all *Activities* + * creates [*Method Builders*](http://byron.github.io/google-apis-rs/google_clouddebugger2/trait.MethodsBuilder.html) which in turn + allow access to individual [*Call Builders*](http://byron.github.io/google-apis-rs/google_clouddebugger2/trait.CallBuilder.html) +* **[Resources](http://byron.github.io/google-apis-rs/google_clouddebugger2/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_clouddebugger2/trait.Part.html)** + * a collection of properties + * never directly used in *Activities* +* **[Activities](http://byron.github.io/google-apis-rs/google_clouddebugger2/trait.CallBuilder.html)** + * operations to apply to *Resources* + +All *structures* are marked with applicable traits to further categorize them and ease browsing. + +Generally speaking, you can invoke *Activities* like this: + +```Rust,ignore +let r = hub.resource().activity(...).doit() +``` + +Or specifically ... + +```ignore +let r = hub.debugger().debuggees_breakpoints_set(...).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-clouddebugger2 = "*" +``` + +## A complete example + +```Rust +extern crate hyper; +extern crate yup_oauth2 as oauth2; +extern crate google_clouddebugger2 as clouddebugger2; +use clouddebugger2::Breakpoint; +use clouddebugger2::{Result, Error}; +use std::default::Default; +use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +use clouddebugger2::Clouddebugger; + +// 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 = Clouddebugger::new(hyper::Client::new(), auth); +// As the method needs a request, you would usually fill it with the desired information +// into the respective structure. Some of the parts shown here might not be applicable ! +// Values shown here are possibly random and not representative ! +let mut req = Breakpoint::default(); + +// You can configure optional parameters by calling the respective setters at will, and +// execute the final call using `doit()`. +// Values shown here are possibly random and not representative ! +let result = hub.debugger().debuggees_breakpoints_set(req, "debuggeeId") + .doit(); + +match result { + Err(e) => match e { + // The Error enum provides details about what exactly happened. + // You can also just use its `Debug`, `Display` or `Error` traits + Error::HttpError(_) + |Error::MissingAPIKey + |Error::MissingToken(_) + |Error::Cancelled + |Error::UploadSizeLimitExceeded(_, _) + |Error::Failure(_) + |Error::BadRequest(_) + |Error::FieldClash(_) + |Error::JsonDecodeError(_, _) => println!("{}", e), + }, + Ok(res) => println!("Success: {:?}", res), +} + +``` +## Handling Errors + +All errors produced by the system are provided either as [Result](http://byron.github.io/google-apis-rs/google_clouddebugger2/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_clouddebugger2/trait.Delegate.html), or the [Authenticator Delegate](http://byron.github.io/google-apis-rs/google_clouddebugger2/../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 Downloads +If a method supports downloads, the response body, which is part of the [Result](http://byron.github.io/google-apis-rs/google_clouddebugger2/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_clouddebugger2/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_clouddebugger2/trait.Delegate.html) to the +[Method Builder](http://byron.github.io/google-apis-rs/google_clouddebugger2/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_clouddebugger2/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_clouddebugger2/trait.RequestValue.html) and +[decodable](http://byron.github.io/google-apis-rs/google_clouddebugger2/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_clouddebugger2/trait.Part.html) which are identifiable 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_clouddebugger2/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_clouddebugger2/trait.RequestValue.html) are moved + +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 **clouddebugger2** 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/clouddebugger2/src/build.rs b/gen/clouddebugger2/src/build.rs new file mode 100644 index 0000000000..e5a115bd40 --- /dev/null +++ b/gen/clouddebugger2/src/build.rs @@ -0,0 +1,16 @@ +extern crate syntex; +extern crate serde_codegen; + +use std::env; +use std::path::Path; + +pub fn main() { + let out_dir = env::var_os("OUT_DIR").unwrap(); + + let src = Path::new("src/lib.rs.in"); + let dst = Path::new(&out_dir).join("lib.rs"); + + let mut registry = syntex::Registry::new(); + serde_codegen::register(&mut registry); + registry.expand("google-clouddebugger2", &src, &dst).unwrap(); +} diff --git a/gen/clouddebugger2/src/cmn.rs b/gen/clouddebugger2/src/cmn.rs new file mode 100644 index 0000000000..0e31353ba3 --- /dev/null +++ b/gen/clouddebugger2/src/cmn.rs @@ -0,0 +1,762 @@ +// COPY OF 'src/rust/api/cmn.rs' +// DO NOT EDIT +use std::io::{self, Read, Seek, Cursor, Write, SeekFrom}; +use std; +use std::fmt::{self, Display}; +use std::str::FromStr; +use std::error; +use std::thread::sleep_ms; + +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::h1::LINE_ENDING; +use hyper::method::Method; +use hyper::status::StatusCode; + +use serde_json as json; + +/// 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 {} + +/// Identifies types for building methods of a particular resource type +pub trait MethodsBuilder {} + +/// Identifies types which represent builders for a particular resource method +pub trait CallBuilder {} + +/// Identifies types which can be inserted and deleted. +/// Types with this trait are most commonly used by clients of this API. +pub trait Resource {} + +/// Identifies types which are used in API responses. +pub trait ResponseResult {} + +/// Identifies types which are used in API requests. +pub trait RequestValue {} + +/// Identifies types which are not actually used by the API +/// This might be a bug within the google API schema. +pub trait UnusedType {} + +/// Identifies types which are only used as part of other types, which +/// usually are carrying the `Resource` trait. +pub trait Part {} + +/// 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 {} + +/// 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 +} + +/// A utility to represent detailed errors we might see in case there are BadRequests. +/// The latter happen if the sent parameters or request structures are unsound +#[derive(Deserialize, Serialize, Debug)] +pub struct ErrorResponse { + error: ServerError, +} + +#[derive(Deserialize, Serialize, Debug)] +pub struct ServerError { + errors: Vec, + code: u16, + message: String, +} + +#[derive(Deserialize, Serialize, Debug)] +pub struct ServerMessage { + domain: String, + reason: String, + message: String, + #[serde(rename="locationType")] + location_type: Option, + location: 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 successful. That way, the delegate 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. + /// + /// If you choose to retry after a duration, the duration should be chosen using the + /// [exponential backoff algorithm](http://en.wikipedia.org/wiki/Exponential_backoff). + /// + /// Return retry information. + fn http_error(&mut self, &hyper::Error) -> 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 it as a general information about the + /// impending failure. + /// The given Error provides information about why the token couldn't be acquired in the + /// first place + fn token(&mut self, err: &error::Error) -> Option { + let _ = err; + 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/canceled, 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()`. + /// It will also be called with None after a successful upload, which allows the delegate + /// to forget the URL. That way, we will not attempt to resume an upload that has already + /// finished. + fn store_upload_url(&mut self, url: Option<&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: &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. + /// + /// If you choose to retry after a duration, the duration should be chosen using the + /// [exponential backoff algorithm](http://en.wikipedia.org/wiki/Exponential_backoff). + fn http_failure(&mut self, _: &hyper::client::Response, Option, _: 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 {} + + +#[derive(Debug)] +pub enum Error { + /// The http connection failed + HttpError(hyper::Error), + + /// 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), + + /// Represents information about a request that was not understood by the server. + /// Details are included. + BadRequest(ErrorResponse), + + /// 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(Box), + + /// 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(String, json::Error), + + /// Indicates an HTTP repsonse with a non-success status code + Failure(hyper::client::Response), +} + + +impl Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + Error::HttpError(ref err) => err.fmt(f), + Error::UploadSizeLimitExceeded(ref resource_size, ref max_size) => + writeln!(f, "The media size {} exceeds the maximum allowed upload size of {}" + , resource_size, max_size), + Error::MissingAPIKey => { + (writeln!(f, "The application's API key was not found in the configuration")).ok(); + writeln!(f, "It is used as there are no Scopes defined for this method.") + }, + Error::BadRequest(ref err) => { + try!(writeln!(f, "Bad Requst ({}): {}", err.error.code, err.error.message)); + for err in err.error.errors.iter() { + try!(writeln!(f, " {}: {}, {}{}", + err.domain, + err.message, + err.reason, + match &err.location { + &Some(ref loc) => format!("@{}", loc), + &None => String::new(), + })); + } + Ok(()) + }, + Error::MissingToken(ref err) => + writeln!(f, "Token retrieval failed with error: {}", err), + Error::Cancelled => + writeln!(f, "Operation cancelled by delegate"), + Error::FieldClash(field) => + writeln!(f, "The custom parameter '{}' is already provided natively by the CallBuilder.", field), + Error::JsonDecodeError(ref json_str, ref err) + => writeln!(f, "{}: {}", err, json_str), + Error::Failure(ref response) => + writeln!(f, "Http status indicates failure: {:?}", response), + } + } +} + +impl error::Error for Error { + fn description(&self) -> &str { + match *self { + Error::HttpError(ref err) => err.description(), + Error::JsonDecodeError(_, ref err) => err.description(), + _ => "NO DESCRIPTION POSSIBLE - use `Display.fmt()` instead" + } + } + + fn cause(&self) -> Option<&error::Error> { + match *self { + Error::HttpError(ref err) => err.cause(), + Error::JsonDecodeError(_, ref err) => err.cause(), + _ => None + } + } +} + +/// A universal result type used as return for all calls. +pub type Result = std::result::Result; + +/// 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 + 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 following macro invocation needs to be expanded, as `include!` +// doens't support external macros +// header!{ +// #[doc="The `X-Upload-Content-Type` header."] +// (XUploadContentType, "X-Upload-Content-Type") => [Mime] + +// xupload_content_type { +// test_header!( +// test1, +// vec![b"text/plain"], +// Some(HeaderField( +// vec![Mime(TopLevel::Text, SubLevel::Plain, Vec::new())] +// ))); + +// } +// } + +/// The `X-Upload-Content-Type` header. +/// +/// Generated via rustc --pretty expanded -Z unstable-options, and manually +/// processed to be more readable. +#[derive(PartialEq, Debug, Clone)] +pub struct XUploadContentType(pub Mime); + +impl ::std::ops::Deref for XUploadContentType { + type Target = Mime; + fn deref<'a>(&'a self) -> &'a Mime { &self.0 } +} +impl ::std::ops::DerefMut for XUploadContentType { + fn deref_mut<'a>(&'a mut self) -> &'a mut Mime { &mut self.0 } +} +impl Header for XUploadContentType { + fn header_name() -> &'static str { "X-Upload-Content-Type" } + fn parse_header(raw: &[Vec]) -> hyper::error::Result { + hyper::header::parsing::from_one_raw_str(raw).map(XUploadContentType) + } +} +impl HeaderFormat for XUploadContentType { + fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { + Display::fmt(&**self, f) + } +} +impl Display for XUploadContentType { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Display::fmt(&**self, f) + } +} + +#[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]) -> hyper::error::Result { + Err(hyper::error::Error::Method) + } +} + + +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]) -> hyper::error::Result { + if raw.len() > 0 { + let v = &raw[0]; + if let Ok(s) = std::str::from_utf8(v) { + const PREFIX: &'static str = "bytes "; + if s.starts_with(PREFIX) { + if let Ok(c) = ::from_str(&s[PREFIX.len()..]) { + return Ok(RangeResponseHeader(c)) + } + } + } + } + Err(hyper::error::Error::Method) + } +} + +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, 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, A> ResumableUploadHelper<'a, A> + where A: oauth2::GetToken { + + fn query_transfer_status(&mut self) -> std::result::Result> { + 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, None) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + return Err(Ok(r)) + } + }; + return Ok(h.0.last) + } + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + return Err(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() { + Ok(s) => s, + Err(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 + }; + + self.reader.seek(SeekFrom::Start(start)).unwrap(); + loop { + let request_size = match self.content_length - start { + rs if rs > chunk_size => chunk_size, + rs => rs + }; + + 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 + } + // workaround https://github.com/rust-lang/rust/issues/22252 + let res = 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(); + match res { + 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, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + } + return Some(Ok(res)) + }, + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + return Some(Err(err)) + } + } + } + } +} + +// Copy of src/rust/cli/cmn.rs +// TODO(ST): Allow sharing common code between program types +pub fn remove_json_null_values(value: &mut json::value::Value) { + match *value { + json::value::Value::Object(ref mut map) => { + let mut for_removal = Vec::new(); + + for (key, mut value) in map.iter_mut() { + if value.is_null() { + for_removal.push(key.clone()); + } else { + remove_json_null_values(&mut value); + } + } + + for key in &for_removal { + map.remove(key); + } + } + _ => {} + } +} diff --git a/gen/clouddebugger2/src/lib.rs b/gen/clouddebugger2/src/lib.rs new file mode 100644 index 0000000000..76886d7249 --- /dev/null +++ b/gen/clouddebugger2/src/lib.rs @@ -0,0 +1,185 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/api/lib.rs.mako' +// DO NOT EDIT ! + +//! This documentation was generated from *clouddebugger* crate version *0.1.9+20150725*, where *20150725* is the exact revision of the *clouddebugger:v2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +//! +//! Everything else about the *clouddebugger* *v2* API can be found at the +//! [official documentation site](https://cloud.google.com/tools/cloud-debugger). +//! The original source code is [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/clouddebugger2). +//! # Features +//! +//! Handle the following *Resources* with ease from the central [hub](struct.Clouddebugger.html) ... +//! +//! * controller +//! * [*debuggees breakpoints list*](struct.ControllerDebuggeeBreakpointListCall.html), [*debuggees breakpoints update*](struct.ControllerDebuggeeBreakpointUpdateCall.html) and [*debuggees register*](struct.ControllerDebuggeeRegisterCall.html) +//! * debugger +//! * [*debuggees breakpoints delete*](struct.DebuggerDebuggeeBreakpointDeleteCall.html), [*debuggees breakpoints get*](struct.DebuggerDebuggeeBreakpointGetCall.html), [*debuggees breakpoints list*](struct.DebuggerDebuggeeBreakpointListCall.html), [*debuggees breakpoints set*](struct.DebuggerDebuggeeBreakpointSetCall.html) and [*debuggees list*](struct.DebuggerDebuggeeListCall.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.Clouddebugger.html)** +//! * a central object to maintain state and allow accessing all *Activities* +//! * creates [*Method Builders*](trait.MethodsBuilder.html) which in turn +//! allow access to individual [*Call Builders*](trait.CallBuilder.html) +//! * **[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* +//! +//! All *structures* are marked with applicable traits to further categorize them and ease browsing. +//! +//! Generally speaking, you can invoke *Activities* like this: +//! +//! ```Rust,ignore +//! let r = hub.resource().activity(...).doit() +//! ``` +//! +//! Or specifically ... +//! +//! ```ignore +//! let r = hub.debugger().debuggees_breakpoints_set(...).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-clouddebugger2 = "*" +//! ``` +//! +//! ## A complete example +//! +//! ```test_harness,no_run +//! extern crate hyper; +//! extern crate yup_oauth2 as oauth2; +//! extern crate google_clouddebugger2 as clouddebugger2; +//! use clouddebugger2::Breakpoint; +//! use clouddebugger2::{Result, Error}; +//! # #[test] fn egal() { +//! use std::default::Default; +//! use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +//! use clouddebugger2::Clouddebugger; +//! +//! // 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 = Clouddebugger::new(hyper::Client::new(), auth); +//! // As the method needs a request, you would usually fill it with the desired information +//! // into the respective structure. Some of the parts shown here might not be applicable ! +//! // Values shown here are possibly random and not representative ! +//! let mut req = Breakpoint::default(); +//! +//! // You can configure optional parameters by calling the respective setters at will, and +//! // execute the final call using `doit()`. +//! // Values shown here are possibly random and not representative ! +//! let result = hub.debugger().debuggees_breakpoints_set(req, "debuggeeId") +//! .doit(); +//! +//! match result { +//! Err(e) => match e { +//! // The Error enum provides details about what exactly happened. +//! // You can also just use its `Debug`, `Display` or `Error` traits +//! Error::HttpError(_) +//! |Error::MissingAPIKey +//! |Error::MissingToken(_) +//! |Error::Cancelled +//! |Error::UploadSizeLimitExceeded(_, _) +//! |Error::Failure(_) +//! |Error::BadRequest(_) +//! |Error::FieldClash(_) +//! |Error::JsonDecodeError(_, _) => println!("{}", e), +//! }, +//! Ok(res) => println!("Success: {:?}", res), +//! } +//! # } +//! ``` +//! ## 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 Downloads +//! 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 identifiable 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 moved +//! +//! 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 +//! +//! + +// 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)] + +include!(concat!(env!("OUT_DIR"), "/lib.rs")); \ No newline at end of file diff --git a/gen/clouddebugger2/src/lib.rs.in b/gen/clouddebugger2/src/lib.rs.in new file mode 100644 index 0000000000..80c8b55f9f --- /dev/null +++ b/gen/clouddebugger2/src/lib.rs.in @@ -0,0 +1,3012 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/api/lib.rs.in.mako' +// DO NOT EDIT ! + +extern crate hyper; +extern crate serde; +extern crate serde_json; +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 serde_json as json; +use std::io; +use std::fs; +use std::thread::sleep_ms; + +pub use cmn::{MultiPartReader, ToParts, MethodInfo, Result, Error, CallBuilder, Hub, ReadSeek, Part, + ResponseResult, RequestValue, NestedType, Delegate, DefaultDelegate, MethodsBuilder, + Resource, ErrorResponse, remove_json_null_values}; + + +// ############## +// 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 cloud debugger + CloudDebugger, + + /// View and manage your data across Google Cloud Platform services + CloudPlatform, + + /// Manage active breakpoints in cloud debugger + CloudDebugletcontroller, +} + +impl AsRef for Scope { + fn as_ref(&self) -> &str { + match *self { + Scope::CloudDebugger => "https://www.googleapis.com/auth/cloud_debugger", + Scope::CloudPlatform => "https://www.googleapis.com/auth/cloud-platform", + Scope::CloudDebugletcontroller => "https://www.googleapis.com/auth/cloud_debugletcontroller", + } + } +} + +impl Default for Scope { + fn default() -> Scope { + Scope::CloudDebugger + } +} + + + +// ######## +// HUB ### +// ###### + +/// Central instance to access all Clouddebugger related resource activities +/// +/// # Examples +/// +/// Instantiate a new hub +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate yup_oauth2 as oauth2; +/// extern crate google_clouddebugger2 as clouddebugger2; +/// use clouddebugger2::Breakpoint; +/// use clouddebugger2::{Result, Error}; +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use clouddebugger2::Clouddebugger; +/// +/// // 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 = Clouddebugger::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req = Breakpoint::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.debugger().debuggees_breakpoints_set(req, "debuggeeId") +/// .doit(); +/// +/// match result { +/// Err(e) => match e { +/// // The Error enum provides details about what exactly happened. +/// // You can also just use its `Debug`, `Display` or `Error` traits +/// Error::HttpError(_) +/// |Error::MissingAPIKey +/// |Error::MissingToken(_) +/// |Error::Cancelled +/// |Error::UploadSizeLimitExceeded(_, _) +/// |Error::Failure(_) +/// |Error::BadRequest(_) +/// |Error::FieldClash(_) +/// |Error::JsonDecodeError(_, _) => println!("{}", e), +/// }, +/// Ok(res) => println!("Success: {:?}", res), +/// } +/// # } +/// ``` +pub struct Clouddebugger { + client: RefCell, + auth: RefCell, + _user_agent: String, +} + +impl<'a, C, A> Hub for Clouddebugger {} + +impl<'a, C, A> Clouddebugger + where C: BorrowMut, A: oauth2::GetToken { + + pub fn new(client: C, authenticator: A) -> Clouddebugger { + Clouddebugger { + client: RefCell::new(client), + auth: RefCell::new(authenticator), + _user_agent: "google-api-rust-client/0.1.9".to_string(), + } + } + + pub fn controller(&'a self) -> ControllerMethods<'a, C, A> { + ControllerMethods { hub: &self } + } + pub fn debugger(&'a self) -> DebuggerMethods<'a, C, A> { + DebuggerMethods { 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.9`. + /// + /// 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 response of listing breakpoints. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [debuggees breakpoints list debugger](struct.DebuggerDebuggeeBreakpointListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ListBreakpointsResponse { + /// A wait token that can be used in the next call to ListBreakpoints to block until the list of breakpoints has changes. + #[serde(rename="nextWaitToken")] + pub next_wait_token: Option, + /// List of all breakpoints with complete state. The fields 'id' and 'location' are guranteed to be set on each breakpoint. + pub breakpoints: Option>, +} + +impl ResponseResult for ListBreakpointsResponse {} + + +/// A CloudWorkspaceSourceContext denotes a workspace at a particular snapshot. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct CloudWorkspaceSourceContext { + /// The ID of the snapshot. An empty snapshot_id refers to the most recent snapshot. + #[serde(rename="snapshotId")] + pub snapshot_id: Option, + /// The ID of the workspace. + #[serde(rename="workspaceId")] + pub workspace_id: Option, +} + +impl Part for CloudWorkspaceSourceContext {} + + +/// Represents a stack frame context. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct StackFrame { + /// The unmangled function name at the call site. + pub function: Option, + /// The source location of the call site. + pub location: Option, + /// The set of local variables at the stack frame location. Note that this might not be populated for all stack frames. + pub locals: Option>, + /// The set of arguments passed to this function Note that this might not be populated for all stack frames. + pub arguments: Option>, +} + +impl Part for StackFrame {} + + +/// The response of listing debuggees. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [debuggees list debugger](struct.DebuggerDebuggeeListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ListDebuggeesResponse { + /// The list of debuggees accessible to the calling user. Note that the description field is the only human readable field that should be displayed to the user. The fields 'debuggee.id' and 'description' are guranteed to be set on each debuggee. + pub debuggees: Option>, +} + +impl ResponseResult for ListDebuggeesResponse {} + + +/// The request to register a debuggee. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [debuggees register controller](struct.ControllerDebuggeeRegisterCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct RegisterDebuggeeRequest { + /// The debuggee information to register. The fields 'project', 'uniquifier', 'description' and 'agent_version' of the debuggee must be set. + pub debuggee: Option, +} + +impl RequestValue for RegisterDebuggeeRequest {} + + +/// The response of updating an active breakpoint. The message is defined to allow future extensions. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [debuggees breakpoints update controller](struct.ControllerDebuggeeBreakpointUpdateCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct UpdateActiveBreakpointResponse; + +impl ResponseResult for UpdateActiveBreakpointResponse {} + + +/// Selects a repo using a Google Cloud Platform project ID (e.g. winged-cargo-31) and a repo name within that project. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ProjectRepoId { + /// The ID of the project. + #[serde(rename="projectId")] + pub project_id: Option, + /// The name of the repo. Leave empty for the default repo. + #[serde(rename="repoName")] + pub repo_name: Option, +} + +impl Part for ProjectRepoId {} + + +/// The response of listing active breakpoints. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [debuggees breakpoints list controller](struct.ControllerDebuggeeBreakpointListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ListActiveBreakpointsResponse { + /// A wait token that can be used in the next method call to block until the list of breakpoints changes. + #[serde(rename="nextWaitToken")] + pub next_wait_token: Option, + /// List of all active breakpoints. The fields 'id' and 'location' are guranteed to be set on each breakpoint. + pub breakpoints: Option>, +} + +impl ResponseResult for ListActiveBreakpointsResponse {} + + +/// A CloudRepoSourceContext denotes a particular revision in a cloud repo (a repo hosted by the Google Cloud Platform). +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct CloudRepoSourceContext { + /// A revision ID. + #[serde(rename="revisionId")] + pub revision_id: Option, + /// The name of an alias (branch, tag, etc.). + #[serde(rename="aliasName")] + pub alias_name: Option, + /// The ID of the repo. + #[serde(rename="repoId")] + pub repo_id: Option, +} + +impl Part for CloudRepoSourceContext {} + + +/// A unique identifier for a cloud repo. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct RepoId { + /// A combination of a project ID and a repo name. + #[serde(rename="projectRepoId")] + pub project_repo_id: Option, + /// A server-assigned, globally unique identifier. + pub uid: Option, +} + +impl Part for RepoId {} + + +/// A generic empty message that you can re-use to avoid defining duplicated empty messages in your APIs. A typical example is to use it as the request or the response type of an API method. For instance: service Foo { rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); } The JSON representation for `Empty` is empty JSON object `{}`. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [debuggees breakpoints delete debugger](struct.DebuggerDebuggeeBreakpointDeleteCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Empty; + +impl ResponseResult for Empty {} + + +/// A SourceContext referring to a Gerrit project. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct GerritSourceContext { + /// A revision (commit) ID. + #[serde(rename="revisionId")] + pub revision_id: Option, + /// The URI of a running Gerrit instance. + #[serde(rename="hostUri")] + pub host_uri: Option, + /// The name of an alias (branch, tag, etc.). + #[serde(rename="aliasName")] + pub alias_name: Option, + /// The full project name within the host. Projects may be nested, so "project/subproject" is a valid project name. The "repo name" is hostURI/project. + #[serde(rename="gerritProject")] + pub gerrit_project: Option, +} + +impl Part for GerritSourceContext {} + + +/// The response of registering a debuggee. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [debuggees register controller](struct.ControllerDebuggeeRegisterCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct RegisterDebuggeeResponse { + /// The debuggee resource. The field 'id' is guranteed to be set (in addition to the echoed fields). + pub debuggee: Option, +} + +impl ResponseResult for RegisterDebuggeeResponse {} + + +/// A SourceContext is a reference to a tree of files. A SourceContext together with a path point to a unique revision of a single file or directory. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct SourceContext { + /// A SourceContext referring to a snapshot in a cloud workspace. + #[serde(rename="cloudWorkspace")] + pub cloud_workspace: Option, + /// A SourceContext referring to a revision in a cloud repo. + #[serde(rename="cloudRepo")] + pub cloud_repo: Option, + /// A SourceContext referring to any third party Git repo (e.g. GitHub). + pub git: Option, + /// A SourceContext referring to a Gerrit project. + pub gerrit: Option, +} + +impl Part for SourceContext {} + + +/// The request to update an active breakpoint. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [debuggees breakpoints update controller](struct.ControllerDebuggeeBreakpointUpdateCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct UpdateActiveBreakpointRequest { + /// The updated breakpoint information. The field 'id' must be set. + pub breakpoint: Option, +} + +impl RequestValue for UpdateActiveBreakpointRequest {} + + +/// Represents a location in the source code. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct SourceLocation { + /// A path to the source file within the source context of the target binary. + pub path: Option, + /// The line inside the file (first line value is '1'). + pub line: Option, +} + +impl Part for SourceLocation {} + + +/// Represents the application to debug. The application may include one or more replicated processes executing the same code. Each of these processes is attached with a debugger agent, carrying out the debugging commands. The agents attached to the same debuggee are identified by using exactly the same fields' values when registering. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Debuggee { + /// Human readable message to be displayed to the user about this debuggee. Absense of this field indicates no message. The message can be either informational or error. + pub status: Option, + /// A human readable description of the debuggee. Recommended to include human readable project name, environment name, and version information . + pub description: Option, + /// If set to true, indicates that the agent should disable itself and detach from the debuggee. + #[serde(rename="isDisabled")] + pub is_disabled: Option, + /// A set of custom debuggee properties, populated by the agent, to be displayed to the user. + pub labels: Option>, + /// The debuggee uniqifier within the project. Any string that id the application within the project can be used. Recomended to include environement and version or build id's. + pub uniquifier: Option, + /// The project the debuggee is associated with. Use the project number when registering a Google Cloud Platform project. + pub project: Option, + /// Repository snapshots containing the source code of the project. + #[serde(rename="sourceContexts")] + pub source_contexts: Option>, + /// Version ID of the agent release. The version ID is structured as following: "domain/type/vmajor.minor" (for example "google.com/gcp-java/v1.1"). + #[serde(rename="agentVersion")] + pub agent_version: Option, + /// If set to true indicates that the debuggee has not been seen by the Controller service in the last active time period (defined by the server). + #[serde(rename="isInactive")] + pub is_inactive: Option, + /// Debuggee unique identifer generated by the server. + pub id: Option, +} + +impl Part for Debuggee {} + + +/// Represents a message with parameters. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct FormatMessage { + /// Optional parameters to be embedded into the message. + pub parameters: Option>, + /// Format template of the message. The "format" uses placeholders "$0", "$1", etc. to reference parameters. "$$" can be used to denote the '$' character. Examples: "Failed to load '$0' which helps debug $1 the first time it is loaded. Again, $0 is very important." "Please pay $$10 to use $0 instead of $1." + pub format: Option, +} + +impl Part for FormatMessage {} + + +/// A GitSourceContext denotes a particular revision in a third party Git repository (e.g. GitHub). +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct GitSourceContext { + /// Git repository URL. + pub url: Option, + /// Git commit hash. required. + #[serde(rename="revisionId")] + pub revision_id: Option, +} + +impl Part for GitSourceContext {} + + +/// A CloudWorkspaceId is a unique identifier for a cloud workspace. A cloud workspace is a place associated with a repo where modified files can be stored before they are committed. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct CloudWorkspaceId { + /// The ID of the repo containing the workspace. + #[serde(rename="repoId")] + pub repo_id: Option, + /// The unique name of the workspace within the repo. This is the name chosen by the client in the Source API's CreateWorkspace method. + pub name: Option, +} + +impl Part for CloudWorkspaceId {} + + +/// Represents the breakpoint specification, status and 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*). +/// +/// * [debuggees breakpoints set debugger](struct.DebuggerDebuggeeBreakpointSetCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Breakpoint { + /// Breakpoint status. The status includes an error flag and a human readable message. This field will usually stay unset. The message can be either informational or error. Nevertheless, clients should always display the text message back to the user. Error status of a breakpoint indicates complete failure. Example (non-final state): 'Still loading symbols...' Examples (final state): 'Failed to insert breakpoint' referring to breakpoint, 'Field f not found in class C' referring to condition, ... + pub status: Option, + /// The variable_table exists to aid with computation, memory and network traffic optimization. It enables storing a variable once and reference it from multiple variables, including variables stored in the variable_table itself. For example, the object 'this', which may appear at many levels of the stack, can have all of it's data stored once in this table. The stack frame variables then would hold only a reference to it. The variable var_index field is an index into this repeated field. The stored objects are nameless and get their name from the referencing variable. The effective variable is a merge of the referencing veariable and the referenced variable. + #[serde(rename="variableTable")] + pub variable_table: Option>, + /// The e-mail of the user that created this breakpoint + #[serde(rename="userEmail")] + pub user_email: Option, + /// Indicates the severity of the log. Only relevant when action is "LOG". + #[serde(rename="logLevel")] + pub log_level: Option, + /// Breakpoint identifier, unique in the scope of the debuggee. + pub id: Option, + /// Only relevant when action is "LOG". Defines the message to log when the breakpoint hits. The message may include parameter placeholders "$0", "$1", etc. These placeholders will be replaced with the evaluated value of the appropriate expression. Expressions not referenced in "log_message_format" will not be logged. Example: "Poisonous message received, id = $0, count = $1" with expressions = [ "message.id", "message.count" ]. + #[serde(rename="logMessageFormat")] + pub log_message_format: Option, + /// The stack at breakpoint time. + #[serde(rename="stackFrames")] + pub stack_frames: Option>, + /// The breakpoint source location. + pub location: Option, + /// The time this breakpoint was finalized as seen by the server. The value is in seconds resolution. + #[serde(rename="finalTime")] + pub final_time: Option, + /// Defines what to do when the breakpoint hits. + pub action: Option, + /// A list of read-only expressions to evaluate at the breakpoint location. The expressions are composed using expressions in the programming language at the source location. If the breakpoint action is "LOG", the evaluated expressions are included in log statements. + pub expressions: Option>, + /// When true, indicates that this is a final result and the breakpoint state will not change from here on. + #[serde(rename="isFinalState")] + pub is_final_state: Option, + /// The evaluated expressions' values at breakpoint time. The evaluated expressions appear in exactly the same order they are listed in the 'expressions' field. The 'name' field holds the original expression text, the 'value'/'members' field holds the result of the evaluated expression. If the expression can not be evaluated, an error text is placed in the value field. + #[serde(rename="evaluatedExpressions")] + pub evaluated_expressions: Option>, + /// The time this breakpoint was created by the server. The value is in seconds resolution. + #[serde(rename="createTime")] + pub create_time: Option, + /// A condition to trigger the breakpoint. The condition is a compound boolean expression composed using expressions in a programming language at the source location. + pub condition: Option, +} + +impl RequestValue for Breakpoint {} + + +/// Represents a variable or an argument possibly of a compound object type. 1. A simple variable such as, int x = 5 is represented as: { name: "x", value: "5" } 2. A compound object such as, struct T { int m1; int m2; }; T x = { 3, 7 }; is represented as: { name: "x", members { name: "m1", value: "3" }, members { name: "m2", value: "7" } } 3. A pointer where the pointee was captured such as, T x = { 3, 7 }; T* p = &x; is represented as: { name: "p", value: "0x00500500", members { name: "m1", value: "3" }, members { name: "m2", value: "7" } } 4. A pointer where the pointee was not captured or is inaccessible such as, T* p = new T; is represented as: { name: "p", value: "0x00400400", members { value: "" } } the value text should decribe the reason for the missing value. such as , , +/// . note that a null pointer should not have members. 5. An unnamed value such as, int* p = new int(7); is represented as, { name: "p", value: "0x00500500", members { value: "7" } } 6. An unnamed pointer where the pointee was not captured such as, int* p = new int(7); int** pp = &p; is represented as: { name: "pp", value: "0x00500500", members { value: "0x00400400", members { value: "" } } } To optimize computation, memory and network traffic, variables that repeat in the output multiple times can be stored once in a shared variable table and be referenced using the var_index field. The variables stored in the shared table are nameless and are essentially a partition of the complete variable. To reconstruct the complete variable merge the referencing variable with the referenced variable. When using the shared variable table, variables can be represented as: T x = { 3, 7 }; T* p = &x; T& r = x; are represented as, { name: "x", var_index: 3 } { name: "p", value "0x00500500", var_index: 3 } { name: "r", var_index: 3 } with shared variable table entry #3: { members { name: "m1", value: "3" }, members { name: "m2", value: "7" } } Note that the pointer address is stored with the referencing variable and not with the referenced variable, to allow the referenced variable to be shared between pointer and references. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Variable { + /// Status associated with the variable. This field will usually stay unset. A status of a single variable only applies to that variable or expression. The rest of breakpoint data still remains valid. Variables might be reported in error state even when breakpoint is not in final state. The message may refer to variable name with "refers_to" set to "VARIABLE_NAME". Alternatively "refers_to" will be set to "VARIABLE_VALUE". In either case variable value and members will be unset. Example of error message applied to name: "Invalid expression syntax". Example of information message applied to value: "Not captured". Examples of error message applied to value: "Malformed string", "Field f not found in class C", "Null pointer dereference". + pub status: Option, + /// The simple value of the variable. + pub value: Option, + /// This is a reference to a variable in the shared variable table. More than one variable can reference the same variable in the table. The var_index field is an index into variable_table in Breakpoint. + #[serde(rename="varTableIndex")] + pub var_table_index: Option, + /// The members contained or pointed to by the variable. + pub members: Option>, + /// The name of the variable, if any. + pub name: Option, +} + +impl Part for Variable {} + + +/// The response of setting a breakpoint. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [debuggees breakpoints set debugger](struct.DebuggerDebuggeeBreakpointSetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct SetBreakpointResponse { + /// The breakpoint resource. The field 'id' is guranteed to be set (in addition to the echoed fileds). + pub breakpoint: Option, +} + +impl ResponseResult for SetBreakpointResponse {} + + +/// Represents a contextual status message. The message can indicate an error or informational status, and refer to specific parts of the containing object. For example, the Breakpoint.status field can indicate an error referring to the BREAKPOINT_SOURCE_LOCATION with the message "Location not found". +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct StatusMessage { + /// Distinguishes errors from informational messages. + #[serde(rename="isError")] + pub is_error: Option, + /// Reference to which the message applies. + #[serde(rename="refersTo")] + pub refers_to: Option, + /// Status message text. + pub description: Option, +} + +impl Part for StatusMessage {} + + +/// The response of getting breakpoint 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*). +/// +/// * [debuggees breakpoints get debugger](struct.DebuggerDebuggeeBreakpointGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct GetBreakpointResponse { + /// The complete breakpoint state. The fields 'id' and 'location' are guranteed to be set. + pub breakpoint: Option, +} + +impl ResponseResult for GetBreakpointResponse {} + + + +// ################### +// MethodBuilders ### +// ################# + +/// A builder providing access to all methods supported on *controller* resources. +/// It is not used directly, but through the `Clouddebugger` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate yup_oauth2 as oauth2; +/// extern crate google_clouddebugger2 as clouddebugger2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use clouddebugger2::Clouddebugger; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Clouddebugger::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `debuggees_breakpoints_list(...)`, `debuggees_breakpoints_update(...)` and `debuggees_register(...)` +/// // to build up your call. +/// let rb = hub.controller(); +/// # } +/// ``` +pub struct ControllerMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Clouddebugger, +} + +impl<'a, C, A> MethodsBuilder for ControllerMethods<'a, C, A> {} + +impl<'a, C, A> ControllerMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Updates the breakpoint state or mutable fields. The entire Breakpoint protobuf must be sent back to the controller. Updates to active breakpoint fields are only allowed if the new value does not change the breakpoint specification. Updates to the 'location', 'condition' and 'expression' fields should not alter the breakpoint semantics. They are restricted to changes such as canonicalizing a value or snapping the location to the correct line of code. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `debuggeeId` - Identifies the debuggee being debugged. + /// * `id` - Breakpoint identifier, unique in the scope of the debuggee. + pub fn debuggees_breakpoints_update(&self, request: UpdateActiveBreakpointRequest, debuggee_id: &str, id: &str) -> ControllerDebuggeeBreakpointUpdateCall<'a, C, A> { + ControllerDebuggeeBreakpointUpdateCall { + hub: self.hub, + _request: request, + _debuggee_id: debuggee_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: + /// + /// Registers the debuggee with the controller. All agents should call this API with the same request content to get back the same stable 'debuggee_id'. Agents should call this API again whenever ListActiveBreakpoints or UpdateActiveBreakpoint return the error google.rpc.Code.NOT_FOUND. It allows the server to disable the agent or recover from any registration loss. If the debuggee is disabled server, the response will have is_disabled' set to true. + /// + /// # Arguments + /// + /// * `request` - No description provided. + pub fn debuggees_register(&self, request: RegisterDebuggeeRequest) -> ControllerDebuggeeRegisterCall<'a, C, A> { + ControllerDebuggeeRegisterCall { + hub: self.hub, + _request: request, + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Returns the list of all active breakpoints for the specified debuggee. The breakpoint specification (location, condition, and expression fields) is semantically immutable, although the field values may change. For example, an agent may update the location line number to reflect the actual line the breakpoint was set to, but that doesn't change the breakpoint semantics. Thus, an agent does not need to check if a breakpoint has changed when it encounters the same breakpoint on a successive call. Moreover, an agent should remember breakpoints that are complete until the controller removes them from the active list to avoid setting those breakpoints again. + /// + /// # Arguments + /// + /// * `debuggeeId` - Identifies the debuggee. + pub fn debuggees_breakpoints_list(&self, debuggee_id: &str) -> ControllerDebuggeeBreakpointListCall<'a, C, A> { + ControllerDebuggeeBreakpointListCall { + hub: self.hub, + _debuggee_id: debuggee_id.to_string(), + _wait_token: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *debugger* resources. +/// It is not used directly, but through the `Clouddebugger` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate yup_oauth2 as oauth2; +/// extern crate google_clouddebugger2 as clouddebugger2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use clouddebugger2::Clouddebugger; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Clouddebugger::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `debuggees_breakpoints_delete(...)`, `debuggees_breakpoints_get(...)`, `debuggees_breakpoints_list(...)`, `debuggees_breakpoints_set(...)` and `debuggees_list(...)` +/// // to build up your call. +/// let rb = hub.debugger(); +/// # } +/// ``` +pub struct DebuggerMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Clouddebugger, +} + +impl<'a, C, A> MethodsBuilder for DebuggerMethods<'a, C, A> {} + +impl<'a, C, A> DebuggerMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Gets breakpoint information. + /// + /// # Arguments + /// + /// * `debuggeeId` - The debuggee id to get the breakpoint from. + /// * `breakpointId` - The breakpoint to get. + pub fn debuggees_breakpoints_get(&self, debuggee_id: &str, breakpoint_id: &str) -> DebuggerDebuggeeBreakpointGetCall<'a, C, A> { + DebuggerDebuggeeBreakpointGetCall { + hub: self.hub, + _debuggee_id: debuggee_id.to_string(), + _breakpoint_id: breakpoint_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 breakpoint from the debuggee. + /// + /// # Arguments + /// + /// * `debuggeeId` - The debuggee id to delete the breakpoint from. + /// * `breakpointId` - The breakpoint to delete. + pub fn debuggees_breakpoints_delete(&self, debuggee_id: &str, breakpoint_id: &str) -> DebuggerDebuggeeBreakpointDeleteCall<'a, C, A> { + DebuggerDebuggeeBreakpointDeleteCall { + hub: self.hub, + _debuggee_id: debuggee_id.to_string(), + _breakpoint_id: breakpoint_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 debuggees that the user can set breakpoints to. + pub fn debuggees_list(&self) -> DebuggerDebuggeeListCall<'a, C, A> { + DebuggerDebuggeeListCall { + hub: self.hub, + _project: 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: + /// + /// Sets the breakpoint to the debuggee. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `debuggeeId` - The debuggee id to set the breakpoint to. + pub fn debuggees_breakpoints_set(&self, request: Breakpoint, debuggee_id: &str) -> DebuggerDebuggeeBreakpointSetCall<'a, C, A> { + DebuggerDebuggeeBreakpointSetCall { + hub: self.hub, + _request: request, + _debuggee_id: debuggee_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 breakpoints of the debuggee that the user has access to. + /// + /// # Arguments + /// + /// * `debuggeeId` - The debuggee id to list breakpoint from. + pub fn debuggees_breakpoints_list(&self, debuggee_id: &str) -> DebuggerDebuggeeBreakpointListCall<'a, C, A> { + DebuggerDebuggeeBreakpointListCall { + hub: self.hub, + _debuggee_id: debuggee_id.to_string(), + _wait_token: Default::default(), + _strip_results: Default::default(), + _include_inactive: Default::default(), + _include_all_users: Default::default(), + _action_value: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + + + +// ################### +// CallBuilders ### +// ################# + +/// Updates the breakpoint state or mutable fields. The entire Breakpoint protobuf must be sent back to the controller. Updates to active breakpoint fields are only allowed if the new value does not change the breakpoint specification. Updates to the 'location', 'condition' and 'expression' fields should not alter the breakpoint semantics. They are restricted to changes such as canonicalizing a value or snapping the location to the correct line of code. +/// +/// A builder for the *debuggees.breakpoints.update* method supported by a *controller* resource. +/// It is not used directly, but through a `ControllerMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_clouddebugger2 as clouddebugger2; +/// use clouddebugger2::UpdateActiveBreakpointRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use clouddebugger2::Clouddebugger; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Clouddebugger::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req = UpdateActiveBreakpointRequest::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.controller().debuggees_breakpoints_update(req, "debuggeeId", "id") +/// .doit(); +/// # } +/// ``` +pub struct ControllerDebuggeeBreakpointUpdateCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Clouddebugger, + _request: UpdateActiveBreakpointRequest, + _debuggee_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ControllerDebuggeeBreakpointUpdateCall<'a, C, A> {} + +impl<'a, C, A> ControllerDebuggeeBreakpointUpdateCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, UpdateActiveBreakpointResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "clouddebugger.controller.debuggees.breakpoints.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("debuggeeId", self._debuggee_id.to_string())); + params.push(("id", self._id.to_string())); + for &field in ["alt", "debuggeeId", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://clouddebugger.googleapis.com/v2/controller/debuggees/{debuggeeId}/breakpoints/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{debuggeeId}", "debuggeeId"), ("{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 ["id", "debuggeeId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: UpdateActiveBreakpointRequest) -> ControllerDebuggeeBreakpointUpdateCall<'a, C, A> { + self._request = new_value; + self + } + /// Identifies the debuggee being debugged. + /// + /// Sets the *debuggee id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn debuggee_id(mut self, new_value: &str) -> ControllerDebuggeeBreakpointUpdateCall<'a, C, A> { + self._debuggee_id = new_value.to_string(); + self + } + /// Breakpoint identifier, unique in the scope of the debuggee. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> ControllerDebuggeeBreakpointUpdateCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ControllerDebuggeeBreakpointUpdateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> ControllerDebuggeeBreakpointUpdateCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ControllerDebuggeeBreakpointUpdateCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Registers the debuggee with the controller. All agents should call this API with the same request content to get back the same stable 'debuggee_id'. Agents should call this API again whenever ListActiveBreakpoints or UpdateActiveBreakpoint return the error google.rpc.Code.NOT_FOUND. It allows the server to disable the agent or recover from any registration loss. If the debuggee is disabled server, the response will have is_disabled' set to true. +/// +/// A builder for the *debuggees.register* method supported by a *controller* resource. +/// It is not used directly, but through a `ControllerMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_clouddebugger2 as clouddebugger2; +/// use clouddebugger2::RegisterDebuggeeRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use clouddebugger2::Clouddebugger; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Clouddebugger::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req = RegisterDebuggeeRequest::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.controller().debuggees_register(req) +/// .doit(); +/// # } +/// ``` +pub struct ControllerDebuggeeRegisterCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Clouddebugger, + _request: RegisterDebuggeeRequest, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ControllerDebuggeeRegisterCall<'a, C, A> {} + +impl<'a, C, A> ControllerDebuggeeRegisterCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, RegisterDebuggeeResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "clouddebugger.controller.debuggees.register", + 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 Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://clouddebugger.googleapis.com/v2/controller/debuggees/register".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: RegisterDebuggeeRequest) -> ControllerDebuggeeRegisterCall<'a, C, A> { + self._request = new_value; + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ControllerDebuggeeRegisterCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> ControllerDebuggeeRegisterCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ControllerDebuggeeRegisterCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Returns the list of all active breakpoints for the specified debuggee. The breakpoint specification (location, condition, and expression fields) is semantically immutable, although the field values may change. For example, an agent may update the location line number to reflect the actual line the breakpoint was set to, but that doesn't change the breakpoint semantics. Thus, an agent does not need to check if a breakpoint has changed when it encounters the same breakpoint on a successive call. Moreover, an agent should remember breakpoints that are complete until the controller removes them from the active list to avoid setting those breakpoints again. +/// +/// A builder for the *debuggees.breakpoints.list* method supported by a *controller* resource. +/// It is not used directly, but through a `ControllerMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_clouddebugger2 as clouddebugger2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use clouddebugger2::Clouddebugger; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Clouddebugger::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.controller().debuggees_breakpoints_list("debuggeeId") +/// .wait_token("dolores") +/// .doit(); +/// # } +/// ``` +pub struct ControllerDebuggeeBreakpointListCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Clouddebugger, + _debuggee_id: String, + _wait_token: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ControllerDebuggeeBreakpointListCall<'a, C, A> {} + +impl<'a, C, A> ControllerDebuggeeBreakpointListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ListActiveBreakpointsResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "clouddebugger.controller.debuggees.breakpoints.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("debuggeeId", self._debuggee_id.to_string())); + if let Some(value) = self._wait_token { + params.push(("waitToken", value.to_string())); + } + for &field in ["alt", "debuggeeId", "waitToken"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://clouddebugger.googleapis.com/v2/controller/debuggees/{debuggeeId}/breakpoints".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{debuggeeId}", "debuggeeId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["debuggeeId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Identifies the debuggee. + /// + /// Sets the *debuggee id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn debuggee_id(mut self, new_value: &str) -> ControllerDebuggeeBreakpointListCall<'a, C, A> { + self._debuggee_id = new_value.to_string(); + self + } + /// A wait token that, if specified, blocks the method call until the list of active breakpoints has changed, or a server selected timeout has expired. The value should be set from the last returned response. The error code google.rpc.Code.ABORTED is returned on wait timeout (which does not require the agent to re-register with the server) + /// + /// Sets the *wait token* query property to the given value. + pub fn wait_token(mut self, new_value: &str) -> ControllerDebuggeeBreakpointListCall<'a, C, A> { + self._wait_token = Some(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ControllerDebuggeeBreakpointListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> ControllerDebuggeeBreakpointListCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ControllerDebuggeeBreakpointListCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Gets breakpoint information. +/// +/// A builder for the *debuggees.breakpoints.get* method supported by a *debugger* resource. +/// It is not used directly, but through a `DebuggerMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_clouddebugger2 as clouddebugger2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use clouddebugger2::Clouddebugger; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Clouddebugger::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.debugger().debuggees_breakpoints_get("debuggeeId", "breakpointId") +/// .doit(); +/// # } +/// ``` +pub struct DebuggerDebuggeeBreakpointGetCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Clouddebugger, + _debuggee_id: String, + _breakpoint_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for DebuggerDebuggeeBreakpointGetCall<'a, C, A> {} + +impl<'a, C, A> DebuggerDebuggeeBreakpointGetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, GetBreakpointResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "clouddebugger.debugger.debuggees.breakpoints.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("debuggeeId", self._debuggee_id.to_string())); + params.push(("breakpointId", self._breakpoint_id.to_string())); + for &field in ["alt", "debuggeeId", "breakpointId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://clouddebugger.googleapis.com/v2/debugger/debuggees/{debuggeeId}/breakpoints/{breakpointId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{debuggeeId}", "debuggeeId"), ("{breakpointId}", "breakpointId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["breakpointId", "debuggeeId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The debuggee id to get the breakpoint from. + /// + /// Sets the *debuggee id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn debuggee_id(mut self, new_value: &str) -> DebuggerDebuggeeBreakpointGetCall<'a, C, A> { + self._debuggee_id = new_value.to_string(); + self + } + /// The breakpoint to get. + /// + /// Sets the *breakpoint id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn breakpoint_id(mut self, new_value: &str) -> DebuggerDebuggeeBreakpointGetCall<'a, C, A> { + self._breakpoint_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DebuggerDebuggeeBreakpointGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> DebuggerDebuggeeBreakpointGetCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DebuggerDebuggeeBreakpointGetCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Deletes the breakpoint from the debuggee. +/// +/// A builder for the *debuggees.breakpoints.delete* method supported by a *debugger* resource. +/// It is not used directly, but through a `DebuggerMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_clouddebugger2 as clouddebugger2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use clouddebugger2::Clouddebugger; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Clouddebugger::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.debugger().debuggees_breakpoints_delete("debuggeeId", "breakpointId") +/// .doit(); +/// # } +/// ``` +pub struct DebuggerDebuggeeBreakpointDeleteCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Clouddebugger, + _debuggee_id: String, + _breakpoint_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for DebuggerDebuggeeBreakpointDeleteCall<'a, C, A> {} + +impl<'a, C, A> DebuggerDebuggeeBreakpointDeleteCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Empty)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "clouddebugger.debugger.debuggees.breakpoints.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("debuggeeId", self._debuggee_id.to_string())); + params.push(("breakpointId", self._breakpoint_id.to_string())); + for &field in ["alt", "debuggeeId", "breakpointId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://clouddebugger.googleapis.com/v2/debugger/debuggees/{debuggeeId}/breakpoints/{breakpointId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{debuggeeId}", "debuggeeId"), ("{breakpointId}", "breakpointId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["breakpointId", "debuggeeId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The debuggee id to delete the breakpoint from. + /// + /// Sets the *debuggee id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn debuggee_id(mut self, new_value: &str) -> DebuggerDebuggeeBreakpointDeleteCall<'a, C, A> { + self._debuggee_id = new_value.to_string(); + self + } + /// The breakpoint to delete. + /// + /// Sets the *breakpoint id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn breakpoint_id(mut self, new_value: &str) -> DebuggerDebuggeeBreakpointDeleteCall<'a, C, A> { + self._breakpoint_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DebuggerDebuggeeBreakpointDeleteCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> DebuggerDebuggeeBreakpointDeleteCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DebuggerDebuggeeBreakpointDeleteCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Lists all the debuggees that the user can set breakpoints to. +/// +/// A builder for the *debuggees.list* method supported by a *debugger* resource. +/// It is not used directly, but through a `DebuggerMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_clouddebugger2 as clouddebugger2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use clouddebugger2::Clouddebugger; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Clouddebugger::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.debugger().debuggees_list() +/// .project("amet.") +/// .include_inactive(false) +/// .doit(); +/// # } +/// ``` +pub struct DebuggerDebuggeeListCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Clouddebugger, + _project: Option, + _include_inactive: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for DebuggerDebuggeeListCall<'a, C, A> {} + +impl<'a, C, A> DebuggerDebuggeeListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ListDebuggeesResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "clouddebugger.debugger.debuggees.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._project { + params.push(("project", value.to_string())); + } + if let Some(value) = self._include_inactive { + params.push(("includeInactive", value.to_string())); + } + for &field in ["alt", "project", "includeInactive"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://clouddebugger.googleapis.com/v2/debugger/debuggees".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Set to the project number of the Google Cloud Platform to list the debuggees that are part of that project. + /// + /// Sets the *project* query property to the given value. + pub fn project(mut self, new_value: &str) -> DebuggerDebuggeeListCall<'a, C, A> { + self._project = Some(new_value.to_string()); + self + } + /// When set to true the result includes all debuggees, otherwise only debugees that are active. + /// + /// Sets the *include inactive* query property to the given value. + pub fn include_inactive(mut self, new_value: bool) -> DebuggerDebuggeeListCall<'a, C, A> { + self._include_inactive = Some(new_value); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DebuggerDebuggeeListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> DebuggerDebuggeeListCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DebuggerDebuggeeListCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Sets the breakpoint to the debuggee. +/// +/// A builder for the *debuggees.breakpoints.set* method supported by a *debugger* resource. +/// It is not used directly, but through a `DebuggerMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_clouddebugger2 as clouddebugger2; +/// use clouddebugger2::Breakpoint; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use clouddebugger2::Clouddebugger; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Clouddebugger::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req = Breakpoint::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.debugger().debuggees_breakpoints_set(req, "debuggeeId") +/// .doit(); +/// # } +/// ``` +pub struct DebuggerDebuggeeBreakpointSetCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Clouddebugger, + _request: Breakpoint, + _debuggee_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for DebuggerDebuggeeBreakpointSetCall<'a, C, A> {} + +impl<'a, C, A> DebuggerDebuggeeBreakpointSetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, SetBreakpointResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "clouddebugger.debugger.debuggees.breakpoints.set", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("debuggeeId", self._debuggee_id.to_string())); + for &field in ["alt", "debuggeeId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://clouddebugger.googleapis.com/v2/debugger/debuggees/{debuggeeId}/breakpoints/set".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{debuggeeId}", "debuggeeId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["debuggeeId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: Breakpoint) -> DebuggerDebuggeeBreakpointSetCall<'a, C, A> { + self._request = new_value; + self + } + /// The debuggee id to set the breakpoint to. + /// + /// Sets the *debuggee id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn debuggee_id(mut self, new_value: &str) -> DebuggerDebuggeeBreakpointSetCall<'a, C, A> { + self._debuggee_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DebuggerDebuggeeBreakpointSetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> DebuggerDebuggeeBreakpointSetCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DebuggerDebuggeeBreakpointSetCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Lists all breakpoints of the debuggee that the user has access to. +/// +/// A builder for the *debuggees.breakpoints.list* method supported by a *debugger* resource. +/// It is not used directly, but through a `DebuggerMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_clouddebugger2 as clouddebugger2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use clouddebugger2::Clouddebugger; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Clouddebugger::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.debugger().debuggees_breakpoints_list("debuggeeId") +/// .wait_token("nonumy") +/// .strip_results(true) +/// .include_inactive(false) +/// .include_all_users(false) +/// .action_value("aliquyam") +/// .doit(); +/// # } +/// ``` +pub struct DebuggerDebuggeeBreakpointListCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Clouddebugger, + _debuggee_id: String, + _wait_token: Option, + _strip_results: Option, + _include_inactive: Option, + _include_all_users: Option, + _action_value: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for DebuggerDebuggeeBreakpointListCall<'a, C, A> {} + +impl<'a, C, A> DebuggerDebuggeeBreakpointListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ListBreakpointsResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "clouddebugger.debugger.debuggees.breakpoints.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((8 + self._additional_params.len())); + params.push(("debuggeeId", self._debuggee_id.to_string())); + if let Some(value) = self._wait_token { + params.push(("waitToken", value.to_string())); + } + if let Some(value) = self._strip_results { + params.push(("stripResults", value.to_string())); + } + if let Some(value) = self._include_inactive { + params.push(("includeInactive", value.to_string())); + } + if let Some(value) = self._include_all_users { + params.push(("includeAllUsers", value.to_string())); + } + if let Some(value) = self._action_value { + params.push(("action.value", value.to_string())); + } + for &field in ["alt", "debuggeeId", "waitToken", "stripResults", "includeInactive", "includeAllUsers", "action.value"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://clouddebugger.googleapis.com/v2/debugger/debuggees/{debuggeeId}/breakpoints".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{debuggeeId}", "debuggeeId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["debuggeeId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The debuggee id to list breakpoint from. + /// + /// Sets the *debuggee id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn debuggee_id(mut self, new_value: &str) -> DebuggerDebuggeeBreakpointListCall<'a, C, A> { + self._debuggee_id = new_value.to_string(); + self + } + /// A wait token that, if specified, blocks the call until the breakpoints list has changed, or a server selected timeout has expired. The value should be set from the last response to ListBreakpoints. The error code ABORTED is returned on wait timeout, which should be called again with the same wait_token. + /// + /// Sets the *wait token* query property to the given value. + pub fn wait_token(mut self, new_value: &str) -> DebuggerDebuggeeBreakpointListCall<'a, C, A> { + self._wait_token = Some(new_value.to_string()); + self + } + /// When set to true the response breakpoints will be stripped of the results fields: stack_frames, evaluated_expressions and variable_table. + /// + /// Sets the *strip results* query property to the given value. + pub fn strip_results(mut self, new_value: bool) -> DebuggerDebuggeeBreakpointListCall<'a, C, A> { + self._strip_results = Some(new_value); + self + } + /// When set to true the response includes active and inactive breakpoints, otherwise only active breakpoints are returned. + /// + /// Sets the *include inactive* query property to the given value. + pub fn include_inactive(mut self, new_value: bool) -> DebuggerDebuggeeBreakpointListCall<'a, C, A> { + self._include_inactive = Some(new_value); + self + } + /// When set to true the response includes the list of breakpoints set by any user, otherwise only breakpoints set by the caller. + /// + /// Sets the *include all users* query property to the given value. + pub fn include_all_users(mut self, new_value: bool) -> DebuggerDebuggeeBreakpointListCall<'a, C, A> { + self._include_all_users = Some(new_value); + self + } + /// Only breakpoints with the specified action will pass the filter. + /// + /// Sets the *action.value* query property to the given value. + pub fn action_value(mut self, new_value: &str) -> DebuggerDebuggeeBreakpointListCall<'a, C, A> { + self._action_value = Some(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DebuggerDebuggeeBreakpointListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> DebuggerDebuggeeBreakpointListCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DebuggerDebuggeeBreakpointListCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + diff --git a/gen/cloudmonitoring2_beta2-cli/Cargo.toml b/gen/cloudmonitoring2_beta2-cli/Cargo.toml index 13d26e3a87..6fdd4390b5 100644 --- a/gen/cloudmonitoring2_beta2-cli/Cargo.toml +++ b/gen/cloudmonitoring2_beta2-cli/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-cloudmonitoring2_beta2-cli" -version = "0.3.2+20150713" +version = "0.3.2+20151012" 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-cli" diff --git a/gen/cloudmonitoring2_beta2-cli/README.md b/gen/cloudmonitoring2_beta2-cli/README.md index 5a0124d16f..327b5e82bc 100644 --- a/gen/cloudmonitoring2_beta2-cli/README.md +++ b/gen/cloudmonitoring2_beta2-cli/README.md @@ -24,7 +24,7 @@ Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/ma # Usage -This documentation was generated from the *Cloud Monitoring* API at revision *20150713*. The CLI is at version *0.3.2*. +This documentation was generated from the *Cloud Monitoring* API at revision *20151012*. The CLI is at version *0.3.2*. ```bash cloudmonitoring2-beta2 [options] diff --git a/gen/cloudmonitoring2_beta2-cli/mkdocs.yml b/gen/cloudmonitoring2_beta2-cli/mkdocs.yml index 0e8758557a..b6c3eda800 100644 --- a/gen/cloudmonitoring2_beta2-cli/mkdocs.yml +++ b/gen/cloudmonitoring2_beta2-cli/mkdocs.yml @@ -1,4 +1,4 @@ -site_name: Cloud Monitoring v0.3.2+20150713 +site_name: Cloud Monitoring v0.3.2+20151012 site_url: http://byron.github.io/google-apis-rs/google-cloudmonitoring2_beta2-cli site_description: Write integrating applications with bcore diff --git a/gen/cloudmonitoring2_beta2-cli/src/main.rs b/gen/cloudmonitoring2_beta2-cli/src/main.rs index 975101d443..bdc16d7fda 100644 --- a/gen/cloudmonitoring2_beta2-cli/src/main.rs +++ b/gen/cloudmonitoring2_beta2-cli/src/main.rs @@ -914,7 +914,7 @@ fn main() { let mut app = App::new("cloudmonitoring2-beta2") .author("Sebastian Thiel ") - .version("0.3.2+20150713") + .version("0.3.2+20151012") .about("API for accessing Google Cloud and API monitoring data.") .after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_cloudmonitoring2_beta2_cli") .arg(Arg::with_name("url") diff --git a/gen/cloudmonitoring2_beta2/Cargo.toml b/gen/cloudmonitoring2_beta2/Cargo.toml index f850f25c4c..29952fb187 100644 --- a/gen/cloudmonitoring2_beta2/Cargo.toml +++ b/gen/cloudmonitoring2_beta2/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-cloudmonitoring2_beta2" -version = "0.1.9+20150713" +version = "0.1.9+20151012" 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" diff --git a/gen/cloudmonitoring2_beta2/README.md b/gen/cloudmonitoring2_beta2/README.md index 02029bbf47..7153906916 100644 --- a/gen/cloudmonitoring2_beta2/README.md +++ b/gen/cloudmonitoring2_beta2/README.md @@ -5,7 +5,7 @@ DO NOT EDIT ! --> 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.9+20150713*, where *20150713* is the exact revision of the *cloudmonitoring:v2beta2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +This documentation was generated from *Cloud Monitoring* crate version *0.1.9+20151012*, where *20151012* is the exact revision of the *cloudmonitoring:v2beta2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. Everything else about the *Cloud Monitoring* *v2_beta2* API can be found at the [official documentation site](https://cloud.google.com/monitoring/v2beta2/). diff --git a/gen/cloudmonitoring2_beta2/src/lib.rs b/gen/cloudmonitoring2_beta2/src/lib.rs index d413fdee53..849164b1a0 100644 --- a/gen/cloudmonitoring2_beta2/src/lib.rs +++ b/gen/cloudmonitoring2_beta2/src/lib.rs @@ -2,7 +2,7 @@ // This file was generated automatically from 'src/mako/api/lib.rs.mako' // DO NOT EDIT ! -//! This documentation was generated from *Cloud Monitoring* crate version *0.1.9+20150713*, where *20150713* is the exact revision of the *cloudmonitoring:v2beta2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +//! This documentation was generated from *Cloud Monitoring* crate version *0.1.9+20151012*, where *20151012* is the exact revision of the *cloudmonitoring:v2beta2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. //! //! Everything else about the *Cloud Monitoring* *v2_beta2* API can be found at the //! [official documentation site](https://cloud.google.com/monitoring/v2beta2/). diff --git a/gen/cloudresourcemanager1_beta1-cli/Cargo.toml b/gen/cloudresourcemanager1_beta1-cli/Cargo.toml index d92f6d2c19..0a8731dec5 100644 --- a/gen/cloudresourcemanager1_beta1-cli/Cargo.toml +++ b/gen/cloudresourcemanager1_beta1-cli/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-cloudresourcemanager1_beta1-cli" -version = "0.3.2+20150711" +version = "0.3.2+20150909" authors = ["Sebastian Thiel "] description = "A complete library to interact with cloudresourcemanager (protocol v1beta1)" repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/cloudresourcemanager1_beta1-cli" diff --git a/gen/cloudresourcemanager1_beta1-cli/README.md b/gen/cloudresourcemanager1_beta1-cli/README.md index 2d9fc4d055..9ee50ba276 100644 --- a/gen/cloudresourcemanager1_beta1-cli/README.md +++ b/gen/cloudresourcemanager1_beta1-cli/README.md @@ -24,15 +24,25 @@ Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/ma # Usage -This documentation was generated from the *cloudresourcemanager* API at revision *20150711*. The CLI is at version *0.3.2*. +This documentation was generated from the *cloudresourcemanager* API at revision *20150909*. The CLI is at version *0.3.2*. ```bash cloudresourcemanager1-beta1 [options] + organizations + get [-p ]... [-o ] + get-iam-policy (-r )... [-p ]... [-o ] + list [-p ]... [-o ] + set-iam-policy (-r )... [-p ]... [-o ] + test-iam-permissions (-r )... [-p ]... [-o ] + update (-r )... [-p ]... [-o ] projects create (-r )... [-p ]... [-o ] delete [-p ]... [-o ] get [-p ]... [-o ] + get-iam-policy (-r )... [-p ]... [-o ] list [-p ]... [-o ] + set-iam-policy (-r )... [-p ]... [-o ] + test-iam-permissions (-r )... [-p ]... [-o ] undelete [-p ]... [-o ] update (-r )... [-p ]... [-o ] cloudresourcemanager1-beta1 --help diff --git a/gen/cloudresourcemanager1_beta1-cli/mkdocs.yml b/gen/cloudresourcemanager1_beta1-cli/mkdocs.yml index 4ac43669e6..993c61d1da 100644 --- a/gen/cloudresourcemanager1_beta1-cli/mkdocs.yml +++ b/gen/cloudresourcemanager1_beta1-cli/mkdocs.yml @@ -1,4 +1,4 @@ -site_name: cloudresourcemanager v0.3.2+20150711 +site_name: cloudresourcemanager v0.3.2+20150909 site_url: http://byron.github.io/google-apis-rs/google-cloudresourcemanager1_beta1-cli site_description: Write integrating applications with bcore @@ -9,10 +9,19 @@ site_dir: build_html pages: - ['index.md', 'Home'] +- ['organizations_get.md', 'Organizations', 'Get'] +- ['organizations_get-iam-policy.md', 'Organizations', 'Get Iam Policy'] +- ['organizations_list.md', 'Organizations', 'List'] +- ['organizations_set-iam-policy.md', 'Organizations', 'Set Iam Policy'] +- ['organizations_test-iam-permissions.md', 'Organizations', 'Test Iam Permissions'] +- ['organizations_update.md', 'Organizations', 'Update'] - ['projects_create.md', 'Projects', 'Create'] - ['projects_delete.md', 'Projects', 'Delete'] - ['projects_get.md', 'Projects', 'Get'] +- ['projects_get-iam-policy.md', 'Projects', 'Get Iam Policy'] - ['projects_list.md', 'Projects', 'List'] +- ['projects_set-iam-policy.md', 'Projects', 'Set Iam Policy'] +- ['projects_test-iam-permissions.md', 'Projects', 'Test Iam Permissions'] - ['projects_undelete.md', 'Projects', 'Undelete'] - ['projects_update.md', 'Projects', 'Update'] diff --git a/gen/cloudresourcemanager1_beta1-cli/src/main.rs b/gen/cloudresourcemanager1_beta1-cli/src/main.rs index ce6bc958b4..f2fddf9b94 100644 --- a/gen/cloudresourcemanager1_beta1-cli/src/main.rs +++ b/gen/cloudresourcemanager1_beta1-cli/src/main.rs @@ -45,6 +45,462 @@ struct Engine<'n, 'a> { impl<'n, 'a> Engine<'n, 'a> { + fn _organizations_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.organizations().get(opt.value_of("organization-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _organizations_get_iam_policy(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec![]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::GetIamPolicyRequest = json::value::from_value(object).unwrap(); + let mut call = self.hub.organizations().get_iam_policy(request, opt.value_of("resource").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _organizations_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.organizations().list(); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "page-size" => { + call = call.page_size(arg_from_str(value.unwrap_or("-0"), err, "page-size", "integer")); + }, + "filter" => { + call = call.filter(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["filter", "page-token", "page-size"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _organizations_set_iam_policy(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "policy.version" => Some(("policy.version", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "policy.etag" => Some(("policy.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["etag", "policy", "version"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::SetIamPolicyRequest = json::value::from_value(object).unwrap(); + let mut call = self.hub.organizations().set_iam_policy(request, opt.value_of("resource").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _organizations_test_iam_permissions(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "permissions" => Some(("permissions", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["permissions"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::TestIamPermissionsRequest = json::value::from_value(object).unwrap(); + let mut call = self.hub.organizations().test_iam_permissions(request, opt.value_of("resource").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _organizations_update(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "organization-id" => Some(("organizationId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "owner.directory-customer-id" => Some(("owner.directoryCustomerId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "display-name" => Some(("displayName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["directory-customer-id", "display-name", "organization-id", "owner"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::Organization = json::value::from_value(object).unwrap(); + let mut call = self.hub.organizations().update(request, opt.value_of("organization-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + fn _projects_create(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) -> Result<(), DoitError> { @@ -69,13 +525,15 @@ impl<'n, 'a> Engine<'n, 'a> { let type_info: Option<(&'static str, JsonTypeInfo)> = match &temp_cursor.to_string()[..] { "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "parent.type" => Some(("parent.type", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "parent.id" => Some(("parent.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "project-id" => Some(("projectId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "labels" => Some(("labels", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Map })), "project-number" => Some(("projectNumber", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "lifecycle-state" => Some(("lifecycleState", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "create-time" => Some(("createTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), _ => { - let suggestion = FieldCursor::did_you_mean(key, &vec!["create-time", "labels", "lifecycle-state", "name", "project-id", "project-number"]); + let suggestion = FieldCursor::did_you_mean(key, &vec!["create-time", "id", "labels", "lifecycle-state", "name", "parent", "project-id", "project-number", "type"]); err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); None } @@ -239,6 +697,90 @@ impl<'n, 'a> Engine<'n, 'a> { } } + fn _projects_get_iam_policy(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec![]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::GetIamPolicyRequest = json::value::from_value(object).unwrap(); + let mut call = self.hub.projects().get_iam_policy(request, opt.value_of("resource").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + fn _projects_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) -> Result<(), DoitError> { let mut call = self.hub.projects().list(); @@ -301,6 +843,177 @@ impl<'n, 'a> Engine<'n, 'a> { } } + fn _projects_set_iam_policy(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "policy.version" => Some(("policy.version", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "policy.etag" => Some(("policy.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["etag", "policy", "version"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::SetIamPolicyRequest = json::value::from_value(object).unwrap(); + let mut call = self.hub.projects().set_iam_policy(request, opt.value_of("resource").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _projects_test_iam_permissions(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "permissions" => Some(("permissions", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["permissions"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::TestIamPermissionsRequest = json::value::from_value(object).unwrap(); + let mut call = self.hub.projects().test_iam_permissions(request, opt.value_of("resource").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + fn _projects_undelete(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) -> Result<(), DoitError> { let mut call = self.hub.projects().undelete(opt.value_of("project-id").unwrap_or("")); @@ -377,13 +1090,15 @@ impl<'n, 'a> Engine<'n, 'a> { let type_info: Option<(&'static str, JsonTypeInfo)> = match &temp_cursor.to_string()[..] { "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "parent.type" => Some(("parent.type", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "parent.id" => Some(("parent.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "project-id" => Some(("projectId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "labels" => Some(("labels", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Map })), "project-number" => Some(("projectNumber", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "lifecycle-state" => Some(("lifecycleState", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "create-time" => Some(("createTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), _ => { - let suggestion = FieldCursor::did_you_mean(key, &vec!["create-time", "labels", "lifecycle-state", "name", "project-id", "project-number"]); + let suggestion = FieldCursor::did_you_mean(key, &vec!["create-time", "id", "labels", "lifecycle-state", "name", "parent", "project-id", "project-number", "type"]); err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); None } @@ -448,6 +1163,32 @@ impl<'n, 'a> Engine<'n, 'a> { let mut call_result: Result<(), DoitError> = Ok(()); let mut err_opt: Option = None; match self.opt.subcommand() { + ("organizations", Some(opt)) => { + match opt.subcommand() { + ("get", Some(opt)) => { + call_result = self._organizations_get(opt, dry_run, &mut err); + }, + ("get-iam-policy", Some(opt)) => { + call_result = self._organizations_get_iam_policy(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._organizations_list(opt, dry_run, &mut err); + }, + ("set-iam-policy", Some(opt)) => { + call_result = self._organizations_set_iam_policy(opt, dry_run, &mut err); + }, + ("test-iam-permissions", Some(opt)) => { + call_result = self._organizations_test_iam_permissions(opt, dry_run, &mut err); + }, + ("update", Some(opt)) => { + call_result = self._organizations_update(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("organizations".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, ("projects", Some(opt)) => { match opt.subcommand() { ("create", Some(opt)) => { @@ -459,9 +1200,18 @@ impl<'n, 'a> Engine<'n, 'a> { ("get", Some(opt)) => { call_result = self._projects_get(opt, dry_run, &mut err); }, + ("get-iam-policy", Some(opt)) => { + call_result = self._projects_get_iam_policy(opt, dry_run, &mut err); + }, ("list", Some(opt)) => { call_result = self._projects_list(opt, dry_run, &mut err); }, + ("set-iam-policy", Some(opt)) => { + call_result = self._projects_set_iam_policy(opt, dry_run, &mut err); + }, + ("test-iam-permissions", Some(opt)) => { + call_result = self._projects_test_iam_permissions(opt, dry_run, &mut err); + }, ("undelete", Some(opt)) => { call_result = self._projects_undelete(opt, dry_run, &mut err); }, @@ -560,7 +1310,160 @@ impl<'n, 'a> Engine<'n, 'a> { fn main() { let mut exit_status = 0i32; let arg_data = [ - ("projects", "methods: 'create', 'delete', 'get', 'list', 'undelete' and 'update'", vec![ + ("organizations", "methods: 'get', 'get-iam-policy', 'list', 'set-iam-policy', 'test-iam-permissions' and 'update'", vec![ + ("get", + Some(r##"Fetches an Organization resource by id."##), + "Details at http://byron.github.io/google-apis-rs/google_cloudresourcemanager1_beta1_cli/organizations_get", + vec![ + (Some(r##"organization-id"##), + None, + Some(r##"The id of the Organization resource to fetch."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("get-iam-policy", + Some(r##"Gets the access control policy for a Organization resource. May be empty if no such policy or resource exists."##), + "Details at http://byron.github.io/google-apis-rs/google_cloudresourcemanager1_beta1_cli/organizations_get-iam-policy", + vec![ + (Some(r##"resource"##), + None, + Some(r##"REQUIRED: The resource for which policy is being requested. Resource is usually specified as a path, such as, `projects/{project}`."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Query Organization resources."##), + "Details at http://byron.github.io/google-apis-rs/google_cloudresourcemanager1_beta1_cli/organizations_list", + vec![ + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("set-iam-policy", + Some(r##"Sets the access control policy on a Organization resource. Replaces any existing policy."##), + "Details at http://byron.github.io/google-apis-rs/google_cloudresourcemanager1_beta1_cli/organizations_set-iam-policy", + vec![ + (Some(r##"resource"##), + None, + Some(r##"REQUIRED: The resource for which policy is being specified. `resource` is usually specified as a path, such as, `projects/{project}/zones/{zone}/disks/{disk}`."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("test-iam-permissions", + Some(r##"Returns permissions that a caller has on the specified Organization."##), + "Details at http://byron.github.io/google-apis-rs/google_cloudresourcemanager1_beta1_cli/organizations_test-iam-permissions", + vec![ + (Some(r##"resource"##), + None, + Some(r##"REQUIRED: The resource for which policy detail is being requested. `resource` is usually specified as a path, such as, `projects/{project}`."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("update", + Some(r##"Updates an Organization resource."##), + "Details at http://byron.github.io/google-apis-rs/google_cloudresourcemanager1_beta1_cli/organizations_update", + vec![ + (Some(r##"organization-id"##), + None, + Some(r##"An immutable id for the Organization that is assigned on creation. This should be omitted when creating a new Organization. This field is read-only."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("projects", "methods: 'create', 'delete', 'get', 'get-iam-policy', 'list', 'set-iam-policy', 'test-iam-permissions', 'undelete' and 'update'", vec![ ("create", Some(r##"Creates a project resource. Initially, the project resource is owned by its creator exclusively. The creator can later grant permission to others to read or update the project. Several APIs are activated automatically for the project, including Google Cloud Storage."##), "Details at http://byron.github.io/google-apis-rs/google_cloudresourcemanager1_beta1_cli/projects_create", @@ -621,6 +1524,34 @@ fn main() { Some(false), Some(true)), + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("get-iam-policy", + Some(r##"Returns the IAM access control policy for specified project."##), + "Details at http://byron.github.io/google-apis-rs/google_cloudresourcemanager1_beta1_cli/projects_get-iam-policy", + vec![ + (Some(r##"resource"##), + None, + Some(r##"REQUIRED: The resource for which policy is being requested. Resource is usually specified as a path, such as, `projects/{project}`."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + (Some(r##"out"##), Some(r##"o"##), Some(r##"Specify the file into which to write the program's output"##), @@ -637,6 +1568,62 @@ fn main() { Some(false), Some(true)), + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("set-iam-policy", + Some(r##"Sets the IAM access control policy for the specified project. We do not currently support 'domain:' prefixed members in a Binding of a Policy. Calling this method requires enabling the App Engine Admin API."##), + "Details at http://byron.github.io/google-apis-rs/google_cloudresourcemanager1_beta1_cli/projects_set-iam-policy", + vec![ + (Some(r##"resource"##), + None, + Some(r##"REQUIRED: The resource for which policy is being specified. `resource` is usually specified as a path, such as, `projects/{project}/zones/{zone}/disks/{disk}`."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("test-iam-permissions", + Some(r##"Tests the specified permissions against the IAM access control policy for the specified project."##), + "Details at http://byron.github.io/google-apis-rs/google_cloudresourcemanager1_beta1_cli/projects_test-iam-permissions", + vec![ + (Some(r##"resource"##), + None, + Some(r##"REQUIRED: The resource for which policy detail is being requested. `resource` is usually specified as a path, such as, `projects/{project}`."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + (Some(r##"out"##), Some(r##"o"##), Some(r##"Specify the file into which to write the program's output"##), @@ -699,7 +1686,7 @@ fn main() { let mut app = App::new("cloudresourcemanager1-beta1") .author("Sebastian Thiel ") - .version("0.3.2+20150711") + .version("0.3.2+20150909") .about("The Google Cloud Resource Manager API provides methods for creating, reading, and updating of project metadata.") .after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_cloudresourcemanager1_beta1_cli") .arg(Arg::with_name("url") diff --git a/gen/cloudresourcemanager1_beta1/Cargo.toml b/gen/cloudresourcemanager1_beta1/Cargo.toml index 649dc21428..db8cbf3d7b 100644 --- a/gen/cloudresourcemanager1_beta1/Cargo.toml +++ b/gen/cloudresourcemanager1_beta1/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-cloudresourcemanager1_beta1" -version = "0.1.9+20150711" +version = "0.1.9+20150909" authors = ["Sebastian Thiel "] description = "A complete library to interact with cloudresourcemanager (protocol v1beta1)" repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/cloudresourcemanager1_beta1" diff --git a/gen/cloudresourcemanager1_beta1/README.md b/gen/cloudresourcemanager1_beta1/README.md index 34792babe8..556cd4de9f 100644 --- a/gen/cloudresourcemanager1_beta1/README.md +++ b/gen/cloudresourcemanager1_beta1/README.md @@ -5,7 +5,7 @@ DO NOT EDIT ! --> The `google-cloudresourcemanager1_beta1` library allows access to all features of the *Google cloudresourcemanager* service. -This documentation was generated from *cloudresourcemanager* crate version *0.1.9+20150711*, where *20150711* is the exact revision of the *cloudresourcemanager:v1beta1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +This documentation was generated from *cloudresourcemanager* crate version *0.1.9+20150909*, where *20150909* is the exact revision of the *cloudresourcemanager:v1beta1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. Everything else about the *cloudresourcemanager* *v1_beta1* API can be found at the [official documentation site](https://cloud.google.com/resource-manager). @@ -13,8 +13,10 @@ Everything else about the *cloudresourcemanager* *v1_beta1* API can be found at Handle the following *Resources* with ease from the central [hub](http://byron.github.io/google-apis-rs/google_cloudresourcemanager1_beta1/struct.Cloudresourcemanager.html) ... +* [organizations](http://byron.github.io/google-apis-rs/google_cloudresourcemanager1_beta1/struct.Organization.html) + * [*get*](http://byron.github.io/google-apis-rs/google_cloudresourcemanager1_beta1/struct.OrganizationGetCall.html), [*get iam policy*](http://byron.github.io/google-apis-rs/google_cloudresourcemanager1_beta1/struct.OrganizationGetIamPolicyCall.html), [*list*](http://byron.github.io/google-apis-rs/google_cloudresourcemanager1_beta1/struct.OrganizationListCall.html), [*set iam policy*](http://byron.github.io/google-apis-rs/google_cloudresourcemanager1_beta1/struct.OrganizationSetIamPolicyCall.html), [*test iam permissions*](http://byron.github.io/google-apis-rs/google_cloudresourcemanager1_beta1/struct.OrganizationTestIamPermissionCall.html) and [*update*](http://byron.github.io/google-apis-rs/google_cloudresourcemanager1_beta1/struct.OrganizationUpdateCall.html) * [projects](http://byron.github.io/google-apis-rs/google_cloudresourcemanager1_beta1/struct.Project.html) - * [*create*](http://byron.github.io/google-apis-rs/google_cloudresourcemanager1_beta1/struct.ProjectCreateCall.html), [*delete*](http://byron.github.io/google-apis-rs/google_cloudresourcemanager1_beta1/struct.ProjectDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google_cloudresourcemanager1_beta1/struct.ProjectGetCall.html), [*list*](http://byron.github.io/google-apis-rs/google_cloudresourcemanager1_beta1/struct.ProjectListCall.html), [*undelete*](http://byron.github.io/google-apis-rs/google_cloudresourcemanager1_beta1/struct.ProjectUndeleteCall.html) and [*update*](http://byron.github.io/google-apis-rs/google_cloudresourcemanager1_beta1/struct.ProjectUpdateCall.html) + * [*create*](http://byron.github.io/google-apis-rs/google_cloudresourcemanager1_beta1/struct.ProjectCreateCall.html), [*delete*](http://byron.github.io/google-apis-rs/google_cloudresourcemanager1_beta1/struct.ProjectDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google_cloudresourcemanager1_beta1/struct.ProjectGetCall.html), [*get iam policy*](http://byron.github.io/google-apis-rs/google_cloudresourcemanager1_beta1/struct.ProjectGetIamPolicyCall.html), [*list*](http://byron.github.io/google-apis-rs/google_cloudresourcemanager1_beta1/struct.ProjectListCall.html), [*set iam policy*](http://byron.github.io/google-apis-rs/google_cloudresourcemanager1_beta1/struct.ProjectSetIamPolicyCall.html), [*test iam permissions*](http://byron.github.io/google-apis-rs/google_cloudresourcemanager1_beta1/struct.ProjectTestIamPermissionCall.html), [*undelete*](http://byron.github.io/google-apis-rs/google_cloudresourcemanager1_beta1/struct.ProjectUndeleteCall.html) and [*update*](http://byron.github.io/google-apis-rs/google_cloudresourcemanager1_beta1/struct.ProjectUpdateCall.html) @@ -47,10 +49,13 @@ let r = hub.resource().activity(...).doit() Or specifically ... ```ignore -let r = hub.projects().delete(...).doit() +let r = hub.projects().test_iam_permissions(...).doit() let r = hub.projects().undelete(...).doit() +let r = hub.projects().set_iam_policy(...).doit() let r = hub.projects().get(...).doit() let r = hub.projects().update(...).doit() +let r = hub.projects().get_iam_policy(...).doit() +let r = hub.projects().delete(...).doit() let r = hub.projects().create(...).doit() let r = hub.projects().list(...).doit() ``` diff --git a/gen/cloudresourcemanager1_beta1/src/lib.rs b/gen/cloudresourcemanager1_beta1/src/lib.rs index c4cba7dc7e..9498c9b3c8 100644 --- a/gen/cloudresourcemanager1_beta1/src/lib.rs +++ b/gen/cloudresourcemanager1_beta1/src/lib.rs @@ -2,7 +2,7 @@ // This file was generated automatically from 'src/mako/api/lib.rs.mako' // DO NOT EDIT ! -//! This documentation was generated from *cloudresourcemanager* crate version *0.1.9+20150711*, where *20150711* is the exact revision of the *cloudresourcemanager:v1beta1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +//! This documentation was generated from *cloudresourcemanager* crate version *0.1.9+20150909*, where *20150909* is the exact revision of the *cloudresourcemanager:v1beta1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. //! //! Everything else about the *cloudresourcemanager* *v1_beta1* API can be found at the //! [official documentation site](https://cloud.google.com/resource-manager). @@ -11,8 +11,10 @@ //! //! Handle the following *Resources* with ease from the central [hub](struct.Cloudresourcemanager.html) ... //! +//! * [organizations](struct.Organization.html) +//! * [*get*](struct.OrganizationGetCall.html), [*get iam policy*](struct.OrganizationGetIamPolicyCall.html), [*list*](struct.OrganizationListCall.html), [*set iam policy*](struct.OrganizationSetIamPolicyCall.html), [*test iam permissions*](struct.OrganizationTestIamPermissionCall.html) and [*update*](struct.OrganizationUpdateCall.html) //! * [projects](struct.Project.html) -//! * [*create*](struct.ProjectCreateCall.html), [*delete*](struct.ProjectDeleteCall.html), [*get*](struct.ProjectGetCall.html), [*list*](struct.ProjectListCall.html), [*undelete*](struct.ProjectUndeleteCall.html) and [*update*](struct.ProjectUpdateCall.html) +//! * [*create*](struct.ProjectCreateCall.html), [*delete*](struct.ProjectDeleteCall.html), [*get*](struct.ProjectGetCall.html), [*get iam policy*](struct.ProjectGetIamPolicyCall.html), [*list*](struct.ProjectListCall.html), [*set iam policy*](struct.ProjectSetIamPolicyCall.html), [*test iam permissions*](struct.ProjectTestIamPermissionCall.html), [*undelete*](struct.ProjectUndeleteCall.html) and [*update*](struct.ProjectUpdateCall.html) //! //! //! @@ -47,10 +49,13 @@ //! Or specifically ... //! //! ```ignore -//! let r = hub.projects().delete(...).doit() +//! let r = hub.projects().test_iam_permissions(...).doit() //! let r = hub.projects().undelete(...).doit() +//! let r = hub.projects().set_iam_policy(...).doit() //! let r = hub.projects().get(...).doit() //! let r = hub.projects().update(...).doit() +//! let r = hub.projects().get_iam_policy(...).doit() +//! let r = hub.projects().delete(...).doit() //! let r = hub.projects().create(...).doit() //! let r = hub.projects().list(...).doit() //! ``` @@ -99,9 +104,9 @@ //! // execute the final call using `doit()`. //! // Values shown here are possibly random and not representative ! //! let result = hub.projects().list() -//! .page_token("sea") -//! .page_size(-90) -//! .filter("dolores") +//! .page_token("et") +//! .page_size(-41) +//! .filter("ipsum") //! .doit(); //! //! match result { diff --git a/gen/cloudresourcemanager1_beta1/src/lib.rs.in b/gen/cloudresourcemanager1_beta1/src/lib.rs.in index d53420666b..035a8654ca 100644 --- a/gen/cloudresourcemanager1_beta1/src/lib.rs.in +++ b/gen/cloudresourcemanager1_beta1/src/lib.rs.in @@ -133,6 +133,9 @@ impl<'a, C, A> Cloudresourcemanager } } + pub fn organizations(&'a self) -> OrganizationMethods<'a, C, A> { + OrganizationMethods { hub: &self } + } pub fn projects(&'a self) -> ProjectMethods<'a, C, A> { ProjectMethods { hub: &self } } @@ -159,17 +162,22 @@ impl<'a, C, A> Cloudresourcemanager /// This type is used in activities, which are methods you may call on this type or where 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 projects](struct.ProjectDeleteCall.html) (none) +/// * [test iam permissions projects](struct.ProjectTestIamPermissionCall.html) (none) /// * [undelete projects](struct.ProjectUndeleteCall.html) (none) +/// * [set iam policy projects](struct.ProjectSetIamPolicyCall.html) (none) /// * [get projects](struct.ProjectGetCall.html) (response) /// * [update projects](struct.ProjectUpdateCall.html) (request|response) +/// * [get iam policy projects](struct.ProjectGetIamPolicyCall.html) (none) +/// * [delete projects](struct.ProjectDeleteCall.html) (none) /// * [create projects](struct.ProjectCreateCall.html) (request|response) /// * [list projects](struct.ProjectListCall.html) (none) /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct Project { - /// The user-assigned name of the project. This field is optional and can remain unset. Allowed characters are: lowercase and uppercase letters, numbers, hyphen, single-quote, double-quote, space, and exclamation point. Example: My Project Read-write. + /// The user-assigned name of the project. It must be 4 to 30 characters. Allowed characters are: lowercase and uppercase letters, numbers, hyphen, single-quote, double-quote, space, and exclamation point. Example: My Project Read-write. pub name: Option, + /// An optional reference to a parent Resource. The only supported parent type is "organization". Once set, the parent cannot be modified. Read-write. + pub parent: Option, /// The unique, user-assigned ID of the project. It must be 6 to 30 lowercase letters, digits, or hyphens. It must start with a letter. Trailing hyphens are prohibited. Example: tokyo-rain-123 Read-only after creation. #[serde(rename="projectId")] pub project_id: Option, @@ -191,6 +199,187 @@ impl Resource for Project {} impl ResponseResult for Project {} +/// Response message for `TestIamPermissions` 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*). +/// +/// * [test iam permissions organizations](struct.OrganizationTestIamPermissionCall.html) (response) +/// * [test iam permissions projects](struct.ProjectTestIamPermissionCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct TestIamPermissionsResponse { + /// A subset of `TestPermissionsRequest.permissions` that the caller is allowed. + pub permissions: Option>, +} + +impl ResponseResult for TestIamPermissionsResponse {} + + +/// Request message for `GetIamPolicy` 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*). +/// +/// * [get iam policy projects](struct.ProjectGetIamPolicyCall.html) (request) +/// * [get iam policy organizations](struct.OrganizationGetIamPolicyCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct GetIamPolicyRequest; + +impl RequestValue for GetIamPolicyRequest {} + + +/// Request message for `TestIamPermissions` 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*). +/// +/// * [test iam permissions organizations](struct.OrganizationTestIamPermissionCall.html) (request) +/// * [test iam permissions projects](struct.ProjectTestIamPermissionCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct TestIamPermissionsRequest { + /// The set of permissions to check for the `resource`. Permissions with wildcards (such as '*' or 'storage.*') are not allowed. + pub permissions: Option>, +} + +impl RequestValue for TestIamPermissionsRequest {} + + +/// Request message for `SetIamPolicy` 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*). +/// +/// * [set iam policy projects](struct.ProjectSetIamPolicyCall.html) (request) +/// * [set iam policy organizations](struct.OrganizationSetIamPolicyCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct SetIamPolicyRequest { + /// REQUIRED: The complete policy to be applied to the `resource`. The size of the policy is limited to a few 10s of KB. An empty policy is a valid policy but certain Cloud Platform services (such as Projects) might reject them. + pub policy: Option, +} + +impl RequestValue for SetIamPolicyRequest {} + + +/// A container to reference an id for any resource type. A 'resource' in Google Cloud Platform is a generic term for something you (a developer) may want to interact with through one of our API's. Some examples are an AppEngine app, a Compute Engine instance, Cloud SQL database, ... +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ResourceId { + /// Required field representing the resource type this id is for. At present, the only valid type is "organization". + #[serde(rename="type")] + pub type_: Option, + /// Required field for the type-specific id. This should correspond to the id used in the type-specific API's. + pub id: Option, +} + +impl Part for ResourceId {} + + +/// Associates `members` with a `role`. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Binding { + /// Role that is assigned to `members`. For example, `roles/viewer`, `roles/editor`, or `roles/owner`. Required + pub role: Option, + /// Specifies the identities requesting access for a Cloud Platform resource. `members` can have the following formats: * `allUsers`: A special identifier that represents anyone who is on the internet; with or without a Google account. * `allAuthenticatedUsers`: A special identifier that represents anyone who is authenticated with a Google account or a service account. * `user:{emailid}`: An email address that represents a specific Google account. For example, `alice@gmail.com` or `joe@example.com`. * `serviceAccount:{emailid}`: An email address that represents a service account. For example, `my-other-app@appspot.gserviceaccount.com`. * `group:{emailid}`: An email address that represents a Google group. For example, `admins@example.com`. * `domain:{domain}`: A Google Apps domain name that represents all the users of that domain. For example, `google.com` or `example.com`. + pub members: Option>, +} + +impl Part for Binding {} + + +/// The response returned from the ListOrganizations 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*). +/// +/// * [list organizations](struct.OrganizationListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ListOrganizationsResponse { + /// A pagination token to be used to retrieve the next page of results. If the result is too large to fit within the page size specified in the request, this field will be set with a token that can be used to fetch the next page of results. If this field is empty, it indicates that this response contains the last page of results. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// The list of Organizations that matched the list query, possibly paginated. + pub organizations: Option>, +} + +impl ResponseResult for ListOrganizationsResponse {} + + +/// Defines an Identity and Access Management (IAM) policy. It is used to specify access control policies for Cloud Platform resources. A `Policy` consists of a list of `bindings`. A `Binding` binds a list of `members` to a `role`, where the members can be user accounts, Google groups, Google domains, and service accounts. A `role` is a named list of permissions defined by IAM. **Example** ``` { "bindings": [ { "role": "roles/owner", "members": [ "user:mike@example.com", "group:admins@example.com", "domain:google.com", "serviceAccount:my-other-app@appspot.gserviceaccount.com"] }, { "role": "roles/viewer", "members": ["user:sean@example.com"] } ] } ``` For a description of IAM and its features, see the [IAM developer's guide][https://cloud.google.com/iam]. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where 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 iam policy projects](struct.ProjectSetIamPolicyCall.html) (response) +/// * [set iam policy organizations](struct.OrganizationSetIamPolicyCall.html) (response) +/// * [get iam policy projects](struct.ProjectGetIamPolicyCall.html) (response) +/// * [get iam policy organizations](struct.OrganizationGetIamPolicyCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Policy { + /// Associates a list of `members` to a `role`. Multiple `bindings` must not be specified for the same `role`. `bindings` with no members will result in an error. + pub bindings: Option>, + /// Version of the `Policy`. The default version is 0. + pub version: Option, + /// Can be used to perform a read-modify-write. + pub etag: Option, +} + +impl ResponseResult for Policy {} + + +/// The root node in the resource hierarchy to which a particular entity's (e.g., company) resources belong. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where 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 iam policy organizations](struct.OrganizationSetIamPolicyCall.html) (none) +/// * [get iam policy organizations](struct.OrganizationGetIamPolicyCall.html) (none) +/// * [test iam permissions organizations](struct.OrganizationTestIamPermissionCall.html) (none) +/// * [get organizations](struct.OrganizationGetCall.html) (response) +/// * [update organizations](struct.OrganizationUpdateCall.html) (request|response) +/// * [list organizations](struct.OrganizationListCall.html) (none) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Organization { + /// An immutable id for the Organization that is assigned on creation. This should be omitted when creating a new Organization. This field is read-only. + #[serde(rename="organizationId")] + pub organization_id: Option, + /// The owner of this Organization. The owner should be specified upon creation. Once set, it cannot be changed. This field is required. + pub owner: Option, + /// A friendly string to be used to refer to the Organization in the UI. This field is required. + #[serde(rename="displayName")] + pub display_name: Option, +} + +impl RequestValue for Organization {} +impl Resource for Organization {} +impl ResponseResult for Organization {} + + /// A page of the response received from the [ListProjects][google.cloudresourcemanager.projects.v1beta1.DeveloperProjects.ListProjects] method. A paginated response where more pages are available has `next_page_token` set. This token can be used in a subsequent request to retrieve the next request page. /// /// # Activities @@ -228,11 +417,174 @@ pub struct Empty; impl ResponseResult for Empty {} +/// The entity that owns an Organization. The lifetime of the Organization and all of its descendants are bound to the OrganizationOwner. If the OrganizationOwner is deleted, the Organization and all its descendants will be deleted. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct OrganizationOwner { + /// The Google for Work customer id used in the Directory API. + #[serde(rename="directoryCustomerId")] + pub directory_customer_id: Option, +} + +impl Part for OrganizationOwner {} + + // ################### // MethodBuilders ### // ################# +/// A builder providing access to all methods supported on *organization* resources. +/// It is not used directly, but through the `Cloudresourcemanager` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate yup_oauth2 as oauth2; +/// extern crate google_cloudresourcemanager1_beta1 as cloudresourcemanager1_beta1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use cloudresourcemanager1_beta1::Cloudresourcemanager; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Cloudresourcemanager::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get(...)`, `get_iam_policy(...)`, `list(...)`, `set_iam_policy(...)`, `test_iam_permissions(...)` and `update(...)` +/// // to build up your call. +/// let rb = hub.organizations(); +/// # } +/// ``` +pub struct OrganizationMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Cloudresourcemanager, +} + +impl<'a, C, A> MethodsBuilder for OrganizationMethods<'a, C, A> {} + +impl<'a, C, A> OrganizationMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Sets the access control policy on a Organization resource. Replaces any existing policy. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `resource` - REQUIRED: The resource for which policy is being specified. `resource` is usually specified as a path, such as, `projects/{project}/zones/{zone}/disks/{disk}`. + pub fn set_iam_policy(&self, request: SetIamPolicyRequest, resource: &str) -> OrganizationSetIamPolicyCall<'a, C, A> { + OrganizationSetIamPolicyCall { + hub: self.hub, + _request: request, + _resource: resource.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets the access control policy for a Organization resource. May be empty if no such policy or resource exists. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `resource` - REQUIRED: The resource for which policy is being requested. Resource is usually specified as a path, such as, `projects/{project}`. + pub fn get_iam_policy(&self, request: GetIamPolicyRequest, resource: &str) -> OrganizationGetIamPolicyCall<'a, C, A> { + OrganizationGetIamPolicyCall { + hub: self.hub, + _request: request, + _resource: resource.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Returns permissions that a caller has on the specified Organization. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `resource` - REQUIRED: The resource for which policy detail is being requested. `resource` is usually specified as a path, such as, `projects/{project}`. + pub fn test_iam_permissions(&self, request: TestIamPermissionsRequest, resource: &str) -> OrganizationTestIamPermissionCall<'a, C, A> { + OrganizationTestIamPermissionCall { + hub: self.hub, + _request: request, + _resource: resource.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Fetches an Organization resource by id. + /// + /// # Arguments + /// + /// * `organizationId` - The id of the Organization resource to fetch. + pub fn get(&self, organization_id: &str) -> OrganizationGetCall<'a, C, A> { + OrganizationGetCall { + hub: self.hub, + _organization_id: organization_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 Organization resource. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `organizationId` - An immutable id for the Organization that is assigned on creation. This should be omitted when creating a new Organization. This field is read-only. + pub fn update(&self, request: Organization, organization_id: &str) -> OrganizationUpdateCall<'a, C, A> { + OrganizationUpdateCall { + hub: self.hub, + _request: request, + _organization_id: organization_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Query Organization resources. + pub fn list(&self) -> OrganizationListCall<'a, C, A> { + OrganizationListCall { + hub: self.hub, + _page_token: Default::default(), + _page_size: 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 `Cloudresourcemanager` hub. /// @@ -256,7 +608,7 @@ impl ResponseResult for Empty {} /// ::default(), None); /// let mut hub = Cloudresourcemanager::new(hyper::Client::new(), auth); /// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* -/// // like `create(...)`, `delete(...)`, `get(...)`, `list(...)`, `undelete(...)` and `update(...)` +/// // like `create(...)`, `delete(...)`, `get(...)`, `get_iam_policy(...)`, `list(...)`, `set_iam_policy(...)`, `test_iam_permissions(...)`, `undelete(...)` and `update(...)` /// // to build up your call. /// let rb = hub.projects(); /// # } @@ -273,15 +625,17 @@ impl<'a, C, A> ProjectMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Marks the project identified by the specified `project_id` (for example, `my-project-123`) for deletion. This method will only affect the project if the following criteria are met: + The project does not have a billing account associated with it. + The project has a lifecycle state of [ACTIVE][google.cloudresourcemanager.projects.v1beta1.LifecycleState.ACTIVE]. This method changes the project's lifecycle state from [ACTIVE][google.cloudresourcemanager.projects.v1beta1.LifecycleState.ACTIVE] to [DELETE_REQUESTED] [google.cloudresourcemanager.projects.v1beta1.LifecycleState.DELETE_REQUESTED]. The deletion starts at an unspecified time, at which point the lifecycle state changes to [DELETE_IN_PROGRESS] [google.cloudresourcemanager.projects.v1beta1.LifecycleState.DELETE_IN_PROGRESS]. Until the deletion completes, you can check the lifecycle state checked by retrieving the project with [GetProject] [google.cloudresourcemanager.projects.v1beta1.DeveloperProjects.GetProject], and the project remains visible to [ListProjects] [google.cloudresourcemanager.projects.v1beta1.DeveloperProjects.ListProjects]. However, you cannot update the project. After the deletion completes, the project is not retrievable by the [GetProject] [google.cloudresourcemanager.projects.v1beta1.DeveloperProjects.GetProject] and [ListProjects] [google.cloudresourcemanager.projects.v1beta1.DeveloperProjects.ListProjects] methods. The caller must have modify permissions for this project. + /// Tests the specified permissions against the IAM access control policy for the specified project. /// /// # Arguments /// - /// * `projectId` - The project ID (for example, `foo-bar-123`). Required. - pub fn delete(&self, project_id: &str) -> ProjectDeleteCall<'a, C, A> { - ProjectDeleteCall { + /// * `request` - No description provided. + /// * `resource` - REQUIRED: The resource for which policy detail is being requested. `resource` is usually specified as a path, such as, `projects/{project}`. + pub fn test_iam_permissions(&self, request: TestIamPermissionsRequest, resource: &str) -> ProjectTestIamPermissionCall<'a, C, A> { + ProjectTestIamPermissionCall { hub: self.hub, - _project_id: project_id.to_string(), + _request: request, + _resource: resource.to_string(), _delegate: Default::default(), _scopes: Default::default(), _additional_params: Default::default(), @@ -305,6 +659,42 @@ impl<'a, C, A> ProjectMethods<'a, C, A> { } } + /// Create a builder to help you perform the following task: + /// + /// Creates a project resource. Initially, the project resource is owned by its creator exclusively. The creator can later grant permission to others to read or update the project. Several APIs are activated automatically for the project, including Google Cloud Storage. + /// + /// # Arguments + /// + /// * `request` - No description provided. + pub fn create(&self, request: Project) -> ProjectCreateCall<'a, C, A> { + ProjectCreateCall { + hub: self.hub, + _request: request, + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Sets the IAM access control policy for the specified project. We do not currently support 'domain:' prefixed members in a Binding of a Policy. Calling this method requires enabling the App Engine Admin API. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `resource` - REQUIRED: The resource for which policy is being specified. `resource` is usually specified as a path, such as, `projects/{project}/zones/{zone}/disks/{disk}`. + pub fn set_iam_policy(&self, request: SetIamPolicyRequest, resource: &str) -> ProjectSetIamPolicyCall<'a, C, A> { + ProjectSetIamPolicyCall { + hub: self.hub, + _request: request, + _resource: resource.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + /// Create a builder to help you perform the following task: /// /// Retrieves the project identified by the specified `project_id` (for example, `my-project-123`). The caller must have read permissions for this project. @@ -343,15 +733,34 @@ impl<'a, C, A> ProjectMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Creates a project resource. Initially, the project resource is owned by its creator exclusively. The creator can later grant permission to others to read or update the project. Several APIs are activated automatically for the project, including Google Cloud Storage. + /// Returns the IAM access control policy for specified project. /// /// # Arguments /// /// * `request` - No description provided. - pub fn create(&self, request: Project) -> ProjectCreateCall<'a, C, A> { - ProjectCreateCall { + /// * `resource` - REQUIRED: The resource for which policy is being requested. Resource is usually specified as a path, such as, `projects/{project}`. + pub fn get_iam_policy(&self, request: GetIamPolicyRequest, resource: &str) -> ProjectGetIamPolicyCall<'a, C, A> { + ProjectGetIamPolicyCall { hub: self.hub, _request: request, + _resource: resource.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Marks the project identified by the specified `project_id` (for example, `my-project-123`) for deletion. This method will only affect the project if the following criteria are met: + The project does not have a billing account associated with it. + The project has a lifecycle state of [ACTIVE][google.cloudresourcemanager.projects.v1beta1.LifecycleState.ACTIVE]. This method changes the project's lifecycle state from [ACTIVE][google.cloudresourcemanager.projects.v1beta1.LifecycleState.ACTIVE] to [DELETE_REQUESTED] [google.cloudresourcemanager.projects.v1beta1.LifecycleState.DELETE_REQUESTED]. The deletion starts at an unspecified time, at which point the lifecycle state changes to [DELETE_IN_PROGRESS] [google.cloudresourcemanager.projects.v1beta1.LifecycleState.DELETE_IN_PROGRESS]. Until the deletion completes, you can check the lifecycle state checked by retrieving the project with [GetProject] [google.cloudresourcemanager.projects.v1beta1.DeveloperProjects.GetProject], and the project remains visible to [ListProjects] [google.cloudresourcemanager.projects.v1beta1.DeveloperProjects.ListProjects]. However, you cannot update the project. After the deletion completes, the project is not retrievable by the [GetProject] [google.cloudresourcemanager.projects.v1beta1.DeveloperProjects.GetProject] and [ListProjects] [google.cloudresourcemanager.projects.v1beta1.DeveloperProjects.ListProjects] methods. The caller must have modify permissions for this project. + /// + /// # Arguments + /// + /// * `projectId` - The project ID (for example, `foo-bar-123`). Required. + pub fn delete(&self, project_id: &str) -> ProjectDeleteCall<'a, C, A> { + ProjectDeleteCall { + hub: self.hub, + _project_id: project_id.to_string(), _delegate: Default::default(), _scopes: Default::default(), _additional_params: Default::default(), @@ -382,10 +791,829 @@ impl<'a, C, A> ProjectMethods<'a, C, A> { // CallBuilders ### // ################# -/// Marks the project identified by the specified `project_id` (for example, `my-project-123`) for deletion. This method will only affect the project if the following criteria are met: + The project does not have a billing account associated with it. + The project has a lifecycle state of [ACTIVE][google.cloudresourcemanager.projects.v1beta1.LifecycleState.ACTIVE]. This method changes the project's lifecycle state from [ACTIVE][google.cloudresourcemanager.projects.v1beta1.LifecycleState.ACTIVE] to [DELETE_REQUESTED] [google.cloudresourcemanager.projects.v1beta1.LifecycleState.DELETE_REQUESTED]. The deletion starts at an unspecified time, at which point the lifecycle state changes to [DELETE_IN_PROGRESS] [google.cloudresourcemanager.projects.v1beta1.LifecycleState.DELETE_IN_PROGRESS]. Until the deletion completes, you can check the lifecycle state checked by retrieving the project with [GetProject] [google.cloudresourcemanager.projects.v1beta1.DeveloperProjects.GetProject], and the project remains visible to [ListProjects] [google.cloudresourcemanager.projects.v1beta1.DeveloperProjects.ListProjects]. However, you cannot update the project. After the deletion completes, the project is not retrievable by the [GetProject] [google.cloudresourcemanager.projects.v1beta1.DeveloperProjects.GetProject] and [ListProjects] [google.cloudresourcemanager.projects.v1beta1.DeveloperProjects.ListProjects] methods. The caller must have modify permissions for this project. +/// Sets the access control policy on a Organization resource. Replaces any existing policy. /// -/// A builder for the *delete* method supported by a *project* resource. -/// It is not used directly, but through a `ProjectMethods` instance. +/// A builder for the *setIamPolicy* method supported by a *organization* resource. +/// It is not used directly, but through a `OrganizationMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_cloudresourcemanager1_beta1 as cloudresourcemanager1_beta1; +/// use cloudresourcemanager1_beta1::SetIamPolicyRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use cloudresourcemanager1_beta1::Cloudresourcemanager; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Cloudresourcemanager::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req = SetIamPolicyRequest::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.organizations().set_iam_policy(req, "resource") +/// .doit(); +/// # } +/// ``` +pub struct OrganizationSetIamPolicyCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Cloudresourcemanager, + _request: SetIamPolicyRequest, + _resource: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for OrganizationSetIamPolicyCall<'a, C, A> {} + +impl<'a, C, A> OrganizationSetIamPolicyCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Policy)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "cloudresourcemanager.organizations.setIamPolicy", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("resource", self._resource.to_string())); + for &field in ["alt", "resource"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://cloudresourcemanager.googleapis.com/v1beta1/organizations/{resource}:setIamPolicy".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{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(1); + for param_name in ["resource"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: SetIamPolicyRequest) -> OrganizationSetIamPolicyCall<'a, C, A> { + self._request = new_value; + self + } + /// REQUIRED: The resource for which policy is being specified. `resource` is usually specified as a path, such as, `projects/{project}/zones/{zone}/disks/{disk}`. + /// + /// 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. + pub fn resource(mut self, new_value: &str) -> OrganizationSetIamPolicyCall<'a, C, A> { + self._resource = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> OrganizationSetIamPolicyCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> OrganizationSetIamPolicyCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> OrganizationSetIamPolicyCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Gets the access control policy for a Organization resource. May be empty if no such policy or resource exists. +/// +/// A builder for the *getIamPolicy* method supported by a *organization* resource. +/// It is not used directly, but through a `OrganizationMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_cloudresourcemanager1_beta1 as cloudresourcemanager1_beta1; +/// use cloudresourcemanager1_beta1::GetIamPolicyRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use cloudresourcemanager1_beta1::Cloudresourcemanager; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Cloudresourcemanager::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req = GetIamPolicyRequest::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.organizations().get_iam_policy(req, "resource") +/// .doit(); +/// # } +/// ``` +pub struct OrganizationGetIamPolicyCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Cloudresourcemanager, + _request: GetIamPolicyRequest, + _resource: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for OrganizationGetIamPolicyCall<'a, C, A> {} + +impl<'a, C, A> OrganizationGetIamPolicyCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Policy)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "cloudresourcemanager.organizations.getIamPolicy", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("resource", self._resource.to_string())); + for &field in ["alt", "resource"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://cloudresourcemanager.googleapis.com/v1beta1/organizations/{resource}:getIamPolicy".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{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(1); + for param_name in ["resource"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: GetIamPolicyRequest) -> OrganizationGetIamPolicyCall<'a, C, A> { + self._request = new_value; + self + } + /// REQUIRED: The resource for which policy is being requested. Resource is usually specified as a path, such as, `projects/{project}`. + /// + /// 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. + pub fn resource(mut self, new_value: &str) -> OrganizationGetIamPolicyCall<'a, C, A> { + self._resource = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> OrganizationGetIamPolicyCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> OrganizationGetIamPolicyCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> OrganizationGetIamPolicyCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Returns permissions that a caller has on the specified Organization. +/// +/// A builder for the *testIamPermissions* method supported by a *organization* resource. +/// It is not used directly, but through a `OrganizationMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_cloudresourcemanager1_beta1 as cloudresourcemanager1_beta1; +/// use cloudresourcemanager1_beta1::TestIamPermissionsRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use cloudresourcemanager1_beta1::Cloudresourcemanager; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Cloudresourcemanager::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req = TestIamPermissionsRequest::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.organizations().test_iam_permissions(req, "resource") +/// .doit(); +/// # } +/// ``` +pub struct OrganizationTestIamPermissionCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Cloudresourcemanager, + _request: TestIamPermissionsRequest, + _resource: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for OrganizationTestIamPermissionCall<'a, C, A> {} + +impl<'a, C, A> OrganizationTestIamPermissionCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, TestIamPermissionsResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "cloudresourcemanager.organizations.testIamPermissions", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("resource", self._resource.to_string())); + for &field in ["alt", "resource"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://cloudresourcemanager.googleapis.com/v1beta1/organizations/{resource}:testIamPermissions".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{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(1); + for param_name in ["resource"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: TestIamPermissionsRequest) -> OrganizationTestIamPermissionCall<'a, C, A> { + self._request = new_value; + self + } + /// REQUIRED: The resource for which policy detail is being requested. `resource` is usually specified as a path, such as, `projects/{project}`. + /// + /// 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. + pub fn resource(mut self, new_value: &str) -> OrganizationTestIamPermissionCall<'a, C, A> { + self._resource = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> OrganizationTestIamPermissionCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> OrganizationTestIamPermissionCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> OrganizationTestIamPermissionCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Fetches an Organization resource by id. +/// +/// A builder for the *get* method supported by a *organization* resource. +/// It is not used directly, but through a `OrganizationMethods` instance. /// /// # Example /// @@ -408,27 +1636,27 @@ impl<'a, C, A> ProjectMethods<'a, C, A> { /// // You can configure optional parameters by calling 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().delete("projectId") +/// let result = hub.organizations().get("organizationId") /// .doit(); /// # } /// ``` -pub struct ProjectDeleteCall<'a, C, A> +pub struct OrganizationGetCall<'a, C, A> where C: 'a, A: 'a { hub: &'a Cloudresourcemanager, - _project_id: String, + _organization_id: String, _delegate: Option<&'a mut Delegate>, _additional_params: HashMap, _scopes: BTreeMap } -impl<'a, C, A> CallBuilder for ProjectDeleteCall<'a, C, A> {} +impl<'a, C, A> CallBuilder for OrganizationGetCall<'a, C, A> {} -impl<'a, C, A> ProjectDeleteCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { +impl<'a, C, A> OrganizationGetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { /// Perform the operation you have build so far. - pub fn doit(mut self) -> Result<(hyper::client::Response, Empty)> { + pub fn doit(mut self) -> Result<(hyper::client::Response, Organization)> { use std::io::{Read, Seek}; use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; let mut dd = DefaultDelegate; @@ -436,11 +1664,11 @@ impl<'a, C, A> ProjectDeleteCall<'a, C, A> where C: BorrowMut, A: Some(d) => d, None => &mut dd }; - dlg.begin(MethodInfo { id: "cloudresourcemanager.projects.delete", - http_method: hyper::method::Method::Delete }); + dlg.begin(MethodInfo { id: "cloudresourcemanager.organizations.get", + 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() { + params.push(("organizationId", self._organization_id.to_string())); + for &field in ["alt", "organizationId"].iter() { if self._additional_params.contains_key(field) { dlg.finished(false); return Err(Error::FieldClash(field)); @@ -452,12 +1680,12 @@ impl<'a, C, A> ProjectDeleteCall<'a, C, A> where C: BorrowMut, A: params.push(("alt", "json".to_string())); - let mut url = "https://cloudresourcemanager.googleapis.com/v1beta1/projects/{projectId}".to_string(); + let mut url = "https://cloudresourcemanager.googleapis.com/v1beta1/organizations/{organizationId}".to_string(); if self._scopes.len() == 0 { self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); } - for &(find_this, param_name) in [("{projectId}", "projectId")].iter() { + for &(find_this, param_name) in [("{organizationId}", "organizationId")].iter() { let mut replace_with: Option<&str> = None; for &(name, ref value) in params.iter() { if name == param_name { @@ -469,7 +1697,7 @@ impl<'a, C, A> ProjectDeleteCall<'a, C, A> where C: BorrowMut, A: } { let mut indices_for_removal: Vec = Vec::with_capacity(1); - for param_name in ["projectId"].iter() { + for param_name in ["organizationId"].iter() { if let Some(index) = params.iter().position(|t| &t.0 == param_name) { indices_for_removal.push(index); } @@ -503,7 +1731,7 @@ impl<'a, C, A> ProjectDeleteCall<'a, C, A> where C: BorrowMut, A: access_token: token.access_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) + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) .header(UserAgent(self.hub._user_agent.clone())) .header(auth_header.clone()); @@ -556,14 +1784,14 @@ impl<'a, C, A> ProjectDeleteCall<'a, C, A> where C: BorrowMut, A: } - /// The project ID (for example, `foo-bar-123`). Required. + /// The id of the Organization resource to fetch. /// - /// Sets the *project id* path property to the given value. + /// Sets the *organization id* path property to 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_id(mut self, new_value: &str) -> ProjectDeleteCall<'a, C, A> { - self._project_id = new_value.to_string(); + pub fn organization_id(mut self, new_value: &str) -> OrganizationGetCall<'a, C, A> { + self._organization_id = new_value.to_string(); self } /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong @@ -572,7 +1800,7 @@ impl<'a, C, A> ProjectDeleteCall<'a, C, A> where C: BorrowMut, A: /// It should be used to handle progress information, and to implement a certain level of resilience. /// /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectDeleteCall<'a, C, A> { + pub fn delegate(mut self, new_value: &'a mut Delegate) -> OrganizationGetCall<'a, C, A> { self._delegate = Some(new_value); self } @@ -599,7 +1827,7 @@ impl<'a, C, A> ProjectDeleteCall<'a, C, A> where C: BorrowMut, A: /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). /// * *alt* (query-string) - Data format for response. /// * *$.xgafv* (query-string) - V1 error format. - pub fn param(mut self, name: T, value: T) -> ProjectDeleteCall<'a, C, A> + pub fn param(mut self, name: T, value: T) -> OrganizationGetCall<'a, C, A> where T: AsRef { self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); self @@ -616,7 +1844,798 @@ impl<'a, C, A> ProjectDeleteCall<'a, C, A> where C: BorrowMut, A: /// Usually there is more than one suitable scope to authorize an operation, some of which may /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be /// sufficient, a read-write scope will do as well. - pub fn add_scope(mut self, scope: T) -> ProjectDeleteCall<'a, C, A> + pub fn add_scope(mut self, scope: T) -> OrganizationGetCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Updates an Organization resource. +/// +/// A builder for the *update* method supported by a *organization* resource. +/// It is not used directly, but through a `OrganizationMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_cloudresourcemanager1_beta1 as cloudresourcemanager1_beta1; +/// use cloudresourcemanager1_beta1::Organization; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use cloudresourcemanager1_beta1::Cloudresourcemanager; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Cloudresourcemanager::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req = Organization::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.organizations().update(req, "organizationId") +/// .doit(); +/// # } +/// ``` +pub struct OrganizationUpdateCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Cloudresourcemanager, + _request: Organization, + _organization_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for OrganizationUpdateCall<'a, C, A> {} + +impl<'a, C, A> OrganizationUpdateCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Organization)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "cloudresourcemanager.organizations.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("organizationId", self._organization_id.to_string())); + for &field in ["alt", "organizationId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://cloudresourcemanager.googleapis.com/v1beta1/organizations/{organizationId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{organizationId}", "organizationId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["organizationId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: Organization) -> OrganizationUpdateCall<'a, C, A> { + self._request = new_value; + self + } + /// An immutable id for the Organization that is assigned on creation. This should be omitted when creating a new Organization. This field is read-only. + /// + /// Sets the *organization id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn organization_id(mut self, new_value: &str) -> OrganizationUpdateCall<'a, C, A> { + self._organization_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> OrganizationUpdateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> OrganizationUpdateCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> OrganizationUpdateCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Query Organization resources. +/// +/// A builder for the *list* method supported by a *organization* resource. +/// It is not used directly, but through a `OrganizationMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_cloudresourcemanager1_beta1 as cloudresourcemanager1_beta1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use cloudresourcemanager1_beta1::Cloudresourcemanager; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Cloudresourcemanager::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.organizations().list() +/// .page_token("erat") +/// .page_size(-35) +/// .filter("sea") +/// .doit(); +/// # } +/// ``` +pub struct OrganizationListCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Cloudresourcemanager, + _page_token: Option, + _page_size: Option, + _filter: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for OrganizationListCall<'a, C, A> {} + +impl<'a, C, A> OrganizationListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ListOrganizationsResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "cloudresourcemanager.organizations.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._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._filter { + params.push(("filter", value.to_string())); + } + for &field in ["alt", "pageToken", "pageSize", "filter"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://cloudresourcemanager.googleapis.com/v1beta1/organizations".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// A pagination token returned from a previous call to ListOrganizations that indicates from where listing should continue. This field is optional. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> OrganizationListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// The maximum number of Organizations to return in the response. This field is optional. + /// + /// Sets the *page size* query property to the given value. + pub fn page_size(mut self, new_value: i32) -> OrganizationListCall<'a, C, A> { + self._page_size = Some(new_value); + self + } + /// An optional query string used to filter the Organizations to be return in the response. Filter rules are case-insensitive. Organizations may be filtered by `owner.directoryCustomerId` or by `domain`, where the domain is a Google for Work domain, for example: |Filter|Description| |------|-----------| |owner.directorycustomerid:123456789|Organizations with `owner.directory_customer_id` equal to `123456789`.| |domain:google.com|Organizations corresponding to the domain `google.com`.| This field is optional. + /// + /// Sets the *filter* query property to the given value. + pub fn filter(mut self, new_value: &str) -> OrganizationListCall<'a, C, A> { + self._filter = Some(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> OrganizationListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> OrganizationListCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> OrganizationListCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Tests the specified permissions against the IAM access control policy for the specified project. +/// +/// A builder for the *testIamPermissions* method supported by a *project* resource. +/// It is not used directly, but through a `ProjectMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_cloudresourcemanager1_beta1 as cloudresourcemanager1_beta1; +/// use cloudresourcemanager1_beta1::TestIamPermissionsRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use cloudresourcemanager1_beta1::Cloudresourcemanager; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Cloudresourcemanager::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req = TestIamPermissionsRequest::default(); +/// +/// // You can configure optional parameters by calling 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().test_iam_permissions(req, "resource") +/// .doit(); +/// # } +/// ``` +pub struct ProjectTestIamPermissionCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Cloudresourcemanager, + _request: TestIamPermissionsRequest, + _resource: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ProjectTestIamPermissionCall<'a, C, A> {} + +impl<'a, C, A> ProjectTestIamPermissionCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, TestIamPermissionsResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "cloudresourcemanager.projects.testIamPermissions", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("resource", self._resource.to_string())); + for &field in ["alt", "resource"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://cloudresourcemanager.googleapis.com/v1beta1/projects/{resource}:testIamPermissions".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{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(1); + for param_name in ["resource"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: TestIamPermissionsRequest) -> ProjectTestIamPermissionCall<'a, C, A> { + self._request = new_value; + self + } + /// REQUIRED: The resource for which policy detail is being requested. `resource` is usually specified as a path, such as, `projects/{project}`. + /// + /// 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. + pub fn resource(mut self, new_value: &str) -> ProjectTestIamPermissionCall<'a, C, A> { + self._resource = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectTestIamPermissionCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> ProjectTestIamPermissionCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProjectTestIamPermissionCall<'a, C, A> where T: AsRef { self._scopes.insert(scope.as_ref().to_string(), ()); self @@ -866,6 +2885,519 @@ impl<'a, C, A> ProjectUndeleteCall<'a, C, A> where C: BorrowMut, } +/// Creates a project resource. Initially, the project resource is owned by its creator exclusively. The creator can later grant permission to others to read or update the project. Several APIs are activated automatically for the project, including Google Cloud Storage. +/// +/// A builder for the *create* method supported by a *project* resource. +/// It is not used directly, but through a `ProjectMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_cloudresourcemanager1_beta1 as cloudresourcemanager1_beta1; +/// use cloudresourcemanager1_beta1::Project; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use cloudresourcemanager1_beta1::Cloudresourcemanager; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Cloudresourcemanager::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req = Project::default(); +/// +/// // You can configure optional parameters by calling 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().create(req) +/// .doit(); +/// # } +/// ``` +pub struct ProjectCreateCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Cloudresourcemanager, + _request: Project, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ProjectCreateCall<'a, C, A> {} + +impl<'a, C, A> ProjectCreateCall<'a, C, A> where 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: "cloudresourcemanager.projects.create", + 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 Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://cloudresourcemanager.googleapis.com/v1beta1/projects".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: Project) -> ProjectCreateCall<'a, C, A> { + self._request = new_value; + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectCreateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> ProjectCreateCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProjectCreateCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Sets the IAM access control policy for the specified project. We do not currently support 'domain:' prefixed members in a Binding of a Policy. Calling this method requires enabling the App Engine Admin API. +/// +/// A builder for the *setIamPolicy* method supported by a *project* resource. +/// It is not used directly, but through a `ProjectMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_cloudresourcemanager1_beta1 as cloudresourcemanager1_beta1; +/// use cloudresourcemanager1_beta1::SetIamPolicyRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use cloudresourcemanager1_beta1::Cloudresourcemanager; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Cloudresourcemanager::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req = SetIamPolicyRequest::default(); +/// +/// // You can configure optional parameters by calling 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_iam_policy(req, "resource") +/// .doit(); +/// # } +/// ``` +pub struct ProjectSetIamPolicyCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Cloudresourcemanager, + _request: SetIamPolicyRequest, + _resource: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ProjectSetIamPolicyCall<'a, C, A> {} + +impl<'a, C, A> ProjectSetIamPolicyCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Policy)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "cloudresourcemanager.projects.setIamPolicy", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("resource", self._resource.to_string())); + for &field in ["alt", "resource"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://cloudresourcemanager.googleapis.com/v1beta1/projects/{resource}:setIamPolicy".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{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(1); + for param_name in ["resource"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: SetIamPolicyRequest) -> ProjectSetIamPolicyCall<'a, C, A> { + self._request = new_value; + self + } + /// REQUIRED: The resource for which policy is being specified. `resource` is usually specified as a path, such as, `projects/{project}/zones/{zone}/disks/{disk}`. + /// + /// 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. + pub fn resource(mut self, new_value: &str) -> ProjectSetIamPolicyCall<'a, C, A> { + self._resource = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectSetIamPolicyCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> ProjectSetIamPolicyCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProjectSetIamPolicyCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + /// Retrieves the project identified by the specified `project_id` (for example, `my-project-123`). The caller must have read permissions for this project. /// /// A builder for the *get* method supported by a *project* resource. @@ -1381,9 +3913,9 @@ impl<'a, C, A> ProjectUpdateCall<'a, C, A> where C: BorrowMut, A: } -/// Creates a project resource. Initially, the project resource is owned by its creator exclusively. The creator can later grant permission to others to read or update the project. Several APIs are activated automatically for the project, including Google Cloud Storage. +/// Returns the IAM access control policy for specified project. /// -/// A builder for the *create* method supported by a *project* resource. +/// A builder for the *getIamPolicy* method supported by a *project* resource. /// It is not used directly, but through a `ProjectMethods` instance. /// /// # Example @@ -1394,7 +3926,7 @@ impl<'a, C, A> ProjectUpdateCall<'a, C, A> where C: BorrowMut, A: /// # extern crate hyper; /// # extern crate yup_oauth2 as oauth2; /// # extern crate google_cloudresourcemanager1_beta1 as cloudresourcemanager1_beta1; -/// use cloudresourcemanager1_beta1::Project; +/// use cloudresourcemanager1_beta1::GetIamPolicyRequest; /// # #[test] fn egal() { /// # use std::default::Default; /// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; @@ -1408,32 +3940,33 @@ impl<'a, C, A> ProjectUpdateCall<'a, C, A> where C: BorrowMut, A: /// // As the method needs a request, you would usually fill it with the desired information /// // into the respective structure. Some of the parts shown here might not be applicable ! /// // Values shown here are possibly random and not representative ! -/// let mut req = Project::default(); +/// let mut req = GetIamPolicyRequest::default(); /// /// // You can configure optional parameters by calling 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().create(req) +/// let result = hub.projects().get_iam_policy(req, "resource") /// .doit(); /// # } /// ``` -pub struct ProjectCreateCall<'a, C, A> +pub struct ProjectGetIamPolicyCall<'a, C, A> where C: 'a, A: 'a { hub: &'a Cloudresourcemanager, - _request: Project, + _request: GetIamPolicyRequest, + _resource: String, _delegate: Option<&'a mut Delegate>, _additional_params: HashMap, _scopes: BTreeMap } -impl<'a, C, A> CallBuilder for ProjectCreateCall<'a, C, A> {} +impl<'a, C, A> CallBuilder for ProjectGetIamPolicyCall<'a, C, A> {} -impl<'a, C, A> ProjectCreateCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { +impl<'a, C, A> ProjectGetIamPolicyCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { /// Perform the operation you have build so far. - pub fn doit(mut self) -> Result<(hyper::client::Response, Project)> { + pub fn doit(mut self) -> Result<(hyper::client::Response, Policy)> { use std::io::{Read, Seek}; use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; let mut dd = DefaultDelegate; @@ -1441,10 +3974,11 @@ impl<'a, C, A> ProjectCreateCall<'a, C, A> where C: BorrowMut, A: Some(d) => d, None => &mut dd }; - dlg.begin(MethodInfo { id: "cloudresourcemanager.projects.create", + dlg.begin(MethodInfo { id: "cloudresourcemanager.projects.getIamPolicy", 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() { + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("resource", self._resource.to_string())); + for &field in ["alt", "resource"].iter() { if self._additional_params.contains_key(field) { dlg.finished(false); return Err(Error::FieldClash(field)); @@ -1456,11 +3990,32 @@ impl<'a, C, A> ProjectCreateCall<'a, C, A> where C: BorrowMut, A: params.push(("alt", "json".to_string())); - let mut url = "https://cloudresourcemanager.googleapis.com/v1beta1/projects".to_string(); + let mut url = "https://cloudresourcemanager.googleapis.com/v1beta1/projects/{resource}:getIamPolicy".to_string(); if self._scopes.len() == 0 { self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); } + for &(find_this, param_name) in [("{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(1); + for param_name in ["resource"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } if params.len() > 0 { url.push('?'); @@ -1559,17 +4114,27 @@ impl<'a, C, A> ProjectCreateCall<'a, C, A> where C: BorrowMut, A: /// /// Even though the property as already been set when instantiating this call, /// we provide this method for API completeness. - pub fn request(mut self, new_value: Project) -> ProjectCreateCall<'a, C, A> { + pub fn request(mut self, new_value: GetIamPolicyRequest) -> ProjectGetIamPolicyCall<'a, C, A> { self._request = new_value; self } + /// REQUIRED: The resource for which policy is being requested. Resource is usually specified as a path, such as, `projects/{project}`. + /// + /// 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. + pub fn resource(mut self, new_value: &str) -> ProjectGetIamPolicyCall<'a, C, A> { + self._resource = new_value.to_string(); + self + } /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong /// while executing the actual API request. /// /// It should be used to handle progress information, and to implement a certain level of resilience. /// /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectCreateCall<'a, C, A> { + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectGetIamPolicyCall<'a, C, A> { self._delegate = Some(new_value); self } @@ -1596,7 +4161,7 @@ impl<'a, C, A> ProjectCreateCall<'a, C, A> where C: BorrowMut, A: /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). /// * *alt* (query-string) - Data format for response. /// * *$.xgafv* (query-string) - V1 error format. - pub fn param(mut self, name: T, value: T) -> ProjectCreateCall<'a, C, A> + pub fn param(mut self, name: T, value: T) -> ProjectGetIamPolicyCall<'a, C, A> where T: AsRef { self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); self @@ -1613,7 +4178,249 @@ impl<'a, C, A> ProjectCreateCall<'a, C, A> where C: BorrowMut, A: /// Usually there is more than one suitable scope to authorize an operation, some of which may /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be /// sufficient, a read-write scope will do as well. - pub fn add_scope(mut self, scope: T) -> ProjectCreateCall<'a, C, A> + pub fn add_scope(mut self, scope: T) -> ProjectGetIamPolicyCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Marks the project identified by the specified `project_id` (for example, `my-project-123`) for deletion. This method will only affect the project if the following criteria are met: + The project does not have a billing account associated with it. + The project has a lifecycle state of [ACTIVE][google.cloudresourcemanager.projects.v1beta1.LifecycleState.ACTIVE]. This method changes the project's lifecycle state from [ACTIVE][google.cloudresourcemanager.projects.v1beta1.LifecycleState.ACTIVE] to [DELETE_REQUESTED] [google.cloudresourcemanager.projects.v1beta1.LifecycleState.DELETE_REQUESTED]. The deletion starts at an unspecified time, at which point the lifecycle state changes to [DELETE_IN_PROGRESS] [google.cloudresourcemanager.projects.v1beta1.LifecycleState.DELETE_IN_PROGRESS]. Until the deletion completes, you can check the lifecycle state checked by retrieving the project with [GetProject] [google.cloudresourcemanager.projects.v1beta1.DeveloperProjects.GetProject], and the project remains visible to [ListProjects] [google.cloudresourcemanager.projects.v1beta1.DeveloperProjects.ListProjects]. However, you cannot update the project. After the deletion completes, the project is not retrievable by the [GetProject] [google.cloudresourcemanager.projects.v1beta1.DeveloperProjects.GetProject] and [ListProjects] [google.cloudresourcemanager.projects.v1beta1.DeveloperProjects.ListProjects] methods. The caller must have modify permissions for this project. +/// +/// A builder for the *delete* method supported by a *project* resource. +/// It is not used directly, but through a `ProjectMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_cloudresourcemanager1_beta1 as cloudresourcemanager1_beta1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use cloudresourcemanager1_beta1::Cloudresourcemanager; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Cloudresourcemanager::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling 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().delete("projectId") +/// .doit(); +/// # } +/// ``` +pub struct ProjectDeleteCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Cloudresourcemanager, + _project_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ProjectDeleteCall<'a, C, A> {} + +impl<'a, C, A> ProjectDeleteCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Empty)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "cloudresourcemanager.projects.delete", + http_method: hyper::method::Method::Delete }); + 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 Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://cloudresourcemanager.googleapis.com/v1beta1/projects/{projectId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The project ID (for example, `foo-bar-123`). Required. + /// + /// 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. + pub fn project_id(mut self, new_value: &str) -> ProjectDeleteCall<'a, C, A> { + self._project_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectDeleteCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> ProjectDeleteCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProjectDeleteCall<'a, C, A> where T: AsRef { self._scopes.insert(scope.as_ref().to_string(), ()); self @@ -1648,9 +4455,9 @@ impl<'a, C, A> ProjectCreateCall<'a, C, A> where C: BorrowMut, A: /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.projects().list() -/// .page_token("amet.") -/// .page_size(-81) -/// .filter("labore") +/// .page_token("justo") +/// .page_size(-21) +/// .filter("et") /// .doit(); /// # } /// ``` diff --git a/gen/cloudtrace1-cli/Cargo.toml b/gen/cloudtrace1-cli/Cargo.toml new file mode 100644 index 0000000000..f3d2d0101d --- /dev/null +++ b/gen/cloudtrace1-cli/Cargo.toml @@ -0,0 +1,35 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-cloudtrace1-cli" +version = "0.3.2+20150825" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with cloudtrace (protocol v1)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/cloudtrace1-cli" +homepage = "https://cloud.google.com/tools/cloud-trace" +documentation = "http://byron.github.io/google-apis-rs/google_cloudtrace1_cli" +license = "MIT" +keywords = ["cloudtrace", "google", "cli"] + +[[bin]] +name = "cloudtrace1" + +[dependencies] +hyper = ">= 0.6.8" +mime = "0.1.0" +serde = ">= 0.6.0" +serde_json = ">= 0.6.0" +yup-oauth2 = "*" +strsim = "*" +yup-hyper-mock = ">=1.0.0" +clap = ">= 1.0.3" + +[build-dependencies] +syntex = { version = "*" } +serde_codegen = { version = "*" } + + +[dependencies.google-cloudtrace1] +path = "../cloudtrace1" diff --git a/gen/cloudtrace1-cli/LICENSE.md b/gen/cloudtrace1-cli/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/cloudtrace1-cli/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/cloudtrace1-cli/README.md b/gen/cloudtrace1-cli/README.md new file mode 100644 index 0000000000..ccf913392b --- /dev/null +++ b/gen/cloudtrace1-cli/README.md @@ -0,0 +1,117 @@ + +The `cloudtrace1` command-line interface *(CLI)* allows to use most features of the *Google cloudtrace* service from the comfort of your terminal. + +By default all output is printed to standard out, but flags can be set to direct it into a file independent of your shell's +capabilities. Errors will be printed to standard error, and cause the program's exit code to be non-zero. + +If data-structures are requested, these will be returned as pretty-printed JSON, to be useful as input to other tools. + +Everything else about the *cloudtrace* API can be found at the +[official documentation site](https://cloud.google.com/tools/cloud-trace). + +# Downloads + +You can download the pre-compiled 64bit binaries for the following platforms: + +* ![icon](http://megaicons.net/static/img/icons_sizes/6/140/16/ubuntu-icon.png) [ubuntu](http://dl.byronimo.de/google.rs/cli/0.3.2/ubuntu/cloudtrace1.tar.gz) +* ![icon](http://hydra-media.cursecdn.com/wow.gamepedia.com/a/a2/Apple-icon-16x16.png?version=25ddd67ac3dd3b634478e3978b76cb74) [osx](http://dl.byronimo.de/google.rs/cli/0.3.2/osx/cloudtrace1.tar.gz) + +Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/cloudtrace1-cli). + +# Usage + +This documentation was generated from the *cloudtrace* API at revision *20150825*. The CLI is at version *0.3.2*. + +```bash +cloudtrace1 [options] + methods + get-discovery [-p ]... + projects + patch-traces (-r )... [-p ]... [-o ] + traces-get [-p ]... [-o ] + traces-list [-p ]... [-o ] + cloudtrace1 --help + +Configuration: + [--scope ]... + Specify the authentication a method should be executed in. Each scope + requires the user to grant this application permission to use it. + If unset, it defaults to the shortest scope url for a particular method. + --config-dir + A directory into which we will store our persistent data. Defaults to + a user-writable directory that we will create during the first invocation. + [default: ~/.google-service-cli] + --debug + Output all server communication to standard error. `tx` and `rx` are placed + into the same stream. + --debug-auth + Output all communication related to authentication to standard error. `tx` + and `rx` are placed into the same stream. + +``` + +# Configuration + +The program will store all persistent data in the `~/.google-service-cli` directory in *JSON* files prefixed with `cloudtrace1-`. You can change the directory used to store configuration with the `--config-dir` flag on a per-invocation basis. + +More information about the various kinds of persistent data are given in the following paragraphs. + +# Authentication + +Most APIs require a user to authenticate any request. If this is the case, the [scope][scopes] determines the +set of permissions granted. The granularity of these is usually no more than *read-only* or *full-access*. + +If not set, the system will automatically select the smallest feasible scope, e.g. when invoking a +method that is read-only, it will ask only for a read-only scope. +You may use the `--scope` flag to specify a scope directly. +All applicable scopes are documented in the respective method's CLI documentation. + +The first time a scope is used, the user is asked for permission. Follow the instructions given +by the CLI to grant permissions, or to decline. + +If a scope was authenticated by the user, the respective information will be stored as *JSON* in the configuration +directory, e.g. `~/.google-service-cli/cloudtrace1-token-.json`. No manual management of these tokens +is necessary. + +To revoke granted authentication, please refer to the [official documentation][revoke-access]. + +# Application Secrets + +In order to allow any application to use Google services, it will need to be registered using the +[Google Developer Console][google-dev-console]. APIs the application may use are then enabled for it +one by one. Most APIs can be used for free and have a daily quota. + +To allow more comfortable usage of the CLI without forcing anyone to register an own application, the CLI +comes with a default application secret that is configured accordingly. This also means that heavy usage +all around the world may deplete the daily quota. + +You can workaround this limitation by putting your own secrets file at this location: +`~/.google-service-cli/cloudtrace1-secret.json`, assuming that the required *cloudtrace* API +was enabled for it. Such a secret file can be downloaded in the *Google Developer Console* at +*APIs & auth -> Credentials -> Download JSON* and used as is. + +Learn more about how to setup Google projects and enable APIs using the [official documentation][google-project-new]. + + +# Debugging + +Even though the CLI does its best to provide usable error messages, sometimes it might be desirable to know +what exactly led to a particular issue. This is done by allowing all client-server communication to be +output to standard error *as-is*. + +The `--debug` flag will print all client-server communication to standard error, whereas the `--debug-auth` flag +will cause all communication related to authentication to standard error. +If the `--debug` flag is set, error-results will be debug-printed, possibly yielding more information about the +issue at hand. + +You may consider redirecting standard error into a file for ease of use, e.g. `cloudtrace1 --debug [options] 2>debug.txt`. + + +[scopes]: https://developers.google.com/+/api/oauth#scopes +[revoke-access]: http://webapps.stackexchange.com/a/30849 +[google-dev-console]: https://console.developers.google.com/ +[google-project-new]: https://developers.google.com/console/help/new/ \ No newline at end of file diff --git a/gen/cloudtrace1-cli/mkdocs.yml b/gen/cloudtrace1-cli/mkdocs.yml new file mode 100644 index 0000000000..d36268754a --- /dev/null +++ b/gen/cloudtrace1-cli/mkdocs.yml @@ -0,0 +1,20 @@ +site_name: cloudtrace v0.3.2+20150825 +site_url: http://byron.github.io/google-apis-rs/google-cloudtrace1-cli +site_description: Write integrating applications with bcore + +repo_url: https://github.com/Byron/google-apis-rs/tree/master/gen/cloudtrace1-cli + +docs_dir: docs +site_dir: build_html + +pages: +- ['index.md', 'Home'] +- ['methods_get-discovery.md', 'Methods', 'Get Discovery'] +- ['projects_patch-traces.md', 'Projects', 'Patch Traces'] +- ['projects_traces-get.md', 'Projects', 'Traces Get'] +- ['projects_traces-list.md', 'Projects', 'Traces List'] + +theme: readthedocs + +copyright: Copyright © 2015, `Sebastian Thiel` + diff --git a/gen/cloudtrace1-cli/src/cmn.rs b/gen/cloudtrace1-cli/src/cmn.rs new file mode 100644 index 0000000000..8358f156fa --- /dev/null +++ b/gen/cloudtrace1-cli/src/cmn.rs @@ -0,0 +1,721 @@ +// COPY OF 'src/rust/cli/cmn.rs' +// DO NOT EDIT +use oauth2::{ApplicationSecret, ConsoleApplicationSecret, TokenStorage, Token}; +use serde_json as json; +use serde_json::value::Value; +use mime::Mime; +use clap::{App, SubCommand}; +use strsim; + +use std::fs; +use std::env; +use std::io; +use std::fmt; +use std::path::{Path, PathBuf}; +use std::str::FromStr; +use std::string::ToString; +use std::io::{Write, Read, stdout}; + +use std::default::Default; + +const FIELD_SEP: char = '.'; + + +pub enum ComplexType { + Pod, + Vec, + Map, +} + + // Null, + // Bool(bool), + // I64(i64), + // U64(u64), + // F64(f64), + // String(String), + +pub enum JsonType { + Boolean, + Int, + Uint, + Float, + String, +} + +pub struct JsonTypeInfo { + pub jtype: JsonType, + pub ctype: ComplexType, +} + +// Based on @erickt user comment. Thanks for the idea ! +// Remove all keys whose values are null from given value (changed in place) +pub fn remove_json_null_values(value: &mut Value) { + match *value { + Value::Object(ref mut map) => { + let mut for_removal = Vec::new(); + + for (key, mut value) in map.iter_mut() { + if value.is_null() { + for_removal.push(key.clone()); + } else { + remove_json_null_values(&mut value); + } + } + + for key in &for_removal { + map.remove(key); + } + } + _ => {} + } +} + +fn did_you_mean<'a>(v: &str, possible_values: &[&'a str]) -> Option<&'a str> { + + let mut candidate: Option<(f64, &str)> = None; + for pv in possible_values { + let confidence = strsim::jaro_winkler(v, pv); + if confidence > 0.8 && (candidate.is_none() || (candidate.as_ref().unwrap().0 < confidence)) { + candidate = Some((confidence, pv)); + } + } + match candidate { + None => None, + Some((_, candidate)) => Some(candidate), + } +} + +pub enum CallType { + Upload(UploadProtocol), + Standard, +} + +arg_enum!{ + pub enum UploadProtocol { + Simple, + Resumable + } +} + +impl AsRef for UploadProtocol { + fn as_ref(&self) -> &str { + match *self { + UploadProtocol::Simple => "simple", + UploadProtocol::Resumable => "resumable" + } + } +} + +impl AsRef for CallType { + fn as_ref(&self) -> &str { + match *self { + CallType::Upload(ref proto) => proto.as_ref(), + CallType::Standard => "standard-request" + } + } +} + +#[derive(Clone, Default)] +pub struct FieldCursor(Vec); + +impl ToString for FieldCursor { + fn to_string(&self) -> String { + self.0.join(".") + } +} + +impl From<&'static str> for FieldCursor { + fn from(value: &'static str) -> FieldCursor { + let mut res = FieldCursor::default(); + res.set(value).unwrap(); + res + } +} + +impl FieldCursor { + pub fn set(&mut self, value: &str) -> Result<(), CLIError> { + if value.len() == 0 { + return Err(CLIError::Field(FieldError::Empty)) + } + + let mut first_is_field_sep = false; + let mut char_count: usize = 0; + let mut last_c = FIELD_SEP; + let mut num_conscutive_field_seps = 0; + + let mut field = String::new(); + let mut fields = self.0.clone(); + + let push_field = |fs: &mut Vec, f: &mut String| { + if f.len() > 0 { + fs.push(f.clone()); + f.truncate(0); + } + }; + + for (cid, c) in value.chars().enumerate() { + char_count += 1; + + if c == FIELD_SEP { + if cid == 0 { + first_is_field_sep = true; + } + num_conscutive_field_seps += 1; + if cid > 0 && last_c == FIELD_SEP { + if fields.pop().is_none() { + return Err(CLIError::Field(FieldError::PopOnEmpty(value.to_string()))) + } + } else { + push_field(&mut fields, &mut field); + } + } else { + num_conscutive_field_seps = 0; + if cid == 1 { + if first_is_field_sep { + fields.truncate(0); + } + } + field.push(c); + } + + last_c = c; + } + + push_field(&mut fields, &mut field); + + if char_count == 1 && first_is_field_sep { + fields.truncate(0); + } + if char_count > 1 && num_conscutive_field_seps == 1 { + return Err(CLIError::Field(FieldError::TrailingFieldSep(value.to_string()))) + } + + self.0 = fields; + Ok(()) + } + + pub fn did_you_mean(value: &str, possible_values: &[&str]) -> Option { + if value.len() == 0 { + return None + } + + let mut last_c = FIELD_SEP; + + let mut field = String::new(); + let mut output = String::new(); + + let push_field = |fs: &mut String, f: &mut String| { + if f.len() > 0 { + fs.push_str( + match did_you_mean(&f, possible_values) { + Some(candidate) => candidate, + None => &f, + }); + f.truncate(0); + } + }; + + for (cid, c) in value.chars().enumerate() { + if c == FIELD_SEP { + if last_c != FIELD_SEP { + push_field(&mut output, &mut field); + } + output.push(c); + } else { + field.push(c); + } + + last_c = c; + } + + push_field(&mut output, &mut field); + + if &output == value { + None + } else { + Some(output) + } + } + + pub fn set_json_value(&self, mut object: &mut Value, + value: &str, type_info: JsonTypeInfo, + err: &mut InvalidOptionsError, + orig_cursor: &FieldCursor) { + assert!(self.0.len() > 0); + + for field in &self.0[..self.0.len()-1] { + let tmp = object; + object = + match *tmp { + Value::Object(ref mut mapping) => { + mapping.entry(field.to_owned()).or_insert( + Value::Object(Default::default()) + ) + }, + _ => panic!("We don't expect non-object Values here ...") + }; + } + + match *object { + Value::Object(ref mut mapping) => { + let field = &self.0[self.0.len()-1]; + let to_jval = + |value: &str, jtype: JsonType, err: &mut InvalidOptionsError| + -> Value { + match jtype { + JsonType::Boolean => + Value::Bool(arg_from_str(value, err, &field, "boolean")), + JsonType::Int => + Value::I64(arg_from_str(value, err, &field, "int")), + JsonType::Uint => + Value::U64(arg_from_str(value, err, &field, "uint")), + JsonType::Float => + Value::F64(arg_from_str(value, err, &field, "float")), + JsonType::String => + Value::String(value.to_owned()), + } + }; + + match type_info.ctype { + ComplexType::Pod => { + if mapping.insert(field.to_owned(), to_jval(value, type_info.jtype, err)).is_some() { + err.issues.push(CLIError::Field(FieldError::Duplicate(orig_cursor.to_string()))); + } + }, + ComplexType::Vec => { + match *mapping.entry(field.to_owned()) + .or_insert(Value::Array(Default::default())) { + Value::Array(ref mut values) => values.push(to_jval(value, type_info.jtype, err)), + _ => unreachable!() + } + }, + ComplexType::Map => { + let (key, value) = parse_kv_arg(value, err, true); + let jval = to_jval(value.unwrap_or(""), type_info.jtype, err); + + match *mapping.entry(field.to_owned()) + .or_insert(Value::Object(Default::default())) { + Value::Object(ref mut value_map) => { + if value_map.insert(key.to_owned(), jval).is_some() { + err.issues.push(CLIError::Field(FieldError::Duplicate(orig_cursor.to_string()))); + } + } + _ => unreachable!() + } + } + } + }, + _ => unreachable!() + } + } + + pub fn num_fields(&self) -> usize { + self.0.len() + } +} + +pub fn parse_kv_arg<'a>(kv: &'a str, err: &mut InvalidOptionsError, for_hashmap: bool) + -> (&'a str, Option<&'a str>) { + let mut add_err = || err.issues.push(CLIError::InvalidKeyValueSyntax(kv.to_string(),for_hashmap)); + match kv.find('=') { + None => { + add_err(); + return (kv, None) + }, + Some(pos) => { + let key = &kv[..pos]; + if kv.len() <= pos + 1 { + add_err(); + return (key, Some("")) + } + (key, Some(&kv[pos+1..])) + } + } +} + +pub fn calltype_from_str(name: &str, valid_protocols: Vec, err: &mut InvalidOptionsError) -> CallType { + CallType::Upload( + match UploadProtocol::from_str(name) { + Ok(up) => up, + Err(msg) => { + err.issues.push(CLIError::InvalidUploadProtocol(name.to_string(), valid_protocols)); + UploadProtocol::Simple + } + }) +} + +pub fn input_file_from_opts(file_path: &str, err: &mut InvalidOptionsError) -> Option { + match fs::File::open(file_path) { + Ok(f) => Some(f), + Err(io_err) => { + err.issues.push(CLIError::Input(InputError::IOError((file_path.to_string(), io_err)))); + None + } + } +} + +pub fn input_mime_from_opts(mime: &str, err: &mut InvalidOptionsError) -> Option { + match mime.parse() { + Ok(m) => Some(m), + Err(_) => { + err.issues.push(CLIError::Input(InputError::Mime(mime.to_string()))); + None + } + } +} + +pub fn writer_from_opts(arg: Option<&str>) -> Result, io::Error> { + let f = arg.unwrap_or("-"); + match f { + "-" => Ok(Box::new(stdout())), + _ => match fs::OpenOptions::new().create(true).write(true).open(f) { + Ok(f) => Ok(Box::new(f)), + Err(io_err) => Err(io_err), + } + } +} + + +pub fn arg_from_str<'a, T>(arg: &str, err: &mut InvalidOptionsError, + arg_name: &'a str, + arg_type: &'a str) -> T + where T: FromStr + Default, + ::Err: fmt::Display { + match FromStr::from_str(arg) { + Err(perr) => { + err.issues.push( + CLIError::ParseError(arg_name.to_owned(), arg_type.to_owned(), arg.to_string(), format!("{}", perr)) + ); + Default::default() + }, + Ok(v) => v, + } +} + +pub struct JsonTokenStorage { + pub program_name: &'static str, + pub db_dir: String, +} + +impl JsonTokenStorage { + fn path(&self, scope_hash: u64) -> PathBuf { + Path::new(&self.db_dir).join(&format!("{}-token-{}.json", self.program_name, scope_hash)) + } +} + +impl TokenStorage for JsonTokenStorage { + type Error = json::Error; + + // NOTE: logging might be interesting, currently we swallow all errors + fn set(&mut self, scope_hash: u64, _: &Vec<&str>, token: Option) -> Result<(), json::Error> { + match token { + None => { + match fs::remove_file(self.path(scope_hash)) { + Err(err) => + match err.kind() { + io::ErrorKind::NotFound => Ok(()), + _ => Err(json::Error::IoError(err)) + }, + Ok(_) => Ok(()), + } + } + Some(token) => { + match fs::OpenOptions::new().create(true).write(true).open(&self.path(scope_hash)) { + Ok(mut f) => { + match json::to_writer_pretty(&mut f, &token) { + Ok(_) => Ok(()), + Err(serde_err) => Err(serde_err), + } + }, + Err(io_err) => Err(json::Error::IoError(io_err)) + } + } + } + } + + fn get(&self, scope_hash: u64, _: &Vec<&str>) -> Result, json::Error> { + match fs::File::open(&self.path(scope_hash)) { + Ok(mut f) => { + match json::de::from_reader(f) { + Ok(token) => Ok(Some(token)), + Err(err) => Err(err), + } + }, + Err(io_err) => { + match io_err.kind() { + io::ErrorKind::NotFound => Ok(None), + _ => Err(json::Error::IoError(io_err)) + } + } + } + } +} + + +#[derive(Debug)] +pub enum ApplicationSecretError { + DecoderError((String, json::Error)), + FormatError(String), +} + +impl fmt::Display for ApplicationSecretError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + ApplicationSecretError::DecoderError((ref path, ref err)) + => writeln!(f, "Could not decode file at '{}' with error: {}.", + path, err), + ApplicationSecretError::FormatError(ref path) + => writeln!(f, "'installed' field is unset in secret file at '{}'.", + path), + } + } +} + +#[derive(Debug)] +pub enum ConfigurationError { + DirectoryCreationFailed((String, io::Error)), + DirectoryUnset, + HomeExpansionFailed(String), + Secret(ApplicationSecretError), + IOError((String, io::Error)), +} + +impl fmt::Display for ConfigurationError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + ConfigurationError::DirectoryCreationFailed((ref dir, ref err)) + => writeln!(f, "Directory '{}' could not be created with error: {}.", dir, err), + ConfigurationError::DirectoryUnset + => writeln!(f, "--config-dir was unset or empty."), + ConfigurationError::HomeExpansionFailed(ref dir) + => writeln!(f, "Couldn't find HOME directory of current user, failed to expand '{}'.", dir), + ConfigurationError::Secret(ref err) + => writeln!(f, "Secret -> {}", err), + ConfigurationError::IOError((ref path, ref err)) + => writeln!(f, "IO operation failed on path '{}' with error: {}.", path, err), + } + } +} + +#[derive(Debug)] +pub enum InputError { + IOError((String, io::Error)), + Mime(String), +} + +impl fmt::Display for InputError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + InputError::IOError((ref file_path, ref io_err)) + => writeln!(f, "Failed to open '{}' for reading with error: {}.", file_path, io_err), + InputError::Mime(ref mime) + => writeln!(f, "'{}' is not a known mime-type.", mime), + } + } +} + +#[derive(Debug)] +pub enum FieldError { + PopOnEmpty(String), + TrailingFieldSep(String), + Unknown(String, Option, Option), + Duplicate(String), + Empty, +} + + +impl fmt::Display for FieldError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + FieldError::PopOnEmpty(ref field) + => writeln!(f, "'{}': Cannot move up on empty field cursor.", field), + FieldError::TrailingFieldSep(ref field) + => writeln!(f, "'{}': Single field separator may not be last character.", field), + FieldError::Unknown(ref field, ref suggestion, ref value) => { + let suffix = + match *suggestion { + Some(ref s) => { + let kv = + match *value { + Some(ref v) => format!("{}={}", s, v), + None => s.clone(), + }; + format!(" Did you mean '{}' ?", kv) + }, + None => String::new(), + }; + writeln!(f, "Field '{}' does not exist.{}", field, suffix) + }, + FieldError::Duplicate(ref cursor) + => writeln!(f, "Value at '{}' was already set", cursor), + FieldError::Empty + => writeln!(f, "Field names must not be empty."), + } + } +} + + +#[derive(Debug)] +pub enum CLIError { + Configuration(ConfigurationError), + ParseError(String, String, String, String), + UnknownParameter(String, Vec<&'static str>), + InvalidUploadProtocol(String, Vec), + InvalidKeyValueSyntax(String, bool), + Input(InputError), + Field(FieldError), + MissingCommandError, + MissingMethodError(String), +} + +impl fmt::Display for CLIError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + CLIError::Configuration(ref err) => write!(f, "Configuration -> {}", err), + CLIError::Input(ref err) => write!(f, "Input -> {}", err), + CLIError::Field(ref err) => write!(f, "Field -> {}", err), + CLIError::InvalidUploadProtocol(ref proto_name, ref valid_names) + => writeln!(f, "'{}' is not a valid upload protocol. Choose from one of {}.", proto_name, valid_names.join(", ")), + CLIError::ParseError(ref arg_name, ref type_name, ref value, ref err_desc) + => writeln!(f, "Failed to parse argument '{}' with value '{}' as {} with error: {}.", + arg_name, value, type_name, err_desc), + CLIError::UnknownParameter(ref param_name, ref possible_values) => { + let mut suffix = + match did_you_mean(param_name, &possible_values) { + Some(v) => format!(" Did you mean '{}' ?", v), + None => String::new(), + }; + write!(f, "Parameter '{}' is unknown.{}\n", param_name, suffix) + }, + CLIError::InvalidKeyValueSyntax(ref kv, is_hashmap) => { + let hashmap_info = if is_hashmap { "hashmap " } else { "" }; + writeln!(f, "'{}' does not match {}pattern =.", kv, hashmap_info) + }, + CLIError::MissingCommandError => writeln!(f, "Please specify the main sub-command."), + CLIError::MissingMethodError(ref cmd) => writeln!(f, "Please specify the method to call on the '{}' command.", cmd), + } + } +} + +#[derive(Debug)] +pub struct InvalidOptionsError { + pub issues: Vec, + pub exit_code: i32, +} + +impl fmt::Display for InvalidOptionsError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + for issue in &self.issues { + try!(issue.fmt(f)); + } + Ok(()) + } +} + +impl InvalidOptionsError { + pub fn single(err: CLIError, exit_code: i32) -> InvalidOptionsError { + InvalidOptionsError { + issues: vec![err], + exit_code: exit_code, + } + } + + pub fn new() -> InvalidOptionsError { + InvalidOptionsError { + issues: Vec::new(), + exit_code: 1, + } + } +} + +pub fn assure_config_dir_exists(dir: &str) -> Result { + let trdir = dir.trim(); + if trdir.len() == 0 { + return Err(CLIError::Configuration(ConfigurationError::DirectoryUnset)) + } + + let expanded_config_dir = + if trdir.as_bytes()[0] == b'~' { + match env::var("HOME").ok().or(env::var("UserProfile").ok()) { + None => return Err(CLIError::Configuration(ConfigurationError::HomeExpansionFailed(trdir.to_string()))), + Some(mut user) => { + user.push_str(&trdir[1..]); + user + } + } + } else { + trdir.to_string() + }; + + if let Err(err) = fs::create_dir(&expanded_config_dir) { + if err.kind() != io::ErrorKind::AlreadyExists { + return Err(CLIError::Configuration( + ConfigurationError::DirectoryCreationFailed((expanded_config_dir, err)))) + } + } + + Ok(expanded_config_dir) +} + +pub fn application_secret_from_directory(dir: &str, + secret_basename: &str, + json_console_secret: &str) + -> Result { + let secret_path = Path::new(dir).join(secret_basename); + let secret_str = || secret_path.as_path().to_str().unwrap().to_string(); + let secret_io_error = |io_err: io::Error| { + Err(CLIError::Configuration(ConfigurationError::IOError( + (secret_str(), io_err) + ))) + }; + + for _ in 0..2 { + match fs::File::open(&secret_path) { + Err(mut err) => { + if err.kind() == io::ErrorKind::NotFound { + // Write our built-in one - user may adjust the written file at will + + err = match fs::OpenOptions::new().create(true).write(true).open(&secret_path) { + Err(cfe) => cfe, + Ok(mut f) => { + // Assure we convert 'ugly' json string into pretty one + let console_secret: ConsoleApplicationSecret + = json::from_str(json_console_secret).unwrap(); + match json::to_writer_pretty(&mut f, &console_secret) { + Err(serde_err) => match serde_err { + json::Error::IoError(err) => err, + _ => panic!("Unexpected serde error: {:#?}", serde_err) + }, + Ok(_) => continue, + } + } + }; + // fall through to IO error handling + } + return secret_io_error(err) + }, + Ok(mut f) => { + match json::de::from_reader::<_, ConsoleApplicationSecret>(f) { + Err(json::Error::IoError(err)) => + return secret_io_error(err), + Err(json_err) => + return Err(CLIError::Configuration( + ConfigurationError::Secret( + ApplicationSecretError::DecoderError( + (secret_str(), json_err) + )))), + Ok(console_secret) => + match console_secret.installed { + Some(secret) => return Ok(secret), + None => return Err( + CLIError::Configuration( + ConfigurationError::Secret( + ApplicationSecretError::FormatError(secret_str()) + ))) + }, + } + } + } + } + unreachable!(); +} diff --git a/gen/cloudtrace1-cli/src/main.rs b/gen/cloudtrace1-cli/src/main.rs new file mode 100644 index 0000000000..c944223915 --- /dev/null +++ b/gen/cloudtrace1-cli/src/main.rs @@ -0,0 +1,622 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/cli/main.rs.mako' +// DO NOT EDIT ! +#![allow(unused_variables, unused_imports, dead_code, unused_mut)] + +#[macro_use] +extern crate clap; +extern crate yup_oauth2 as oauth2; +extern crate yup_hyper_mock as mock; +extern crate serde; +extern crate serde_json; +extern crate hyper; +extern crate mime; +extern crate strsim; +extern crate google_cloudtrace1 as api; + +use std::env; +use std::io::{self, Write}; +use clap::{App, SubCommand, Arg}; + +mod cmn; + +use cmn::{InvalidOptionsError, CLIError, JsonTokenStorage, arg_from_str, writer_from_opts, parse_kv_arg, + input_file_from_opts, input_mime_from_opts, FieldCursor, FieldError, CallType, UploadProtocol, + calltype_from_str, remove_json_null_values, ComplexType, JsonType, JsonTypeInfo}; + +use std::default::Default; +use std::str::FromStr; + +use oauth2::{Authenticator, DefaultAuthenticatorDelegate}; +use serde_json as json; +use clap::ArgMatches; + +enum DoitError { + IoError(String, io::Error), + ApiError(api::Error), +} + +struct Engine<'n, 'a> { + opt: ArgMatches<'n, 'a>, + hub: api::Cloudtrace>, + gp: Vec<&'static str>, + gpm: Vec<(&'static str, &'static str)>, +} + + +impl<'n, 'a> Engine<'n, 'a> { + fn _methods_get_discovery(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.methods().get_discovery(); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "version" => { + call = call.version(value.unwrap_or("")); + }, + "labels" => { + call = call.add_labels(value.unwrap_or("")); + }, + "format" => { + call = call.format(value.unwrap_or("")); + }, + "args" => { + call = call.add_args(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["labels", "version", "args", "format"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok(mut response) => { + Ok(()) + } + } + } + } + + fn _projects_patch_traces(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec![]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::Traces = json::value::from_value(object).unwrap(); + let mut call = self.hub.projects().patch_traces(request, opt.value_of("project-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _projects_traces_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.projects().traces_get(opt.value_of("project-id").unwrap_or(""), opt.value_of("trace-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _projects_traces_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.projects().traces_list(opt.value_of("project-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "view" => { + call = call.view(value.unwrap_or("")); + }, + "start-time" => { + call = call.start_time(value.unwrap_or("")); + }, + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "page-size" => { + call = call.page_size(arg_from_str(value.unwrap_or("-0"), err, "page-size", "integer")); + }, + "order-by" => { + call = call.order_by(value.unwrap_or("")); + }, + "filter" => { + call = call.filter(value.unwrap_or("")); + }, + "end-time" => { + call = call.end_time(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["order-by", "page-size", "filter", "page-token", "start-time", "end-time", "view"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _doit(&self, dry_run: bool) -> Result, Option> { + let mut err = InvalidOptionsError::new(); + let mut call_result: Result<(), DoitError> = Ok(()); + let mut err_opt: Option = None; + match self.opt.subcommand() { + ("methods", Some(opt)) => { + match opt.subcommand() { + ("get-discovery", Some(opt)) => { + call_result = self._methods_get_discovery(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("methods".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("projects", Some(opt)) => { + match opt.subcommand() { + ("patch-traces", Some(opt)) => { + call_result = self._projects_patch_traces(opt, dry_run, &mut err); + }, + ("traces-get", Some(opt)) => { + call_result = self._projects_traces_get(opt, dry_run, &mut err); + }, + ("traces-list", Some(opt)) => { + call_result = self._projects_traces_list(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("projects".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + _ => { + err.issues.push(CLIError::MissingCommandError); + writeln!(io::stderr(), "{}\n", self.opt.usage()).ok(); + } + } + + if dry_run { + if err.issues.len() > 0 { + err_opt = Some(err); + } + Err(err_opt) + } else { + Ok(call_result) + } + } + + // Please note that this call will fail if any part of the opt can't be handled + fn new(opt: ArgMatches<'a, 'n>) -> Result, InvalidOptionsError> { + let (config_dir, secret) = { + let config_dir = match cmn::assure_config_dir_exists(opt.value_of("folder").unwrap_or("~/.google-service-cli")) { + Err(e) => return Err(InvalidOptionsError::single(e, 3)), + Ok(p) => p, + }; + + match cmn::application_secret_from_directory(&config_dir, "cloudtrace1-secret.json", + "{\"installed\":{\"auth_uri\":\"https://accounts.google.com/o/oauth2/auth\",\"client_secret\":\"hCsslbCUyfehWMmbkG8vTYxG\",\"token_uri\":\"https://accounts.google.com/o/oauth2/token\",\"client_email\":\"\",\"redirect_uris\":[\"urn:ietf:wg:oauth:2.0:oob\",\"oob\"],\"client_x509_cert_url\":\"\",\"client_id\":\"620010449518-9ngf7o4dhs0dka470npqvor6dc5lqb9b.apps.googleusercontent.com\",\"auth_provider_x509_cert_url\":\"https://www.googleapis.com/oauth2/v1/certs\"}}") { + Ok(secret) => (config_dir, secret), + Err(e) => return Err(InvalidOptionsError::single(e, 4)) + } + }; + + let auth = Authenticator::new( &secret, DefaultAuthenticatorDelegate, + if opt.is_present("debug-auth") { + hyper::Client::with_connector(mock::TeeConnector { + connector: hyper::net::HttpsConnector::::default() + }) + } else { + hyper::Client::new() + }, + JsonTokenStorage { + program_name: "cloudtrace1", + db_dir: config_dir.clone(), + }, None); + + let client = + if opt.is_present("debug") { + hyper::Client::with_connector(mock::TeeConnector { + connector: hyper::net::HttpsConnector::::default() + }) + } else { + hyper::Client::new() + }; + let engine = Engine { + opt: opt, + hub: api::Cloudtrace::new(client, auth), + gp: vec!["$-xgafv", "access-token", "alt", "bearer-token", "callback", "fields", "key", "oauth-token", "pp", "pretty-print", "quota-user", "upload-type", "upload-protocol"], + gpm: vec![ + ("$-xgafv", "$.xgafv"), + ("access-token", "access_token"), + ("bearer-token", "bearer_token"), + ("oauth-token", "oauth_token"), + ("pretty-print", "prettyPrint"), + ("quota-user", "quotaUser"), + ("upload-type", "uploadType"), + ("upload-protocol", "upload_protocol"), + ] + }; + + match engine._doit(true) { + Err(Some(err)) => Err(err), + Err(None) => Ok(engine), + Ok(_) => unreachable!(), + } + } + + fn doit(&self) -> Result<(), DoitError> { + match self._doit(false) { + Ok(res) => res, + Err(_) => unreachable!(), + } + } +} + +fn main() { + let mut exit_status = 0i32; + let arg_data = [ + ("methods", "methods: 'get-discovery'", vec![ + ("get-discovery", + Some(r##"Returns a discovery document in the specified `format`. The typeurl in the returned google.protobuf.Any value depends on the requested format."##), + "Details at http://byron.github.io/google-apis-rs/google_cloudtrace1_cli/methods_get-discovery", + vec![ + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + ]), + ]), + + ("projects", "methods: 'patch-traces', 'traces-get' and 'traces-list'", vec![ + ("patch-traces", + Some(r##"Updates the existing traces specified by PatchTracesRequest and inserts the new traces. Any existing trace or span fields included in an update are overwritten by the update, and any additional fields in an update are merged with the existing trace data."##), + "Details at http://byron.github.io/google-apis-rs/google_cloudtrace1_cli/projects_patch-traces", + vec![ + (Some(r##"project-id"##), + None, + Some(r##"The project id of the trace to patch."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("traces-get", + Some(r##"Gets one trace by id."##), + "Details at http://byron.github.io/google-apis-rs/google_cloudtrace1_cli/projects_traces-get", + vec![ + (Some(r##"project-id"##), + None, + Some(r##"The project id of the trace to return."##), + Some(true), + Some(false)), + + (Some(r##"trace-id"##), + None, + Some(r##"The trace id of the trace to return."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("traces-list", + Some(r##"List traces matching the filter expression."##), + "Details at http://byron.github.io/google-apis-rs/google_cloudtrace1_cli/projects_traces-list", + vec![ + (Some(r##"project-id"##), + None, + Some(r##"The stringified-version of the project id."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ]; + + let mut app = App::new("cloudtrace1") + .author("Sebastian Thiel ") + .version("0.3.2+20150825") + .about("The Google Cloud Trace API provides services for reading and writing runtime trace data for Cloud applications.") + .after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_cloudtrace1_cli") + .arg(Arg::with_name("url") + .long("scope") + .help("Specify the authentication a method should be executed in. Each scope requires the user to grant this application permission to use it.If unset, it defaults to the shortest scope url for a particular method.") + .multiple(true) + .takes_value(true)) + .arg(Arg::with_name("folder") + .long("config-dir") + .help("A directory into which we will store our persistent data. Defaults to a user-writable directory that we will create during the first invocation.[default: ~/.google-service-cli") + .multiple(false) + .takes_value(true)) + .arg(Arg::with_name("debug") + .long("debug") + .help("Output all server communication to standard error. `tx` and `rx` are placed into the same stream.") + .multiple(false) + .takes_value(false)) + .arg(Arg::with_name("debug-auth") + .long("debug-auth") + .help("Output all communication related to authentication to standard error. `tx` and `rx` are placed into the same stream.") + .multiple(false) + .takes_value(false)); + + for &(main_command_name, ref about, ref subcommands) in arg_data.iter() { + let mut mcmd = SubCommand::with_name(main_command_name).about(about); + + for &(sub_command_name, ref desc, url_info, ref args) in subcommands { + let mut scmd = SubCommand::with_name(sub_command_name); + if let &Some(desc) = desc { + scmd = scmd.about(desc); + } + scmd = scmd.after_help(url_info); + + for &(ref arg_name, ref flag, ref desc, ref required, ref multi) in args { + let arg_name_str = + match (arg_name, flag) { + (&Some(an), _ ) => an, + (_ , &Some(f)) => f, + _ => unreachable!(), + }; + let mut arg = Arg::with_name(arg_name_str) + .empty_values(false); + if let &Some(short_flag) = flag { + arg = arg.short(short_flag); + } + if let &Some(desc) = desc { + arg = arg.help(desc); + } + if arg_name.is_some() && flag.is_some() { + arg = arg.takes_value(true); + } + if let &Some(required) = required { + arg = arg.required(required); + } + if let &Some(multi) = multi { + arg = arg.multiple(multi); + } + scmd = scmd.arg(arg); + } + mcmd = mcmd.subcommand(scmd); + } + app = app.subcommand(mcmd); + } + + let matches = app.get_matches(); + + let debug = matches.is_present("debug"); + match Engine::new(matches) { + Err(err) => { + exit_status = err.exit_code; + writeln!(io::stderr(), "{}", err).ok(); + }, + Ok(engine) => { + if let Err(doit_err) = engine.doit() { + exit_status = 1; + match doit_err { + DoitError::IoError(path, err) => { + writeln!(io::stderr(), "Failed to open output file '{}': {}", path, err).ok(); + }, + DoitError::ApiError(err) => { + if debug { + writeln!(io::stderr(), "{:#?}", err).ok(); + } else { + writeln!(io::stderr(), "{}", err).ok(); + } + } + } + } + } + } + + std::process::exit(exit_status); +} \ No newline at end of file diff --git a/gen/cloudtrace1/Cargo.toml b/gen/cloudtrace1/Cargo.toml new file mode 100644 index 0000000000..05749a6d91 --- /dev/null +++ b/gen/cloudtrace1/Cargo.toml @@ -0,0 +1,29 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-cloudtrace1" +version = "0.1.9+20150825" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with cloudtrace (protocol v1)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/cloudtrace1" +homepage = "https://cloud.google.com/tools/cloud-trace" +documentation = "http://byron.github.io/google-apis-rs/google_cloudtrace1" +license = "MIT" +keywords = ["cloudtrace", "google", "protocol", "web", "api"] +build = "src/build.rs" + + +[dependencies] +hyper = ">= 0.6.8" +mime = "0.1.0" +serde = ">= 0.6.0" +serde_json = ">= 0.6.0" +yup-oauth2 = "*" +url = "*" + +[build-dependencies] +syntex = { version = "*" } +serde_codegen = { version = "*" } + diff --git a/gen/cloudtrace1/LICENSE.md b/gen/cloudtrace1/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/cloudtrace1/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/cloudtrace1/README.md b/gen/cloudtrace1/README.md new file mode 100644 index 0000000000..d667c86275 --- /dev/null +++ b/gen/cloudtrace1/README.md @@ -0,0 +1,176 @@ + +The `google-cloudtrace1` library allows access to all features of the *Google cloudtrace* service. + +This documentation was generated from *cloudtrace* crate version *0.1.9+20150825*, where *20150825* is the exact revision of the *cloudtrace:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. + +Everything else about the *cloudtrace* *v1* API can be found at the +[official documentation site](https://cloud.google.com/tools/cloud-trace). +# Features + +Handle the following *Resources* with ease from the central [hub](http://byron.github.io/google-apis-rs/google_cloudtrace1/struct.Cloudtrace.html) ... + +* projects + * [*patch traces*](http://byron.github.io/google-apis-rs/google_cloudtrace1/struct.ProjectPatchTraceCall.html), [*traces get*](http://byron.github.io/google-apis-rs/google_cloudtrace1/struct.ProjectTraceGetCall.html) and [*traces list*](http://byron.github.io/google-apis-rs/google_cloudtrace1/struct.ProjectTraceListCall.html) + +Other activities are ... + +* [get discovery](http://byron.github.io/google-apis-rs/google_cloudtrace1/struct.MethodGetDiscoveryCall.html) + + + +# Structure of this Library + +The API is structured into the following primary items: + +* **[Hub](http://byron.github.io/google-apis-rs/google_cloudtrace1/struct.Cloudtrace.html)** + * a central object to maintain state and allow accessing all *Activities* + * creates [*Method Builders*](http://byron.github.io/google-apis-rs/google_cloudtrace1/trait.MethodsBuilder.html) which in turn + allow access to individual [*Call Builders*](http://byron.github.io/google-apis-rs/google_cloudtrace1/trait.CallBuilder.html) +* **[Resources](http://byron.github.io/google-apis-rs/google_cloudtrace1/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_cloudtrace1/trait.Part.html)** + * a collection of properties + * never directly used in *Activities* +* **[Activities](http://byron.github.io/google-apis-rs/google_cloudtrace1/trait.CallBuilder.html)** + * operations to apply to *Resources* + +All *structures* are marked with applicable traits to further categorize them and ease browsing. + +Generally speaking, you can invoke *Activities* like this: + +```Rust,ignore +let r = hub.resource().activity(...).doit() +``` + +Or specifically ... + +```ignore +let r = hub.projects().traces_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-cloudtrace1 = "*" +``` + +## A complete example + +```Rust +extern crate hyper; +extern crate yup_oauth2 as oauth2; +extern crate google_cloudtrace1 as cloudtrace1; +use cloudtrace1::{Result, Error}; +use std::default::Default; +use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +use cloudtrace1::Cloudtrace; + +// 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 = Cloudtrace::new(hyper::Client::new(), auth); +// You can configure optional parameters by calling 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().traces_get("projectId", "traceId") + .doit(); + +match result { + Err(e) => match e { + // The Error enum provides details about what exactly happened. + // You can also just use its `Debug`, `Display` or `Error` traits + Error::HttpError(_) + |Error::MissingAPIKey + |Error::MissingToken(_) + |Error::Cancelled + |Error::UploadSizeLimitExceeded(_, _) + |Error::Failure(_) + |Error::BadRequest(_) + |Error::FieldClash(_) + |Error::JsonDecodeError(_, _) => println!("{}", e), + }, + Ok(res) => println!("Success: {:?}", res), +} + +``` +## Handling Errors + +All errors produced by the system are provided either as [Result](http://byron.github.io/google-apis-rs/google_cloudtrace1/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_cloudtrace1/trait.Delegate.html), or the [Authenticator Delegate](http://byron.github.io/google-apis-rs/google_cloudtrace1/../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 Downloads +If a method supports downloads, the response body, which is part of the [Result](http://byron.github.io/google-apis-rs/google_cloudtrace1/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_cloudtrace1/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_cloudtrace1/trait.Delegate.html) to the +[Method Builder](http://byron.github.io/google-apis-rs/google_cloudtrace1/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_cloudtrace1/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_cloudtrace1/trait.RequestValue.html) and +[decodable](http://byron.github.io/google-apis-rs/google_cloudtrace1/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_cloudtrace1/trait.Part.html) which are identifiable 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_cloudtrace1/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_cloudtrace1/trait.RequestValue.html) are moved + +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 **cloudtrace1** 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/cloudtrace1/src/build.rs b/gen/cloudtrace1/src/build.rs new file mode 100644 index 0000000000..bcbc2128bb --- /dev/null +++ b/gen/cloudtrace1/src/build.rs @@ -0,0 +1,16 @@ +extern crate syntex; +extern crate serde_codegen; + +use std::env; +use std::path::Path; + +pub fn main() { + let out_dir = env::var_os("OUT_DIR").unwrap(); + + let src = Path::new("src/lib.rs.in"); + let dst = Path::new(&out_dir).join("lib.rs"); + + let mut registry = syntex::Registry::new(); + serde_codegen::register(&mut registry); + registry.expand("google-cloudtrace1", &src, &dst).unwrap(); +} diff --git a/gen/cloudtrace1/src/cmn.rs b/gen/cloudtrace1/src/cmn.rs new file mode 100644 index 0000000000..0e31353ba3 --- /dev/null +++ b/gen/cloudtrace1/src/cmn.rs @@ -0,0 +1,762 @@ +// COPY OF 'src/rust/api/cmn.rs' +// DO NOT EDIT +use std::io::{self, Read, Seek, Cursor, Write, SeekFrom}; +use std; +use std::fmt::{self, Display}; +use std::str::FromStr; +use std::error; +use std::thread::sleep_ms; + +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::h1::LINE_ENDING; +use hyper::method::Method; +use hyper::status::StatusCode; + +use serde_json as json; + +/// 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 {} + +/// Identifies types for building methods of a particular resource type +pub trait MethodsBuilder {} + +/// Identifies types which represent builders for a particular resource method +pub trait CallBuilder {} + +/// Identifies types which can be inserted and deleted. +/// Types with this trait are most commonly used by clients of this API. +pub trait Resource {} + +/// Identifies types which are used in API responses. +pub trait ResponseResult {} + +/// Identifies types which are used in API requests. +pub trait RequestValue {} + +/// Identifies types which are not actually used by the API +/// This might be a bug within the google API schema. +pub trait UnusedType {} + +/// Identifies types which are only used as part of other types, which +/// usually are carrying the `Resource` trait. +pub trait Part {} + +/// 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 {} + +/// 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 +} + +/// A utility to represent detailed errors we might see in case there are BadRequests. +/// The latter happen if the sent parameters or request structures are unsound +#[derive(Deserialize, Serialize, Debug)] +pub struct ErrorResponse { + error: ServerError, +} + +#[derive(Deserialize, Serialize, Debug)] +pub struct ServerError { + errors: Vec, + code: u16, + message: String, +} + +#[derive(Deserialize, Serialize, Debug)] +pub struct ServerMessage { + domain: String, + reason: String, + message: String, + #[serde(rename="locationType")] + location_type: Option, + location: 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 successful. That way, the delegate 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. + /// + /// If you choose to retry after a duration, the duration should be chosen using the + /// [exponential backoff algorithm](http://en.wikipedia.org/wiki/Exponential_backoff). + /// + /// Return retry information. + fn http_error(&mut self, &hyper::Error) -> 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 it as a general information about the + /// impending failure. + /// The given Error provides information about why the token couldn't be acquired in the + /// first place + fn token(&mut self, err: &error::Error) -> Option { + let _ = err; + 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/canceled, 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()`. + /// It will also be called with None after a successful upload, which allows the delegate + /// to forget the URL. That way, we will not attempt to resume an upload that has already + /// finished. + fn store_upload_url(&mut self, url: Option<&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: &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. + /// + /// If you choose to retry after a duration, the duration should be chosen using the + /// [exponential backoff algorithm](http://en.wikipedia.org/wiki/Exponential_backoff). + fn http_failure(&mut self, _: &hyper::client::Response, Option, _: 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 {} + + +#[derive(Debug)] +pub enum Error { + /// The http connection failed + HttpError(hyper::Error), + + /// 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), + + /// Represents information about a request that was not understood by the server. + /// Details are included. + BadRequest(ErrorResponse), + + /// 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(Box), + + /// 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(String, json::Error), + + /// Indicates an HTTP repsonse with a non-success status code + Failure(hyper::client::Response), +} + + +impl Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + Error::HttpError(ref err) => err.fmt(f), + Error::UploadSizeLimitExceeded(ref resource_size, ref max_size) => + writeln!(f, "The media size {} exceeds the maximum allowed upload size of {}" + , resource_size, max_size), + Error::MissingAPIKey => { + (writeln!(f, "The application's API key was not found in the configuration")).ok(); + writeln!(f, "It is used as there are no Scopes defined for this method.") + }, + Error::BadRequest(ref err) => { + try!(writeln!(f, "Bad Requst ({}): {}", err.error.code, err.error.message)); + for err in err.error.errors.iter() { + try!(writeln!(f, " {}: {}, {}{}", + err.domain, + err.message, + err.reason, + match &err.location { + &Some(ref loc) => format!("@{}", loc), + &None => String::new(), + })); + } + Ok(()) + }, + Error::MissingToken(ref err) => + writeln!(f, "Token retrieval failed with error: {}", err), + Error::Cancelled => + writeln!(f, "Operation cancelled by delegate"), + Error::FieldClash(field) => + writeln!(f, "The custom parameter '{}' is already provided natively by the CallBuilder.", field), + Error::JsonDecodeError(ref json_str, ref err) + => writeln!(f, "{}: {}", err, json_str), + Error::Failure(ref response) => + writeln!(f, "Http status indicates failure: {:?}", response), + } + } +} + +impl error::Error for Error { + fn description(&self) -> &str { + match *self { + Error::HttpError(ref err) => err.description(), + Error::JsonDecodeError(_, ref err) => err.description(), + _ => "NO DESCRIPTION POSSIBLE - use `Display.fmt()` instead" + } + } + + fn cause(&self) -> Option<&error::Error> { + match *self { + Error::HttpError(ref err) => err.cause(), + Error::JsonDecodeError(_, ref err) => err.cause(), + _ => None + } + } +} + +/// A universal result type used as return for all calls. +pub type Result = std::result::Result; + +/// 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 + 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 following macro invocation needs to be expanded, as `include!` +// doens't support external macros +// header!{ +// #[doc="The `X-Upload-Content-Type` header."] +// (XUploadContentType, "X-Upload-Content-Type") => [Mime] + +// xupload_content_type { +// test_header!( +// test1, +// vec![b"text/plain"], +// Some(HeaderField( +// vec![Mime(TopLevel::Text, SubLevel::Plain, Vec::new())] +// ))); + +// } +// } + +/// The `X-Upload-Content-Type` header. +/// +/// Generated via rustc --pretty expanded -Z unstable-options, and manually +/// processed to be more readable. +#[derive(PartialEq, Debug, Clone)] +pub struct XUploadContentType(pub Mime); + +impl ::std::ops::Deref for XUploadContentType { + type Target = Mime; + fn deref<'a>(&'a self) -> &'a Mime { &self.0 } +} +impl ::std::ops::DerefMut for XUploadContentType { + fn deref_mut<'a>(&'a mut self) -> &'a mut Mime { &mut self.0 } +} +impl Header for XUploadContentType { + fn header_name() -> &'static str { "X-Upload-Content-Type" } + fn parse_header(raw: &[Vec]) -> hyper::error::Result { + hyper::header::parsing::from_one_raw_str(raw).map(XUploadContentType) + } +} +impl HeaderFormat for XUploadContentType { + fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { + Display::fmt(&**self, f) + } +} +impl Display for XUploadContentType { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Display::fmt(&**self, f) + } +} + +#[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]) -> hyper::error::Result { + Err(hyper::error::Error::Method) + } +} + + +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]) -> hyper::error::Result { + if raw.len() > 0 { + let v = &raw[0]; + if let Ok(s) = std::str::from_utf8(v) { + const PREFIX: &'static str = "bytes "; + if s.starts_with(PREFIX) { + if let Ok(c) = ::from_str(&s[PREFIX.len()..]) { + return Ok(RangeResponseHeader(c)) + } + } + } + } + Err(hyper::error::Error::Method) + } +} + +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, 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, A> ResumableUploadHelper<'a, A> + where A: oauth2::GetToken { + + fn query_transfer_status(&mut self) -> std::result::Result> { + 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, None) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + return Err(Ok(r)) + } + }; + return Ok(h.0.last) + } + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + return Err(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() { + Ok(s) => s, + Err(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 + }; + + self.reader.seek(SeekFrom::Start(start)).unwrap(); + loop { + let request_size = match self.content_length - start { + rs if rs > chunk_size => chunk_size, + rs => rs + }; + + 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 + } + // workaround https://github.com/rust-lang/rust/issues/22252 + let res = 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(); + match res { + 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, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + } + return Some(Ok(res)) + }, + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + return Some(Err(err)) + } + } + } + } +} + +// Copy of src/rust/cli/cmn.rs +// TODO(ST): Allow sharing common code between program types +pub fn remove_json_null_values(value: &mut json::value::Value) { + match *value { + json::value::Value::Object(ref mut map) => { + let mut for_removal = Vec::new(); + + for (key, mut value) in map.iter_mut() { + if value.is_null() { + for_removal.push(key.clone()); + } else { + remove_json_null_values(&mut value); + } + } + + for key in &for_removal { + map.remove(key); + } + } + _ => {} + } +} diff --git a/gen/cloudtrace1/src/lib.rs b/gen/cloudtrace1/src/lib.rs new file mode 100644 index 0000000000..b09518a810 --- /dev/null +++ b/gen/cloudtrace1/src/lib.rs @@ -0,0 +1,180 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/api/lib.rs.mako' +// DO NOT EDIT ! + +//! This documentation was generated from *cloudtrace* crate version *0.1.9+20150825*, where *20150825* is the exact revision of the *cloudtrace:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +//! +//! Everything else about the *cloudtrace* *v1* API can be found at the +//! [official documentation site](https://cloud.google.com/tools/cloud-trace). +//! The original source code is [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/cloudtrace1). +//! # Features +//! +//! Handle the following *Resources* with ease from the central [hub](struct.Cloudtrace.html) ... +//! +//! * projects +//! * [*patch traces*](struct.ProjectPatchTraceCall.html), [*traces get*](struct.ProjectTraceGetCall.html) and [*traces list*](struct.ProjectTraceListCall.html) +//! +//! Other activities are ... +//! +//! * [get discovery](struct.MethodGetDiscoveryCall.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.Cloudtrace.html)** +//! * a central object to maintain state and allow accessing all *Activities* +//! * creates [*Method Builders*](trait.MethodsBuilder.html) which in turn +//! allow access to individual [*Call Builders*](trait.CallBuilder.html) +//! * **[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* +//! +//! All *structures* are marked with applicable traits to further categorize them and ease browsing. +//! +//! Generally speaking, you can invoke *Activities* like this: +//! +//! ```Rust,ignore +//! let r = hub.resource().activity(...).doit() +//! ``` +//! +//! Or specifically ... +//! +//! ```ignore +//! let r = hub.projects().traces_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-cloudtrace1 = "*" +//! ``` +//! +//! ## A complete example +//! +//! ```test_harness,no_run +//! extern crate hyper; +//! extern crate yup_oauth2 as oauth2; +//! extern crate google_cloudtrace1 as cloudtrace1; +//! use cloudtrace1::{Result, Error}; +//! # #[test] fn egal() { +//! use std::default::Default; +//! use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +//! use cloudtrace1::Cloudtrace; +//! +//! // 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 = Cloudtrace::new(hyper::Client::new(), auth); +//! // You can configure optional parameters by calling 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().traces_get("projectId", "traceId") +//! .doit(); +//! +//! match result { +//! Err(e) => match e { +//! // The Error enum provides details about what exactly happened. +//! // You can also just use its `Debug`, `Display` or `Error` traits +//! Error::HttpError(_) +//! |Error::MissingAPIKey +//! |Error::MissingToken(_) +//! |Error::Cancelled +//! |Error::UploadSizeLimitExceeded(_, _) +//! |Error::Failure(_) +//! |Error::BadRequest(_) +//! |Error::FieldClash(_) +//! |Error::JsonDecodeError(_, _) => println!("{}", e), +//! }, +//! Ok(res) => println!("Success: {:?}", res), +//! } +//! # } +//! ``` +//! ## 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 Downloads +//! 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 identifiable 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 moved +//! +//! 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 +//! +//! + +// 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)] + +include!(concat!(env!("OUT_DIR"), "/lib.rs")); \ No newline at end of file diff --git a/gen/cloudtrace1/src/lib.rs.in b/gen/cloudtrace1/src/lib.rs.in new file mode 100644 index 0000000000..394870e007 --- /dev/null +++ b/gen/cloudtrace1/src/lib.rs.in @@ -0,0 +1,1517 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/api/lib.rs.in.mako' +// DO NOT EDIT ! + +extern crate hyper; +extern crate serde; +extern crate serde_json; +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 serde_json as json; +use std::io; +use std::fs; +use std::thread::sleep_ms; + +pub use cmn::{MultiPartReader, ToParts, MethodInfo, Result, Error, CallBuilder, Hub, ReadSeek, Part, + ResponseResult, RequestValue, NestedType, Delegate, DefaultDelegate, MethodsBuilder, + Resource, ErrorResponse, remove_json_null_values}; + + +// ############## +// 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 AsRef for Scope { + fn as_ref(&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 Cloudtrace related resource activities +/// +/// # Examples +/// +/// Instantiate a new hub +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate yup_oauth2 as oauth2; +/// extern crate google_cloudtrace1 as cloudtrace1; +/// use cloudtrace1::{Result, Error}; +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use cloudtrace1::Cloudtrace; +/// +/// // 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 = Cloudtrace::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling 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().traces_get("projectId", "traceId") +/// .doit(); +/// +/// match result { +/// Err(e) => match e { +/// // The Error enum provides details about what exactly happened. +/// // You can also just use its `Debug`, `Display` or `Error` traits +/// Error::HttpError(_) +/// |Error::MissingAPIKey +/// |Error::MissingToken(_) +/// |Error::Cancelled +/// |Error::UploadSizeLimitExceeded(_, _) +/// |Error::Failure(_) +/// |Error::BadRequest(_) +/// |Error::FieldClash(_) +/// |Error::JsonDecodeError(_, _) => println!("{}", e), +/// }, +/// Ok(res) => println!("Success: {:?}", res), +/// } +/// # } +/// ``` +pub struct Cloudtrace { + client: RefCell, + auth: RefCell, + _user_agent: String, +} + +impl<'a, C, A> Hub for Cloudtrace {} + +impl<'a, C, A> Cloudtrace + where C: BorrowMut, A: oauth2::GetToken { + + pub fn new(client: C, authenticator: A) -> Cloudtrace { + Cloudtrace { + client: RefCell::new(client), + auth: RefCell::new(authenticator), + _user_agent: "google-api-rust-client/0.1.9".to_string(), + } + } + + pub fn methods(&'a self) -> MethodMethods<'a, C, A> { + MethodMethods { hub: &self } + } + pub fn projects(&'a self) -> ProjectMethods<'a, C, 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.9`. + /// + /// 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 response message for the ListTraces 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*). +/// +/// * [traces list projects](struct.ProjectTraceListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ListTracesResponse { + /// If defined, indicates that there are more topics that match the request, and this value should be passed to the next ListTopicsRequest to continue. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// The list of trace records returned. + pub traces: Option>, +} + +impl ResponseResult for ListTracesResponse {} + + +/// A list of traces for the PatchTraces 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*). +/// +/// * [patch traces projects](struct.ProjectPatchTraceCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Traces { + /// A list of traces. + pub traces: Option>, +} + +impl RequestValue for Traces {} + + +/// A span is the data recorded with a single span. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct TraceSpan { + /// SpanKind distinguishes spans generated in a particular context. For example, two spans with the same name, one with the kind RPC_CLIENT, and the other with RPC_SERVER can indicate the queueing latency associated with the span. + pub kind: Option, + /// Identifies the parent of the current span. May be missing. Serialized bytes representation of SpanId. + #[serde(rename="parentSpanId")] + pub parent_span_id: Option, + /// The name of the trace. This is sanitized and displayed on the UI. This may be a method name or some other per-callsite name. For the same binary and the same call point, it is a good practice to choose a consistent name in order to correlate cross-trace spans. + pub name: Option, + /// The start time of the span in nanoseconds from the UNIX epoch. + #[serde(rename="startTime")] + pub start_time: Option, + /// Identifier of the span within the trace. Each span should have an identifier that is unique per trace. + #[serde(rename="spanId")] + pub span_id: Option, + /// Annotations via labels. + pub labels: Option>, + /// The end time of the span in nanoseconds from the UNIX epoch. + #[serde(rename="endTime")] + pub end_time: Option, +} + +impl Part for TraceSpan {} + + +/// A generic empty message that you can re-use to avoid defining duplicated empty messages in your APIs. A typical example is to use it as the request or the response type of an API method. For instance: service Foo { rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); } The JSON representation for `Empty` is empty JSON object `{}`. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where 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 traces projects](struct.ProjectPatchTraceCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Empty; + +impl ResponseResult for Empty {} + + +/// A Trace is a collection of spans describing the execution timings of a single 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*). +/// +/// * [traces get projects](struct.ProjectTraceGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Trace { + /// The Project ID of the Google Cloud project. + #[serde(rename="projectId")] + pub project_id: Option, + /// A 128-bit numeric value, formatted as a 32-byte hex string, that represents a trace. Each trace should have an identifier that is globally unique. + #[serde(rename="traceId")] + pub trace_id: Option, + /// The collection of span records within this trace. Spans that appear in calls to PatchTraces may be incomplete or partial. + pub spans: Option>, +} + +impl ResponseResult for Trace {} + + + +// ################### +// 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 `Cloudtrace` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate yup_oauth2 as oauth2; +/// extern crate google_cloudtrace1 as cloudtrace1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use cloudtrace1::Cloudtrace; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Cloudtrace::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get_discovery(...)` +/// // to build up your call. +/// let rb = hub.methods(); +/// # } +/// ``` +pub struct MethodMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Cloudtrace, +} + +impl<'a, C, A> MethodsBuilder for MethodMethods<'a, C, A> {} + +impl<'a, C, A> MethodMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Returns a discovery document in the specified `format`. The typeurl in the returned google.protobuf.Any value depends on the requested format. + pub fn get_discovery(&self) -> MethodGetDiscoveryCall<'a, C, A> { + MethodGetDiscoveryCall { + hub: self.hub, + _version: Default::default(), + _labels: Default::default(), + _format: Default::default(), + _args: Default::default(), + _delegate: 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 `Cloudtrace` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate yup_oauth2 as oauth2; +/// extern crate google_cloudtrace1 as cloudtrace1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use cloudtrace1::Cloudtrace; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Cloudtrace::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `patch_traces(...)`, `traces_get(...)` and `traces_list(...)` +/// // to build up your call. +/// let rb = hub.projects(); +/// # } +/// ``` +pub struct ProjectMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Cloudtrace, +} + +impl<'a, C, A> MethodsBuilder for ProjectMethods<'a, C, A> {} + +impl<'a, C, A> ProjectMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Gets one trace by id. + /// + /// # Arguments + /// + /// * `projectId` - The project id of the trace to return. + /// * `traceId` - The trace id of the trace to return. + pub fn traces_get(&self, project_id: &str, trace_id: &str) -> ProjectTraceGetCall<'a, C, A> { + ProjectTraceGetCall { + hub: self.hub, + _project_id: project_id.to_string(), + _trace_id: trace_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 existing traces specified by PatchTracesRequest and inserts the new traces. Any existing trace or span fields included in an update are overwritten by the update, and any additional fields in an update are merged with the existing trace data. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `projectId` - The project id of the trace to patch. + pub fn patch_traces(&self, request: Traces, project_id: &str) -> ProjectPatchTraceCall<'a, C, A> { + ProjectPatchTraceCall { + hub: self.hub, + _request: request, + _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: + /// + /// List traces matching the filter expression. + /// + /// # Arguments + /// + /// * `projectId` - The stringified-version of the project id. + pub fn traces_list(&self, project_id: &str) -> ProjectTraceListCall<'a, C, A> { + ProjectTraceListCall { + hub: self.hub, + _project_id: project_id.to_string(), + _view: Default::default(), + _start_time: Default::default(), + _page_token: Default::default(), + _page_size: Default::default(), + _order_by: Default::default(), + _filter: Default::default(), + _end_time: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + + + +// ################### +// CallBuilders ### +// ################# + +/// Returns a discovery document in the specified `format`. The typeurl in the returned google.protobuf.Any value depends on the requested format. +/// +/// A builder for the *getDiscovery* method. +/// It is not used directly, but through a `MethodMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_cloudtrace1 as cloudtrace1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use cloudtrace1::Cloudtrace; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Cloudtrace::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling 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().get_discovery() +/// .version("et") +/// .add_labels("dolores") +/// .format("kasd") +/// .add_args("accusam") +/// .doit(); +/// # } +/// ``` +pub struct MethodGetDiscoveryCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Cloudtrace, + _version: Option, + _labels: Vec, + _format: Option, + _args: Vec, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, +} + +impl<'a, C, A> CallBuilder for MethodGetDiscoveryCall<'a, C, A> {} + +impl<'a, C, A> MethodGetDiscoveryCall<'a, C, A> where 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: "cloudtrace.getDiscovery", + 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._version { + params.push(("version", 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._format { + params.push(("format", value.to_string())); + } + if self._args.len() > 0 { + let mut s = String::new(); + for f in self._args.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("args", s)); + } + for &field in ["version", "labels", "format", "args"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://cloudtrace.googleapis.com/v1/discovery".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 Err(Error::MissingAPIKey) + } + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + 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) + .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_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = res; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The API version of the requested discovery doc. + /// + /// Sets the *version* query property to the given value. + pub fn version(mut self, new_value: &str) -> MethodGetDiscoveryCall<'a, C, A> { + self._version = Some(new_value.to_string()); + self + } + /// A list of labels (like visibility) influencing the scope of the requested doc. + /// + /// 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. + pub fn add_labels(mut self, new_value: &str) -> MethodGetDiscoveryCall<'a, C, A> { + self._labels.push(new_value.to_string()); + self + } + /// The format requested for discovery. + /// + /// Sets the *format* query property to the given value. + pub fn format(mut self, new_value: &str) -> MethodGetDiscoveryCall<'a, C, A> { + self._format = Some(new_value.to_string()); + self + } + /// Any additional arguments. + /// + /// Append the given value to the *args* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + pub fn add_args(mut self, new_value: &str) -> MethodGetDiscoveryCall<'a, C, A> { + self._args.push(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> MethodGetDiscoveryCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> MethodGetDiscoveryCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + +} + + +/// Gets one trace by id. +/// +/// A builder for the *traces.get* method supported by a *project* resource. +/// It is not used directly, but through a `ProjectMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_cloudtrace1 as cloudtrace1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use cloudtrace1::Cloudtrace; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Cloudtrace::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling 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().traces_get("projectId", "traceId") +/// .doit(); +/// # } +/// ``` +pub struct ProjectTraceGetCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Cloudtrace, + _project_id: String, + _trace_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ProjectTraceGetCall<'a, C, A> {} + +impl<'a, C, A> ProjectTraceGetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Trace)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "cloudtrace.projects.traces.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(("traceId", self._trace_id.to_string())); + for &field in ["alt", "projectId", "traceId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://cloudtrace.googleapis.com/v1/projects/{projectId}/traces/{traceId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{projectId}", "projectId"), ("{traceId}", "traceId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["traceId", "projectId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The project id of the trace to return. + /// + /// 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. + pub fn project_id(mut self, new_value: &str) -> ProjectTraceGetCall<'a, C, A> { + self._project_id = new_value.to_string(); + self + } + /// The trace id of the trace to return. + /// + /// Sets the *trace id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn trace_id(mut self, new_value: &str) -> ProjectTraceGetCall<'a, C, A> { + self._trace_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectTraceGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> ProjectTraceGetCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProjectTraceGetCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Updates the existing traces specified by PatchTracesRequest and inserts the new traces. Any existing trace or span fields included in an update are overwritten by the update, and any additional fields in an update are merged with the existing trace data. +/// +/// A builder for the *patchTraces* method supported by a *project* resource. +/// It is not used directly, but through a `ProjectMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_cloudtrace1 as cloudtrace1; +/// use cloudtrace1::Traces; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use cloudtrace1::Cloudtrace; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Cloudtrace::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req = Traces::default(); +/// +/// // You can configure optional parameters by calling 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().patch_traces(req, "projectId") +/// .doit(); +/// # } +/// ``` +pub struct ProjectPatchTraceCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Cloudtrace, + _request: Traces, + _project_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ProjectPatchTraceCall<'a, C, A> {} + +impl<'a, C, A> ProjectPatchTraceCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Empty)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "cloudtrace.projects.patchTraces", + http_method: hyper::method::Method::Patch }); + 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 Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://cloudtrace.googleapis.com/v1/projects/{projectId}/traces".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: Traces) -> ProjectPatchTraceCall<'a, C, A> { + self._request = new_value; + self + } + /// The project id of the trace to patch. + /// + /// 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. + pub fn project_id(mut self, new_value: &str) -> ProjectPatchTraceCall<'a, C, A> { + self._project_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectPatchTraceCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> ProjectPatchTraceCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProjectPatchTraceCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// List traces matching the filter expression. +/// +/// A builder for the *traces.list* method supported by a *project* resource. +/// It is not used directly, but through a `ProjectMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_cloudtrace1 as cloudtrace1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use cloudtrace1::Cloudtrace; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Cloudtrace::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling 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().traces_list("projectId") +/// .view("labore") +/// .start_time("sea") +/// .page_token("nonumy") +/// .page_size(-19) +/// .order_by("gubergren") +/// .filter("sadipscing") +/// .end_time("aliquyam") +/// .doit(); +/// # } +/// ``` +pub struct ProjectTraceListCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Cloudtrace, + _project_id: String, + _view: Option, + _start_time: Option, + _page_token: Option, + _page_size: Option, + _order_by: Option, + _filter: Option, + _end_time: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ProjectTraceListCall<'a, C, A> {} + +impl<'a, C, A> ProjectTraceListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ListTracesResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "cloudtrace.projects.traces.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((10 + self._additional_params.len())); + params.push(("projectId", self._project_id.to_string())); + if let Some(value) = self._view { + params.push(("view", value.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._page_size { + params.push(("pageSize", value.to_string())); + } + if let Some(value) = self._order_by { + params.push(("orderBy", value.to_string())); + } + if let Some(value) = self._filter { + params.push(("filter", value.to_string())); + } + if let Some(value) = self._end_time { + params.push(("endTime", value.to_string())); + } + for &field in ["alt", "projectId", "view", "startTime", "pageToken", "pageSize", "orderBy", "filter", "endTime"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://cloudtrace.googleapis.com/v1/projects/{projectId}/traces".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The stringified-version of the project id. + /// + /// 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. + pub fn project_id(mut self, new_value: &str) -> ProjectTraceListCall<'a, C, A> { + self._project_id = new_value.to_string(); + self + } + /// ViewType specifies the projection of the result. + /// + /// Sets the *view* query property to the given value. + pub fn view(mut self, new_value: &str) -> ProjectTraceListCall<'a, C, A> { + self._view = Some(new_value.to_string()); + self + } + /// End of the time interval (inclusive). + /// + /// Sets the *start time* query property to the given value. + pub fn start_time(mut self, new_value: &str) -> ProjectTraceListCall<'a, C, A> { + self._start_time = Some(new_value.to_string()); + self + } + /// The token identifying the page of results to return from the ListTraces method. If present, this value is should be taken from the next_page_token field of a previous ListTracesResponse. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> ProjectTraceListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Maximum number of topics to return. If not specified or <= 0, the implementation will select a reasonable value. The implemenation may always return fewer than the requested page_size. + /// + /// Sets the *page size* query property to the given value. + pub fn page_size(mut self, new_value: i32) -> ProjectTraceListCall<'a, C, A> { + self._page_size = Some(new_value); + self + } + /// The trace field used to establish the order of traces returned by the ListTraces method. Possible options are: trace_id name (name field of root span) duration (different between end_time and start_time fields of root span) start (start_time field of root span) Descending order can be specified by appending "desc" to the sort field: name desc Only one sort field is permitted, though this may change in the future. + /// + /// Sets the *order by* query property to the given value. + pub fn order_by(mut self, new_value: &str) -> ProjectTraceListCall<'a, C, A> { + self._order_by = Some(new_value.to_string()); + self + } + /// An optional filter for the request. + /// + /// Sets the *filter* query property to the given value. + pub fn filter(mut self, new_value: &str) -> ProjectTraceListCall<'a, C, A> { + self._filter = Some(new_value.to_string()); + self + } + /// Start of the time interval (exclusive). + /// + /// Sets the *end time* query property to the given value. + pub fn end_time(mut self, new_value: &str) -> ProjectTraceListCall<'a, C, A> { + self._end_time = Some(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectTraceListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> ProjectTraceListCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProjectTraceListCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + diff --git a/gen/clouduseraccountsvm_beta-cli/Cargo.toml b/gen/clouduseraccountsvm_beta-cli/Cargo.toml new file mode 100644 index 0000000000..6580fff018 --- /dev/null +++ b/gen/clouduseraccountsvm_beta-cli/Cargo.toml @@ -0,0 +1,35 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-clouduseraccountsvm_beta-cli" +version = "0.3.2+20150924" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with Cloud User Accounts (protocol vm_beta)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/clouduseraccountsvm_beta-cli" +homepage = "https://cloud.google.com/compute/docs/access/user-accounts/api/latest/" +documentation = "http://byron.github.io/google-apis-rs/google_clouduseraccountsvm_beta_cli" +license = "MIT" +keywords = ["clouduseraccounts", "google", "cli"] + +[[bin]] +name = "clouduseraccountsvm-beta" + +[dependencies] +hyper = ">= 0.6.8" +mime = "0.1.0" +serde = ">= 0.6.0" +serde_json = ">= 0.6.0" +yup-oauth2 = "*" +strsim = "*" +yup-hyper-mock = ">=1.0.0" +clap = ">= 1.0.3" + +[build-dependencies] +syntex = { version = "*" } +serde_codegen = { version = "*" } + + +[dependencies.google-clouduseraccountsvm_beta] +path = "../clouduseraccountsvm_beta" diff --git a/gen/clouduseraccountsvm_beta-cli/LICENSE.md b/gen/clouduseraccountsvm_beta-cli/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/clouduseraccountsvm_beta-cli/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/clouduseraccountsvm_beta-cli/README.md b/gen/clouduseraccountsvm_beta-cli/README.md new file mode 100644 index 0000000000..f2a3694880 --- /dev/null +++ b/gen/clouduseraccountsvm_beta-cli/README.md @@ -0,0 +1,132 @@ + +The `clouduseraccountsvm-beta` command-line interface *(CLI)* allows to use most features of the *Google Cloud User Accounts* service from the comfort of your terminal. + +By default all output is printed to standard out, but flags can be set to direct it into a file independent of your shell's +capabilities. Errors will be printed to standard error, and cause the program's exit code to be non-zero. + +If data-structures are requested, these will be returned as pretty-printed JSON, to be useful as input to other tools. + +Everything else about the *Cloud User Accounts* API can be found at the +[official documentation site](https://cloud.google.com/compute/docs/access/user-accounts/api/latest/). + +# Downloads + +You can download the pre-compiled 64bit binaries for the following platforms: + +* ![icon](http://megaicons.net/static/img/icons_sizes/6/140/16/ubuntu-icon.png) [ubuntu](http://dl.byronimo.de/google.rs/cli/0.3.2/ubuntu/clouduseraccountsvm-beta.tar.gz) +* ![icon](http://hydra-media.cursecdn.com/wow.gamepedia.com/a/a2/Apple-icon-16x16.png?version=25ddd67ac3dd3b634478e3978b76cb74) [osx](http://dl.byronimo.de/google.rs/cli/0.3.2/osx/clouduseraccountsvm-beta.tar.gz) + +Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/clouduseraccountsvm_beta-cli). + +# Usage + +This documentation was generated from the *Cloud User Accounts* API at revision *20150924*. The CLI is at version *0.3.2*. + +```bash +clouduseraccountsvm-beta [options] + global-accounts-operations + delete [-p ]... + get [-p ]... [-o ] + list [-p ]... [-o ] + groups + add-member (-r )... [-p ]... [-o ] + delete [-p ]... [-o ] + get [-p ]... [-o ] + insert (-r )... [-p ]... [-o ] + list [-p ]... [-o ] + remove-member (-r )... [-p ]... [-o ] + linux + get-authorized-keys-view [-p ]... [-o ] + get-linux-account-views [-p ]... [-o ] + users + add-public-key (-r )... [-p ]... [-o ] + delete [-p ]... [-o ] + get [-p ]... [-o ] + insert (-r )... [-p ]... [-o ] + list [-p ]... [-o ] + remove-public-key [-p ]... [-o ] + clouduseraccountsvm-beta --help + +Configuration: + [--scope ]... + Specify the authentication a method should be executed in. Each scope + requires the user to grant this application permission to use it. + If unset, it defaults to the shortest scope url for a particular method. + --config-dir + A directory into which we will store our persistent data. Defaults to + a user-writable directory that we will create during the first invocation. + [default: ~/.google-service-cli] + --debug + Output all server communication to standard error. `tx` and `rx` are placed + into the same stream. + --debug-auth + Output all communication related to authentication to standard error. `tx` + and `rx` are placed into the same stream. + +``` + +# Configuration + +The program will store all persistent data in the `~/.google-service-cli` directory in *JSON* files prefixed with `clouduseraccountsvm-beta-`. You can change the directory used to store configuration with the `--config-dir` flag on a per-invocation basis. + +More information about the various kinds of persistent data are given in the following paragraphs. + +# Authentication + +Most APIs require a user to authenticate any request. If this is the case, the [scope][scopes] determines the +set of permissions granted. The granularity of these is usually no more than *read-only* or *full-access*. + +If not set, the system will automatically select the smallest feasible scope, e.g. when invoking a +method that is read-only, it will ask only for a read-only scope. +You may use the `--scope` flag to specify a scope directly. +All applicable scopes are documented in the respective method's CLI documentation. + +The first time a scope is used, the user is asked for permission. Follow the instructions given +by the CLI to grant permissions, or to decline. + +If a scope was authenticated by the user, the respective information will be stored as *JSON* in the configuration +directory, e.g. `~/.google-service-cli/clouduseraccountsvm-beta-token-.json`. No manual management of these tokens +is necessary. + +To revoke granted authentication, please refer to the [official documentation][revoke-access]. + +# Application Secrets + +In order to allow any application to use Google services, it will need to be registered using the +[Google Developer Console][google-dev-console]. APIs the application may use are then enabled for it +one by one. Most APIs can be used for free and have a daily quota. + +To allow more comfortable usage of the CLI without forcing anyone to register an own application, the CLI +comes with a default application secret that is configured accordingly. This also means that heavy usage +all around the world may deplete the daily quota. + +You can workaround this limitation by putting your own secrets file at this location: +`~/.google-service-cli/clouduseraccountsvm-beta-secret.json`, assuming that the required *clouduseraccounts* API +was enabled for it. Such a secret file can be downloaded in the *Google Developer Console* at +*APIs & auth -> Credentials -> Download JSON* and used as is. + +Learn more about how to setup Google projects and enable APIs using the [official documentation][google-project-new]. + + +# Debugging + +Even though the CLI does its best to provide usable error messages, sometimes it might be desirable to know +what exactly led to a particular issue. This is done by allowing all client-server communication to be +output to standard error *as-is*. + +The `--debug` flag will print all client-server communication to standard error, whereas the `--debug-auth` flag +will cause all communication related to authentication to standard error. +If the `--debug` flag is set, error-results will be debug-printed, possibly yielding more information about the +issue at hand. + +You may consider redirecting standard error into a file for ease of use, e.g. `clouduseraccountsvm-beta --debug [options] 2>debug.txt`. + + +[scopes]: https://developers.google.com/+/api/oauth#scopes +[revoke-access]: http://webapps.stackexchange.com/a/30849 +[google-dev-console]: https://console.developers.google.com/ +[google-project-new]: https://developers.google.com/console/help/new/ \ No newline at end of file diff --git a/gen/clouduseraccountsvm_beta-cli/mkdocs.yml b/gen/clouduseraccountsvm_beta-cli/mkdocs.yml new file mode 100644 index 0000000000..08da5113af --- /dev/null +++ b/gen/clouduseraccountsvm_beta-cli/mkdocs.yml @@ -0,0 +1,33 @@ +site_name: Cloud User Accounts v0.3.2+20150924 +site_url: http://byron.github.io/google-apis-rs/google-clouduseraccountsvm_beta-cli +site_description: Write integrating applications with bcore + +repo_url: https://github.com/Byron/google-apis-rs/tree/master/gen/clouduseraccountsvm_beta-cli + +docs_dir: docs +site_dir: build_html + +pages: +- ['index.md', 'Home'] +- ['global-accounts-operations_delete.md', 'Global Accounts Operations', 'Delete'] +- ['global-accounts-operations_get.md', 'Global Accounts Operations', 'Get'] +- ['global-accounts-operations_list.md', 'Global Accounts Operations', 'List'] +- ['groups_add-member.md', 'Groups', 'Add Member'] +- ['groups_delete.md', 'Groups', 'Delete'] +- ['groups_get.md', 'Groups', 'Get'] +- ['groups_insert.md', 'Groups', 'Insert'] +- ['groups_list.md', 'Groups', 'List'] +- ['groups_remove-member.md', 'Groups', 'Remove Member'] +- ['linux_get-authorized-keys-view.md', 'Linux', 'Get Authorized Keys View'] +- ['linux_get-linux-account-views.md', 'Linux', 'Get Linux Account Views'] +- ['users_add-public-key.md', 'Users', 'Add Public Key'] +- ['users_delete.md', 'Users', 'Delete'] +- ['users_get.md', 'Users', 'Get'] +- ['users_insert.md', 'Users', 'Insert'] +- ['users_list.md', 'Users', 'List'] +- ['users_remove-public-key.md', 'Users', 'Remove Public Key'] + +theme: readthedocs + +copyright: Copyright © 2015, `Sebastian Thiel` + diff --git a/gen/clouduseraccountsvm_beta-cli/src/cmn.rs b/gen/clouduseraccountsvm_beta-cli/src/cmn.rs new file mode 100644 index 0000000000..8358f156fa --- /dev/null +++ b/gen/clouduseraccountsvm_beta-cli/src/cmn.rs @@ -0,0 +1,721 @@ +// COPY OF 'src/rust/cli/cmn.rs' +// DO NOT EDIT +use oauth2::{ApplicationSecret, ConsoleApplicationSecret, TokenStorage, Token}; +use serde_json as json; +use serde_json::value::Value; +use mime::Mime; +use clap::{App, SubCommand}; +use strsim; + +use std::fs; +use std::env; +use std::io; +use std::fmt; +use std::path::{Path, PathBuf}; +use std::str::FromStr; +use std::string::ToString; +use std::io::{Write, Read, stdout}; + +use std::default::Default; + +const FIELD_SEP: char = '.'; + + +pub enum ComplexType { + Pod, + Vec, + Map, +} + + // Null, + // Bool(bool), + // I64(i64), + // U64(u64), + // F64(f64), + // String(String), + +pub enum JsonType { + Boolean, + Int, + Uint, + Float, + String, +} + +pub struct JsonTypeInfo { + pub jtype: JsonType, + pub ctype: ComplexType, +} + +// Based on @erickt user comment. Thanks for the idea ! +// Remove all keys whose values are null from given value (changed in place) +pub fn remove_json_null_values(value: &mut Value) { + match *value { + Value::Object(ref mut map) => { + let mut for_removal = Vec::new(); + + for (key, mut value) in map.iter_mut() { + if value.is_null() { + for_removal.push(key.clone()); + } else { + remove_json_null_values(&mut value); + } + } + + for key in &for_removal { + map.remove(key); + } + } + _ => {} + } +} + +fn did_you_mean<'a>(v: &str, possible_values: &[&'a str]) -> Option<&'a str> { + + let mut candidate: Option<(f64, &str)> = None; + for pv in possible_values { + let confidence = strsim::jaro_winkler(v, pv); + if confidence > 0.8 && (candidate.is_none() || (candidate.as_ref().unwrap().0 < confidence)) { + candidate = Some((confidence, pv)); + } + } + match candidate { + None => None, + Some((_, candidate)) => Some(candidate), + } +} + +pub enum CallType { + Upload(UploadProtocol), + Standard, +} + +arg_enum!{ + pub enum UploadProtocol { + Simple, + Resumable + } +} + +impl AsRef for UploadProtocol { + fn as_ref(&self) -> &str { + match *self { + UploadProtocol::Simple => "simple", + UploadProtocol::Resumable => "resumable" + } + } +} + +impl AsRef for CallType { + fn as_ref(&self) -> &str { + match *self { + CallType::Upload(ref proto) => proto.as_ref(), + CallType::Standard => "standard-request" + } + } +} + +#[derive(Clone, Default)] +pub struct FieldCursor(Vec); + +impl ToString for FieldCursor { + fn to_string(&self) -> String { + self.0.join(".") + } +} + +impl From<&'static str> for FieldCursor { + fn from(value: &'static str) -> FieldCursor { + let mut res = FieldCursor::default(); + res.set(value).unwrap(); + res + } +} + +impl FieldCursor { + pub fn set(&mut self, value: &str) -> Result<(), CLIError> { + if value.len() == 0 { + return Err(CLIError::Field(FieldError::Empty)) + } + + let mut first_is_field_sep = false; + let mut char_count: usize = 0; + let mut last_c = FIELD_SEP; + let mut num_conscutive_field_seps = 0; + + let mut field = String::new(); + let mut fields = self.0.clone(); + + let push_field = |fs: &mut Vec, f: &mut String| { + if f.len() > 0 { + fs.push(f.clone()); + f.truncate(0); + } + }; + + for (cid, c) in value.chars().enumerate() { + char_count += 1; + + if c == FIELD_SEP { + if cid == 0 { + first_is_field_sep = true; + } + num_conscutive_field_seps += 1; + if cid > 0 && last_c == FIELD_SEP { + if fields.pop().is_none() { + return Err(CLIError::Field(FieldError::PopOnEmpty(value.to_string()))) + } + } else { + push_field(&mut fields, &mut field); + } + } else { + num_conscutive_field_seps = 0; + if cid == 1 { + if first_is_field_sep { + fields.truncate(0); + } + } + field.push(c); + } + + last_c = c; + } + + push_field(&mut fields, &mut field); + + if char_count == 1 && first_is_field_sep { + fields.truncate(0); + } + if char_count > 1 && num_conscutive_field_seps == 1 { + return Err(CLIError::Field(FieldError::TrailingFieldSep(value.to_string()))) + } + + self.0 = fields; + Ok(()) + } + + pub fn did_you_mean(value: &str, possible_values: &[&str]) -> Option { + if value.len() == 0 { + return None + } + + let mut last_c = FIELD_SEP; + + let mut field = String::new(); + let mut output = String::new(); + + let push_field = |fs: &mut String, f: &mut String| { + if f.len() > 0 { + fs.push_str( + match did_you_mean(&f, possible_values) { + Some(candidate) => candidate, + None => &f, + }); + f.truncate(0); + } + }; + + for (cid, c) in value.chars().enumerate() { + if c == FIELD_SEP { + if last_c != FIELD_SEP { + push_field(&mut output, &mut field); + } + output.push(c); + } else { + field.push(c); + } + + last_c = c; + } + + push_field(&mut output, &mut field); + + if &output == value { + None + } else { + Some(output) + } + } + + pub fn set_json_value(&self, mut object: &mut Value, + value: &str, type_info: JsonTypeInfo, + err: &mut InvalidOptionsError, + orig_cursor: &FieldCursor) { + assert!(self.0.len() > 0); + + for field in &self.0[..self.0.len()-1] { + let tmp = object; + object = + match *tmp { + Value::Object(ref mut mapping) => { + mapping.entry(field.to_owned()).or_insert( + Value::Object(Default::default()) + ) + }, + _ => panic!("We don't expect non-object Values here ...") + }; + } + + match *object { + Value::Object(ref mut mapping) => { + let field = &self.0[self.0.len()-1]; + let to_jval = + |value: &str, jtype: JsonType, err: &mut InvalidOptionsError| + -> Value { + match jtype { + JsonType::Boolean => + Value::Bool(arg_from_str(value, err, &field, "boolean")), + JsonType::Int => + Value::I64(arg_from_str(value, err, &field, "int")), + JsonType::Uint => + Value::U64(arg_from_str(value, err, &field, "uint")), + JsonType::Float => + Value::F64(arg_from_str(value, err, &field, "float")), + JsonType::String => + Value::String(value.to_owned()), + } + }; + + match type_info.ctype { + ComplexType::Pod => { + if mapping.insert(field.to_owned(), to_jval(value, type_info.jtype, err)).is_some() { + err.issues.push(CLIError::Field(FieldError::Duplicate(orig_cursor.to_string()))); + } + }, + ComplexType::Vec => { + match *mapping.entry(field.to_owned()) + .or_insert(Value::Array(Default::default())) { + Value::Array(ref mut values) => values.push(to_jval(value, type_info.jtype, err)), + _ => unreachable!() + } + }, + ComplexType::Map => { + let (key, value) = parse_kv_arg(value, err, true); + let jval = to_jval(value.unwrap_or(""), type_info.jtype, err); + + match *mapping.entry(field.to_owned()) + .or_insert(Value::Object(Default::default())) { + Value::Object(ref mut value_map) => { + if value_map.insert(key.to_owned(), jval).is_some() { + err.issues.push(CLIError::Field(FieldError::Duplicate(orig_cursor.to_string()))); + } + } + _ => unreachable!() + } + } + } + }, + _ => unreachable!() + } + } + + pub fn num_fields(&self) -> usize { + self.0.len() + } +} + +pub fn parse_kv_arg<'a>(kv: &'a str, err: &mut InvalidOptionsError, for_hashmap: bool) + -> (&'a str, Option<&'a str>) { + let mut add_err = || err.issues.push(CLIError::InvalidKeyValueSyntax(kv.to_string(),for_hashmap)); + match kv.find('=') { + None => { + add_err(); + return (kv, None) + }, + Some(pos) => { + let key = &kv[..pos]; + if kv.len() <= pos + 1 { + add_err(); + return (key, Some("")) + } + (key, Some(&kv[pos+1..])) + } + } +} + +pub fn calltype_from_str(name: &str, valid_protocols: Vec, err: &mut InvalidOptionsError) -> CallType { + CallType::Upload( + match UploadProtocol::from_str(name) { + Ok(up) => up, + Err(msg) => { + err.issues.push(CLIError::InvalidUploadProtocol(name.to_string(), valid_protocols)); + UploadProtocol::Simple + } + }) +} + +pub fn input_file_from_opts(file_path: &str, err: &mut InvalidOptionsError) -> Option { + match fs::File::open(file_path) { + Ok(f) => Some(f), + Err(io_err) => { + err.issues.push(CLIError::Input(InputError::IOError((file_path.to_string(), io_err)))); + None + } + } +} + +pub fn input_mime_from_opts(mime: &str, err: &mut InvalidOptionsError) -> Option { + match mime.parse() { + Ok(m) => Some(m), + Err(_) => { + err.issues.push(CLIError::Input(InputError::Mime(mime.to_string()))); + None + } + } +} + +pub fn writer_from_opts(arg: Option<&str>) -> Result, io::Error> { + let f = arg.unwrap_or("-"); + match f { + "-" => Ok(Box::new(stdout())), + _ => match fs::OpenOptions::new().create(true).write(true).open(f) { + Ok(f) => Ok(Box::new(f)), + Err(io_err) => Err(io_err), + } + } +} + + +pub fn arg_from_str<'a, T>(arg: &str, err: &mut InvalidOptionsError, + arg_name: &'a str, + arg_type: &'a str) -> T + where T: FromStr + Default, + ::Err: fmt::Display { + match FromStr::from_str(arg) { + Err(perr) => { + err.issues.push( + CLIError::ParseError(arg_name.to_owned(), arg_type.to_owned(), arg.to_string(), format!("{}", perr)) + ); + Default::default() + }, + Ok(v) => v, + } +} + +pub struct JsonTokenStorage { + pub program_name: &'static str, + pub db_dir: String, +} + +impl JsonTokenStorage { + fn path(&self, scope_hash: u64) -> PathBuf { + Path::new(&self.db_dir).join(&format!("{}-token-{}.json", self.program_name, scope_hash)) + } +} + +impl TokenStorage for JsonTokenStorage { + type Error = json::Error; + + // NOTE: logging might be interesting, currently we swallow all errors + fn set(&mut self, scope_hash: u64, _: &Vec<&str>, token: Option) -> Result<(), json::Error> { + match token { + None => { + match fs::remove_file(self.path(scope_hash)) { + Err(err) => + match err.kind() { + io::ErrorKind::NotFound => Ok(()), + _ => Err(json::Error::IoError(err)) + }, + Ok(_) => Ok(()), + } + } + Some(token) => { + match fs::OpenOptions::new().create(true).write(true).open(&self.path(scope_hash)) { + Ok(mut f) => { + match json::to_writer_pretty(&mut f, &token) { + Ok(_) => Ok(()), + Err(serde_err) => Err(serde_err), + } + }, + Err(io_err) => Err(json::Error::IoError(io_err)) + } + } + } + } + + fn get(&self, scope_hash: u64, _: &Vec<&str>) -> Result, json::Error> { + match fs::File::open(&self.path(scope_hash)) { + Ok(mut f) => { + match json::de::from_reader(f) { + Ok(token) => Ok(Some(token)), + Err(err) => Err(err), + } + }, + Err(io_err) => { + match io_err.kind() { + io::ErrorKind::NotFound => Ok(None), + _ => Err(json::Error::IoError(io_err)) + } + } + } + } +} + + +#[derive(Debug)] +pub enum ApplicationSecretError { + DecoderError((String, json::Error)), + FormatError(String), +} + +impl fmt::Display for ApplicationSecretError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + ApplicationSecretError::DecoderError((ref path, ref err)) + => writeln!(f, "Could not decode file at '{}' with error: {}.", + path, err), + ApplicationSecretError::FormatError(ref path) + => writeln!(f, "'installed' field is unset in secret file at '{}'.", + path), + } + } +} + +#[derive(Debug)] +pub enum ConfigurationError { + DirectoryCreationFailed((String, io::Error)), + DirectoryUnset, + HomeExpansionFailed(String), + Secret(ApplicationSecretError), + IOError((String, io::Error)), +} + +impl fmt::Display for ConfigurationError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + ConfigurationError::DirectoryCreationFailed((ref dir, ref err)) + => writeln!(f, "Directory '{}' could not be created with error: {}.", dir, err), + ConfigurationError::DirectoryUnset + => writeln!(f, "--config-dir was unset or empty."), + ConfigurationError::HomeExpansionFailed(ref dir) + => writeln!(f, "Couldn't find HOME directory of current user, failed to expand '{}'.", dir), + ConfigurationError::Secret(ref err) + => writeln!(f, "Secret -> {}", err), + ConfigurationError::IOError((ref path, ref err)) + => writeln!(f, "IO operation failed on path '{}' with error: {}.", path, err), + } + } +} + +#[derive(Debug)] +pub enum InputError { + IOError((String, io::Error)), + Mime(String), +} + +impl fmt::Display for InputError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + InputError::IOError((ref file_path, ref io_err)) + => writeln!(f, "Failed to open '{}' for reading with error: {}.", file_path, io_err), + InputError::Mime(ref mime) + => writeln!(f, "'{}' is not a known mime-type.", mime), + } + } +} + +#[derive(Debug)] +pub enum FieldError { + PopOnEmpty(String), + TrailingFieldSep(String), + Unknown(String, Option, Option), + Duplicate(String), + Empty, +} + + +impl fmt::Display for FieldError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + FieldError::PopOnEmpty(ref field) + => writeln!(f, "'{}': Cannot move up on empty field cursor.", field), + FieldError::TrailingFieldSep(ref field) + => writeln!(f, "'{}': Single field separator may not be last character.", field), + FieldError::Unknown(ref field, ref suggestion, ref value) => { + let suffix = + match *suggestion { + Some(ref s) => { + let kv = + match *value { + Some(ref v) => format!("{}={}", s, v), + None => s.clone(), + }; + format!(" Did you mean '{}' ?", kv) + }, + None => String::new(), + }; + writeln!(f, "Field '{}' does not exist.{}", field, suffix) + }, + FieldError::Duplicate(ref cursor) + => writeln!(f, "Value at '{}' was already set", cursor), + FieldError::Empty + => writeln!(f, "Field names must not be empty."), + } + } +} + + +#[derive(Debug)] +pub enum CLIError { + Configuration(ConfigurationError), + ParseError(String, String, String, String), + UnknownParameter(String, Vec<&'static str>), + InvalidUploadProtocol(String, Vec), + InvalidKeyValueSyntax(String, bool), + Input(InputError), + Field(FieldError), + MissingCommandError, + MissingMethodError(String), +} + +impl fmt::Display for CLIError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + CLIError::Configuration(ref err) => write!(f, "Configuration -> {}", err), + CLIError::Input(ref err) => write!(f, "Input -> {}", err), + CLIError::Field(ref err) => write!(f, "Field -> {}", err), + CLIError::InvalidUploadProtocol(ref proto_name, ref valid_names) + => writeln!(f, "'{}' is not a valid upload protocol. Choose from one of {}.", proto_name, valid_names.join(", ")), + CLIError::ParseError(ref arg_name, ref type_name, ref value, ref err_desc) + => writeln!(f, "Failed to parse argument '{}' with value '{}' as {} with error: {}.", + arg_name, value, type_name, err_desc), + CLIError::UnknownParameter(ref param_name, ref possible_values) => { + let mut suffix = + match did_you_mean(param_name, &possible_values) { + Some(v) => format!(" Did you mean '{}' ?", v), + None => String::new(), + }; + write!(f, "Parameter '{}' is unknown.{}\n", param_name, suffix) + }, + CLIError::InvalidKeyValueSyntax(ref kv, is_hashmap) => { + let hashmap_info = if is_hashmap { "hashmap " } else { "" }; + writeln!(f, "'{}' does not match {}pattern =.", kv, hashmap_info) + }, + CLIError::MissingCommandError => writeln!(f, "Please specify the main sub-command."), + CLIError::MissingMethodError(ref cmd) => writeln!(f, "Please specify the method to call on the '{}' command.", cmd), + } + } +} + +#[derive(Debug)] +pub struct InvalidOptionsError { + pub issues: Vec, + pub exit_code: i32, +} + +impl fmt::Display for InvalidOptionsError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + for issue in &self.issues { + try!(issue.fmt(f)); + } + Ok(()) + } +} + +impl InvalidOptionsError { + pub fn single(err: CLIError, exit_code: i32) -> InvalidOptionsError { + InvalidOptionsError { + issues: vec![err], + exit_code: exit_code, + } + } + + pub fn new() -> InvalidOptionsError { + InvalidOptionsError { + issues: Vec::new(), + exit_code: 1, + } + } +} + +pub fn assure_config_dir_exists(dir: &str) -> Result { + let trdir = dir.trim(); + if trdir.len() == 0 { + return Err(CLIError::Configuration(ConfigurationError::DirectoryUnset)) + } + + let expanded_config_dir = + if trdir.as_bytes()[0] == b'~' { + match env::var("HOME").ok().or(env::var("UserProfile").ok()) { + None => return Err(CLIError::Configuration(ConfigurationError::HomeExpansionFailed(trdir.to_string()))), + Some(mut user) => { + user.push_str(&trdir[1..]); + user + } + } + } else { + trdir.to_string() + }; + + if let Err(err) = fs::create_dir(&expanded_config_dir) { + if err.kind() != io::ErrorKind::AlreadyExists { + return Err(CLIError::Configuration( + ConfigurationError::DirectoryCreationFailed((expanded_config_dir, err)))) + } + } + + Ok(expanded_config_dir) +} + +pub fn application_secret_from_directory(dir: &str, + secret_basename: &str, + json_console_secret: &str) + -> Result { + let secret_path = Path::new(dir).join(secret_basename); + let secret_str = || secret_path.as_path().to_str().unwrap().to_string(); + let secret_io_error = |io_err: io::Error| { + Err(CLIError::Configuration(ConfigurationError::IOError( + (secret_str(), io_err) + ))) + }; + + for _ in 0..2 { + match fs::File::open(&secret_path) { + Err(mut err) => { + if err.kind() == io::ErrorKind::NotFound { + // Write our built-in one - user may adjust the written file at will + + err = match fs::OpenOptions::new().create(true).write(true).open(&secret_path) { + Err(cfe) => cfe, + Ok(mut f) => { + // Assure we convert 'ugly' json string into pretty one + let console_secret: ConsoleApplicationSecret + = json::from_str(json_console_secret).unwrap(); + match json::to_writer_pretty(&mut f, &console_secret) { + Err(serde_err) => match serde_err { + json::Error::IoError(err) => err, + _ => panic!("Unexpected serde error: {:#?}", serde_err) + }, + Ok(_) => continue, + } + } + }; + // fall through to IO error handling + } + return secret_io_error(err) + }, + Ok(mut f) => { + match json::de::from_reader::<_, ConsoleApplicationSecret>(f) { + Err(json::Error::IoError(err)) => + return secret_io_error(err), + Err(json_err) => + return Err(CLIError::Configuration( + ConfigurationError::Secret( + ApplicationSecretError::DecoderError( + (secret_str(), json_err) + )))), + Ok(console_secret) => + match console_secret.installed { + Some(secret) => return Ok(secret), + None => return Err( + CLIError::Configuration( + ConfigurationError::Secret( + ApplicationSecretError::FormatError(secret_str()) + ))) + }, + } + } + } + } + unreachable!(); +} diff --git a/gen/clouduseraccountsvm_beta-cli/src/main.rs b/gen/clouduseraccountsvm_beta-cli/src/main.rs new file mode 100644 index 0000000000..daeffaffd1 --- /dev/null +++ b/gen/clouduseraccountsvm_beta-cli/src/main.rs @@ -0,0 +1,1935 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/cli/main.rs.mako' +// DO NOT EDIT ! +#![allow(unused_variables, unused_imports, dead_code, unused_mut)] + +#[macro_use] +extern crate clap; +extern crate yup_oauth2 as oauth2; +extern crate yup_hyper_mock as mock; +extern crate serde; +extern crate serde_json; +extern crate hyper; +extern crate mime; +extern crate strsim; +extern crate google_clouduseraccountsvm_beta as api; + +use std::env; +use std::io::{self, Write}; +use clap::{App, SubCommand, Arg}; + +mod cmn; + +use cmn::{InvalidOptionsError, CLIError, JsonTokenStorage, arg_from_str, writer_from_opts, parse_kv_arg, + input_file_from_opts, input_mime_from_opts, FieldCursor, FieldError, CallType, UploadProtocol, + calltype_from_str, remove_json_null_values, ComplexType, JsonType, JsonTypeInfo}; + +use std::default::Default; +use std::str::FromStr; + +use oauth2::{Authenticator, DefaultAuthenticatorDelegate}; +use serde_json as json; +use clap::ArgMatches; + +enum DoitError { + IoError(String, io::Error), + ApiError(api::Error), +} + +struct Engine<'n, 'a> { + opt: ArgMatches<'n, 'a>, + hub: api::CloudUserAccounts>, + gp: Vec<&'static str>, + gpm: Vec<(&'static str, &'static str)>, +} + + +impl<'n, 'a> Engine<'n, 'a> { + fn _global_accounts_operations_delete(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.global_accounts_operations().delete(opt.value_of("project").unwrap_or(""), opt.value_of("operation").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok(mut response) => { + Ok(()) + } + } + } + } + + fn _global_accounts_operations_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.global_accounts_operations().get(opt.value_of("project").unwrap_or(""), opt.value_of("operation").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _global_accounts_operations_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.global_accounts_operations().list(opt.value_of("project").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "order-by" => { + call = call.order_by(value.unwrap_or("")); + }, + "max-results" => { + call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer")); + }, + "filter" => { + call = call.filter(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["order-by", "page-token", "filter", "max-results"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _groups_add_member(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "users" => Some(("users", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["users"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::GroupsAddMemberRequest = json::value::from_value(object).unwrap(); + let mut call = self.hub.groups().add_member(request, opt.value_of("project").unwrap_or(""), opt.value_of("group-name").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _groups_delete(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.groups().delete(opt.value_of("project").unwrap_or(""), opt.value_of("group-name").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _groups_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.groups().get(opt.value_of("project").unwrap_or(""), opt.value_of("group-name").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _groups_insert(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "members" => Some(("members", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "creation-timestamp" => Some(("creationTimestamp", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "self-link" => Some(("selfLink", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "description" => Some(("description", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["creation-timestamp", "description", "id", "kind", "members", "name", "self-link"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::Group = json::value::from_value(object).unwrap(); + let mut call = self.hub.groups().insert(request, opt.value_of("project").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _groups_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.groups().list(opt.value_of("project").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "order-by" => { + call = call.order_by(value.unwrap_or("")); + }, + "max-results" => { + call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer")); + }, + "filter" => { + call = call.filter(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["order-by", "page-token", "filter", "max-results"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _groups_remove_member(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "users" => Some(("users", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["users"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::GroupsRemoveMemberRequest = json::value::from_value(object).unwrap(); + let mut call = self.hub.groups().remove_member(request, opt.value_of("project").unwrap_or(""), opt.value_of("group-name").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _linux_get_authorized_keys_view(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.linux().get_authorized_keys_view(opt.value_of("project").unwrap_or(""), opt.value_of("zone").unwrap_or(""), opt.value_of("user").unwrap_or(""), opt.value_of("instance").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "login" => { + call = call.login(arg_from_str(value.unwrap_or("false"), err, "login", "boolean")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["login"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _linux_get_linux_account_views(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.linux().get_linux_account_views(opt.value_of("project").unwrap_or(""), opt.value_of("zone").unwrap_or(""), opt.value_of("instance").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "order-by" => { + call = call.order_by(value.unwrap_or("")); + }, + "max-results" => { + call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer")); + }, + "filter" => { + call = call.filter(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["order-by", "page-token", "filter", "max-results"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _users_add_public_key(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "expiration-timestamp" => Some(("expirationTimestamp", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "creation-timestamp" => Some(("creationTimestamp", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "description" => Some(("description", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "key" => Some(("key", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "fingerprint" => Some(("fingerprint", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["creation-timestamp", "description", "expiration-timestamp", "fingerprint", "key"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::PublicKey = json::value::from_value(object).unwrap(); + let mut call = self.hub.users().add_public_key(request, opt.value_of("project").unwrap_or(""), opt.value_of("user").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _users_delete(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.users().delete(opt.value_of("project").unwrap_or(""), opt.value_of("user").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _users_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.users().get(opt.value_of("project").unwrap_or(""), opt.value_of("user").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _users_insert(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "groups" => Some(("groups", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "owner" => Some(("owner", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "creation-timestamp" => Some(("creationTimestamp", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "self-link" => Some(("selfLink", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "description" => Some(("description", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["creation-timestamp", "description", "groups", "id", "kind", "name", "owner", "self-link"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::User = json::value::from_value(object).unwrap(); + let mut call = self.hub.users().insert(request, opt.value_of("project").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _users_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.users().list(opt.value_of("project").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "order-by" => { + call = call.order_by(value.unwrap_or("")); + }, + "max-results" => { + call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer")); + }, + "filter" => { + call = call.filter(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["order-by", "page-token", "filter", "max-results"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _users_remove_public_key(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.users().remove_public_key(opt.value_of("project").unwrap_or(""), opt.value_of("user").unwrap_or(""), opt.value_of("fingerprint").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _doit(&self, dry_run: bool) -> Result, Option> { + let mut err = InvalidOptionsError::new(); + let mut call_result: Result<(), DoitError> = Ok(()); + let mut err_opt: Option = None; + match self.opt.subcommand() { + ("global-accounts-operations", Some(opt)) => { + match opt.subcommand() { + ("delete", Some(opt)) => { + call_result = self._global_accounts_operations_delete(opt, dry_run, &mut err); + }, + ("get", Some(opt)) => { + call_result = self._global_accounts_operations_get(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._global_accounts_operations_list(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("global-accounts-operations".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("groups", Some(opt)) => { + match opt.subcommand() { + ("add-member", Some(opt)) => { + call_result = self._groups_add_member(opt, dry_run, &mut err); + }, + ("delete", Some(opt)) => { + call_result = self._groups_delete(opt, dry_run, &mut err); + }, + ("get", Some(opt)) => { + call_result = self._groups_get(opt, dry_run, &mut err); + }, + ("insert", Some(opt)) => { + call_result = self._groups_insert(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._groups_list(opt, dry_run, &mut err); + }, + ("remove-member", Some(opt)) => { + call_result = self._groups_remove_member(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("groups".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("linux", Some(opt)) => { + match opt.subcommand() { + ("get-authorized-keys-view", Some(opt)) => { + call_result = self._linux_get_authorized_keys_view(opt, dry_run, &mut err); + }, + ("get-linux-account-views", Some(opt)) => { + call_result = self._linux_get_linux_account_views(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("linux".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("users", Some(opt)) => { + match opt.subcommand() { + ("add-public-key", Some(opt)) => { + call_result = self._users_add_public_key(opt, dry_run, &mut err); + }, + ("delete", Some(opt)) => { + call_result = self._users_delete(opt, dry_run, &mut err); + }, + ("get", Some(opt)) => { + call_result = self._users_get(opt, dry_run, &mut err); + }, + ("insert", Some(opt)) => { + call_result = self._users_insert(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._users_list(opt, dry_run, &mut err); + }, + ("remove-public-key", Some(opt)) => { + call_result = self._users_remove_public_key(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("users".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + _ => { + err.issues.push(CLIError::MissingCommandError); + writeln!(io::stderr(), "{}\n", self.opt.usage()).ok(); + } + } + + if dry_run { + if err.issues.len() > 0 { + err_opt = Some(err); + } + Err(err_opt) + } else { + Ok(call_result) + } + } + + // Please note that this call will fail if any part of the opt can't be handled + fn new(opt: ArgMatches<'a, 'n>) -> Result, InvalidOptionsError> { + let (config_dir, secret) = { + let config_dir = match cmn::assure_config_dir_exists(opt.value_of("folder").unwrap_or("~/.google-service-cli")) { + Err(e) => return Err(InvalidOptionsError::single(e, 3)), + Ok(p) => p, + }; + + match cmn::application_secret_from_directory(&config_dir, "clouduseraccountsvm-beta-secret.json", + "{\"installed\":{\"auth_uri\":\"https://accounts.google.com/o/oauth2/auth\",\"client_secret\":\"hCsslbCUyfehWMmbkG8vTYxG\",\"token_uri\":\"https://accounts.google.com/o/oauth2/token\",\"client_email\":\"\",\"redirect_uris\":[\"urn:ietf:wg:oauth:2.0:oob\",\"oob\"],\"client_x509_cert_url\":\"\",\"client_id\":\"620010449518-9ngf7o4dhs0dka470npqvor6dc5lqb9b.apps.googleusercontent.com\",\"auth_provider_x509_cert_url\":\"https://www.googleapis.com/oauth2/v1/certs\"}}") { + Ok(secret) => (config_dir, secret), + Err(e) => return Err(InvalidOptionsError::single(e, 4)) + } + }; + + let auth = Authenticator::new( &secret, DefaultAuthenticatorDelegate, + if opt.is_present("debug-auth") { + hyper::Client::with_connector(mock::TeeConnector { + connector: hyper::net::HttpsConnector::::default() + }) + } else { + hyper::Client::new() + }, + JsonTokenStorage { + program_name: "clouduseraccountsvm-beta", + db_dir: config_dir.clone(), + }, None); + + let client = + if opt.is_present("debug") { + hyper::Client::with_connector(mock::TeeConnector { + connector: hyper::net::HttpsConnector::::default() + }) + } else { + hyper::Client::new() + }; + let engine = Engine { + opt: opt, + hub: api::CloudUserAccounts::new(client, auth), + gp: vec!["alt", "fields", "key", "oauth-token", "pretty-print", "quota-user", "user-ip"], + gpm: vec![ + ("oauth-token", "oauth_token"), + ("pretty-print", "prettyPrint"), + ("quota-user", "quotaUser"), + ("user-ip", "userIp"), + ] + }; + + match engine._doit(true) { + Err(Some(err)) => Err(err), + Err(None) => Ok(engine), + Ok(_) => unreachable!(), + } + } + + fn doit(&self) -> Result<(), DoitError> { + match self._doit(false) { + Ok(res) => res, + Err(_) => unreachable!(), + } + } +} + +fn main() { + let mut exit_status = 0i32; + let arg_data = [ + ("global-accounts-operations", "methods: 'delete', 'get' and 'list'", vec![ + ("delete", + Some(r##"Deletes the specified operation resource."##), + "Details at http://byron.github.io/google-apis-rs/google_clouduseraccountsvm_beta_cli/global-accounts-operations_delete", + vec![ + (Some(r##"project"##), + None, + Some(r##"Project ID for this request."##), + Some(true), + Some(false)), + + (Some(r##"operation"##), + None, + Some(r##"Name of the Operations resource to delete."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + ]), + ("get", + Some(r##"Retrieves the specified operation resource."##), + "Details at http://byron.github.io/google-apis-rs/google_clouduseraccountsvm_beta_cli/global-accounts-operations_get", + vec![ + (Some(r##"project"##), + None, + Some(r##"Project ID for this request."##), + Some(true), + Some(false)), + + (Some(r##"operation"##), + None, + Some(r##"Name of the Operations resource to return."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Retrieves the list of operation resources contained within the specified project."##), + "Details at http://byron.github.io/google-apis-rs/google_clouduseraccountsvm_beta_cli/global-accounts-operations_list", + vec![ + (Some(r##"project"##), + None, + Some(r##"Project ID for this request."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("groups", "methods: 'add-member', 'delete', 'get', 'insert', 'list' and 'remove-member'", vec![ + ("add-member", + Some(r##"Adds users to the specified group."##), + "Details at http://byron.github.io/google-apis-rs/google_clouduseraccountsvm_beta_cli/groups_add-member", + vec![ + (Some(r##"project"##), + None, + Some(r##"Project ID for this request."##), + Some(true), + Some(false)), + + (Some(r##"group-name"##), + None, + Some(r##"Name of the group for this request."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("delete", + Some(r##"Deletes the specified Group resource."##), + "Details at http://byron.github.io/google-apis-rs/google_clouduseraccountsvm_beta_cli/groups_delete", + vec![ + (Some(r##"project"##), + None, + Some(r##"Project ID for this request."##), + Some(true), + Some(false)), + + (Some(r##"group-name"##), + None, + Some(r##"Name of the Group resource to delete."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("get", + Some(r##"Returns the specified Group resource."##), + "Details at http://byron.github.io/google-apis-rs/google_clouduseraccountsvm_beta_cli/groups_get", + vec![ + (Some(r##"project"##), + None, + Some(r##"Project ID for this request."##), + Some(true), + Some(false)), + + (Some(r##"group-name"##), + None, + Some(r##"Name of the Group resource to return."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("insert", + Some(r##"Creates a Group resource in the specified project using the data included in the request."##), + "Details at http://byron.github.io/google-apis-rs/google_clouduseraccountsvm_beta_cli/groups_insert", + vec![ + (Some(r##"project"##), + None, + Some(r##"Project ID for this request."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Retrieves the list of groups contained within the specified project."##), + "Details at http://byron.github.io/google-apis-rs/google_clouduseraccountsvm_beta_cli/groups_list", + vec![ + (Some(r##"project"##), + None, + Some(r##"Project ID for this request."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("remove-member", + Some(r##"Removes users from the specified group."##), + "Details at http://byron.github.io/google-apis-rs/google_clouduseraccountsvm_beta_cli/groups_remove-member", + vec![ + (Some(r##"project"##), + None, + Some(r##"Project ID for this request."##), + Some(true), + Some(false)), + + (Some(r##"group-name"##), + None, + Some(r##"Name of the group for this request."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("linux", "methods: 'get-authorized-keys-view' and 'get-linux-account-views'", vec![ + ("get-authorized-keys-view", + Some(r##"Returns a list of authorized public keys for a specific user account."##), + "Details at http://byron.github.io/google-apis-rs/google_clouduseraccountsvm_beta_cli/linux_get-authorized-keys-view", + vec![ + (Some(r##"project"##), + None, + Some(r##"Project ID for this request."##), + Some(true), + Some(false)), + + (Some(r##"zone"##), + None, + Some(r##"Name of the zone for this request."##), + Some(true), + Some(false)), + + (Some(r##"user"##), + None, + Some(r##"The user account for which you want to get a list of authorized public keys."##), + Some(true), + Some(false)), + + (Some(r##"instance"##), + None, + Some(r##"The fully-qualified URL of the virtual machine requesting the view."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("get-linux-account-views", + Some(r##"Retrieves a list of user accounts for an instance within a specific project."##), + "Details at http://byron.github.io/google-apis-rs/google_clouduseraccountsvm_beta_cli/linux_get-linux-account-views", + vec![ + (Some(r##"project"##), + None, + Some(r##"Project ID for this request."##), + Some(true), + Some(false)), + + (Some(r##"zone"##), + None, + Some(r##"Name of the zone for this request."##), + Some(true), + Some(false)), + + (Some(r##"instance"##), + None, + Some(r##"The fully-qualified URL of the virtual machine requesting the views."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("users", "methods: 'add-public-key', 'delete', 'get', 'insert', 'list' and 'remove-public-key'", vec![ + ("add-public-key", + Some(r##"Adds a public key to the specified User resource with the data included in the request."##), + "Details at http://byron.github.io/google-apis-rs/google_clouduseraccountsvm_beta_cli/users_add-public-key", + vec![ + (Some(r##"project"##), + None, + Some(r##"Project ID for this request."##), + Some(true), + Some(false)), + + (Some(r##"user"##), + None, + Some(r##"Name of the user for this request."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("delete", + Some(r##"Deletes the specified User resource."##), + "Details at http://byron.github.io/google-apis-rs/google_clouduseraccountsvm_beta_cli/users_delete", + vec![ + (Some(r##"project"##), + None, + Some(r##"Project ID for this request."##), + Some(true), + Some(false)), + + (Some(r##"user"##), + None, + Some(r##"Name of the user resource to delete."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("get", + Some(r##"Returns the specified User resource."##), + "Details at http://byron.github.io/google-apis-rs/google_clouduseraccountsvm_beta_cli/users_get", + vec![ + (Some(r##"project"##), + None, + Some(r##"Project ID for this request."##), + Some(true), + Some(false)), + + (Some(r##"user"##), + None, + Some(r##"Name of the user resource to return."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("insert", + Some(r##"Creates a User resource in the specified project using the data included in the request."##), + "Details at http://byron.github.io/google-apis-rs/google_clouduseraccountsvm_beta_cli/users_insert", + vec![ + (Some(r##"project"##), + None, + Some(r##"Project ID for this request."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Retrieves a list of users contained within the specified project."##), + "Details at http://byron.github.io/google-apis-rs/google_clouduseraccountsvm_beta_cli/users_list", + vec![ + (Some(r##"project"##), + None, + Some(r##"Project ID for this request."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("remove-public-key", + Some(r##"Removes the specified public key from the user."##), + "Details at http://byron.github.io/google-apis-rs/google_clouduseraccountsvm_beta_cli/users_remove-public-key", + vec![ + (Some(r##"project"##), + None, + Some(r##"Project ID for this request."##), + Some(true), + Some(false)), + + (Some(r##"user"##), + None, + Some(r##"Name of the user for this request."##), + Some(true), + Some(false)), + + (Some(r##"fingerprint"##), + None, + Some(r##"The fingerprint of the public key to delete. Public keys are identified by their fingerprint, which is defined by RFC4716 to be the MD5 digest of the public key."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ]; + + let mut app = App::new("clouduseraccountsvm-beta") + .author("Sebastian Thiel ") + .version("0.3.2+20150924") + .about("API for the Google Cloud User Accounts service.") + .after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_clouduseraccountsvm_beta_cli") + .arg(Arg::with_name("url") + .long("scope") + .help("Specify the authentication a method should be executed in. Each scope requires the user to grant this application permission to use it.If unset, it defaults to the shortest scope url for a particular method.") + .multiple(true) + .takes_value(true)) + .arg(Arg::with_name("folder") + .long("config-dir") + .help("A directory into which we will store our persistent data. Defaults to a user-writable directory that we will create during the first invocation.[default: ~/.google-service-cli") + .multiple(false) + .takes_value(true)) + .arg(Arg::with_name("debug") + .long("debug") + .help("Output all server communication to standard error. `tx` and `rx` are placed into the same stream.") + .multiple(false) + .takes_value(false)) + .arg(Arg::with_name("debug-auth") + .long("debug-auth") + .help("Output all communication related to authentication to standard error. `tx` and `rx` are placed into the same stream.") + .multiple(false) + .takes_value(false)); + + for &(main_command_name, ref about, ref subcommands) in arg_data.iter() { + let mut mcmd = SubCommand::with_name(main_command_name).about(about); + + for &(sub_command_name, ref desc, url_info, ref args) in subcommands { + let mut scmd = SubCommand::with_name(sub_command_name); + if let &Some(desc) = desc { + scmd = scmd.about(desc); + } + scmd = scmd.after_help(url_info); + + for &(ref arg_name, ref flag, ref desc, ref required, ref multi) in args { + let arg_name_str = + match (arg_name, flag) { + (&Some(an), _ ) => an, + (_ , &Some(f)) => f, + _ => unreachable!(), + }; + let mut arg = Arg::with_name(arg_name_str) + .empty_values(false); + if let &Some(short_flag) = flag { + arg = arg.short(short_flag); + } + if let &Some(desc) = desc { + arg = arg.help(desc); + } + if arg_name.is_some() && flag.is_some() { + arg = arg.takes_value(true); + } + if let &Some(required) = required { + arg = arg.required(required); + } + if let &Some(multi) = multi { + arg = arg.multiple(multi); + } + scmd = scmd.arg(arg); + } + mcmd = mcmd.subcommand(scmd); + } + app = app.subcommand(mcmd); + } + + let matches = app.get_matches(); + + let debug = matches.is_present("debug"); + match Engine::new(matches) { + Err(err) => { + exit_status = err.exit_code; + writeln!(io::stderr(), "{}", err).ok(); + }, + Ok(engine) => { + if let Err(doit_err) = engine.doit() { + exit_status = 1; + match doit_err { + DoitError::IoError(path, err) => { + writeln!(io::stderr(), "Failed to open output file '{}': {}", path, err).ok(); + }, + DoitError::ApiError(err) => { + if debug { + writeln!(io::stderr(), "{:#?}", err).ok(); + } else { + writeln!(io::stderr(), "{}", err).ok(); + } + } + } + } + } + } + + std::process::exit(exit_status); +} \ No newline at end of file diff --git a/gen/clouduseraccountsvm_beta/Cargo.toml b/gen/clouduseraccountsvm_beta/Cargo.toml new file mode 100644 index 0000000000..617ae8b779 --- /dev/null +++ b/gen/clouduseraccountsvm_beta/Cargo.toml @@ -0,0 +1,29 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-clouduseraccountsvm_beta" +version = "0.1.9+20150924" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with Cloud User Accounts (protocol vm_beta)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/clouduseraccountsvm_beta" +homepage = "https://cloud.google.com/compute/docs/access/user-accounts/api/latest/" +documentation = "http://byron.github.io/google-apis-rs/google_clouduseraccountsvm_beta" +license = "MIT" +keywords = ["clouduseraccounts", "google", "protocol", "web", "api"] +build = "src/build.rs" + + +[dependencies] +hyper = ">= 0.6.8" +mime = "0.1.0" +serde = ">= 0.6.0" +serde_json = ">= 0.6.0" +yup-oauth2 = "*" +url = "*" + +[build-dependencies] +syntex = { version = "*" } +serde_codegen = { version = "*" } + diff --git a/gen/clouduseraccountsvm_beta/LICENSE.md b/gen/clouduseraccountsvm_beta/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/clouduseraccountsvm_beta/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/clouduseraccountsvm_beta/README.md b/gen/clouduseraccountsvm_beta/README.md new file mode 100644 index 0000000000..74b97d02f8 --- /dev/null +++ b/gen/clouduseraccountsvm_beta/README.md @@ -0,0 +1,193 @@ + +The `google-clouduseraccountsvm_beta` library allows access to all features of the *Google Cloud User Accounts* service. + +This documentation was generated from *Cloud User Accounts* crate version *0.1.9+20150924*, where *20150924* is the exact revision of the *clouduseraccounts:vm_beta* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. + +Everything else about the *Cloud User Accounts* *vm_beta* API can be found at the +[official documentation site](https://cloud.google.com/compute/docs/access/user-accounts/api/latest/). +# Features + +Handle the following *Resources* with ease from the central [hub](http://byron.github.io/google-apis-rs/google_clouduseraccountsvm_beta/struct.CloudUserAccounts.html) ... + +* global accounts operations + * [*delete*](http://byron.github.io/google-apis-rs/google_clouduseraccountsvm_beta/struct.GlobalAccountsOperationDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google_clouduseraccountsvm_beta/struct.GlobalAccountsOperationGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google_clouduseraccountsvm_beta/struct.GlobalAccountsOperationListCall.html) +* [groups](http://byron.github.io/google-apis-rs/google_clouduseraccountsvm_beta/struct.Group.html) + * [*add member*](http://byron.github.io/google-apis-rs/google_clouduseraccountsvm_beta/struct.GroupAddMemberCall.html), [*delete*](http://byron.github.io/google-apis-rs/google_clouduseraccountsvm_beta/struct.GroupDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google_clouduseraccountsvm_beta/struct.GroupGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google_clouduseraccountsvm_beta/struct.GroupInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google_clouduseraccountsvm_beta/struct.GroupListCall.html) and [*remove member*](http://byron.github.io/google-apis-rs/google_clouduseraccountsvm_beta/struct.GroupRemoveMemberCall.html) +* linux + * [*get authorized keys view*](http://byron.github.io/google-apis-rs/google_clouduseraccountsvm_beta/struct.LinuxGetAuthorizedKeysViewCall.html) and [*get linux account views*](http://byron.github.io/google-apis-rs/google_clouduseraccountsvm_beta/struct.LinuxGetLinuxAccountViewCall.html) +* [users](http://byron.github.io/google-apis-rs/google_clouduseraccountsvm_beta/struct.User.html) + * [*add public key*](http://byron.github.io/google-apis-rs/google_clouduseraccountsvm_beta/struct.UserAddPublicKeyCall.html), [*delete*](http://byron.github.io/google-apis-rs/google_clouduseraccountsvm_beta/struct.UserDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google_clouduseraccountsvm_beta/struct.UserGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google_clouduseraccountsvm_beta/struct.UserInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google_clouduseraccountsvm_beta/struct.UserListCall.html) and [*remove public key*](http://byron.github.io/google-apis-rs/google_clouduseraccountsvm_beta/struct.UserRemovePublicKeyCall.html) + + + + +# Structure of this Library + +The API is structured into the following primary items: + +* **[Hub](http://byron.github.io/google-apis-rs/google_clouduseraccountsvm_beta/struct.CloudUserAccounts.html)** + * a central object to maintain state and allow accessing all *Activities* + * creates [*Method Builders*](http://byron.github.io/google-apis-rs/google_clouduseraccountsvm_beta/trait.MethodsBuilder.html) which in turn + allow access to individual [*Call Builders*](http://byron.github.io/google-apis-rs/google_clouduseraccountsvm_beta/trait.CallBuilder.html) +* **[Resources](http://byron.github.io/google-apis-rs/google_clouduseraccountsvm_beta/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_clouduseraccountsvm_beta/trait.Part.html)** + * a collection of properties + * never directly used in *Activities* +* **[Activities](http://byron.github.io/google-apis-rs/google_clouduseraccountsvm_beta/trait.CallBuilder.html)** + * operations to apply to *Resources* + +All *structures* are marked with applicable traits to further categorize them and ease browsing. + +Generally speaking, you can invoke *Activities* like this: + +```Rust,ignore +let r = hub.resource().activity(...).doit() +``` + +Or specifically ... + +```ignore +let r = hub.groups().delete(...).doit() +let r = hub.users().add_public_key(...).doit() +let r = hub.users().insert(...).doit() +let r = hub.groups().add_member(...).doit() +let r = hub.users().delete(...).doit() +let r = hub.users().remove_public_key(...).doit() +let r = hub.groups().insert(...).doit() +let r = hub.global_accounts_operations().get(...).doit() +let r = hub.groups().remove_member(...).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-clouduseraccountsvm_beta = "*" +``` + +## A complete example + +```Rust +extern crate hyper; +extern crate yup_oauth2 as oauth2; +extern crate google_clouduseraccountsvm_beta as clouduseraccountsvm_beta; +use clouduseraccountsvm_beta::PublicKey; +use clouduseraccountsvm_beta::{Result, Error}; +use std::default::Default; +use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +use clouduseraccountsvm_beta::CloudUserAccounts; + +// 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 = CloudUserAccounts::new(hyper::Client::new(), auth); +// As the method needs a request, you would usually fill it with the desired information +// into the respective structure. Some of the parts shown here might not be applicable ! +// Values shown here are possibly random and not representative ! +let mut req = PublicKey::default(); + +// You can configure optional parameters by calling 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().add_public_key(req, "project", "user") + .doit(); + +match result { + Err(e) => match e { + // The Error enum provides details about what exactly happened. + // You can also just use its `Debug`, `Display` or `Error` traits + Error::HttpError(_) + |Error::MissingAPIKey + |Error::MissingToken(_) + |Error::Cancelled + |Error::UploadSizeLimitExceeded(_, _) + |Error::Failure(_) + |Error::BadRequest(_) + |Error::FieldClash(_) + |Error::JsonDecodeError(_, _) => println!("{}", e), + }, + Ok(res) => println!("Success: {:?}", res), +} + +``` +## Handling Errors + +All errors produced by the system are provided either as [Result](http://byron.github.io/google-apis-rs/google_clouduseraccountsvm_beta/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_clouduseraccountsvm_beta/trait.Delegate.html), or the [Authenticator Delegate](http://byron.github.io/google-apis-rs/google_clouduseraccountsvm_beta/../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 Downloads +If a method supports downloads, the response body, which is part of the [Result](http://byron.github.io/google-apis-rs/google_clouduseraccountsvm_beta/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_clouduseraccountsvm_beta/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_clouduseraccountsvm_beta/trait.Delegate.html) to the +[Method Builder](http://byron.github.io/google-apis-rs/google_clouduseraccountsvm_beta/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_clouduseraccountsvm_beta/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_clouduseraccountsvm_beta/trait.RequestValue.html) and +[decodable](http://byron.github.io/google-apis-rs/google_clouduseraccountsvm_beta/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_clouduseraccountsvm_beta/trait.Part.html) which are identifiable 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_clouduseraccountsvm_beta/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_clouduseraccountsvm_beta/trait.RequestValue.html) are moved + +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 **clouduseraccountsvm_beta** 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/clouduseraccountsvm_beta/src/build.rs b/gen/clouduseraccountsvm_beta/src/build.rs new file mode 100644 index 0000000000..da9223d224 --- /dev/null +++ b/gen/clouduseraccountsvm_beta/src/build.rs @@ -0,0 +1,16 @@ +extern crate syntex; +extern crate serde_codegen; + +use std::env; +use std::path::Path; + +pub fn main() { + let out_dir = env::var_os("OUT_DIR").unwrap(); + + let src = Path::new("src/lib.rs.in"); + let dst = Path::new(&out_dir).join("lib.rs"); + + let mut registry = syntex::Registry::new(); + serde_codegen::register(&mut registry); + registry.expand("google-clouduseraccountsvm_beta", &src, &dst).unwrap(); +} diff --git a/gen/clouduseraccountsvm_beta/src/cmn.rs b/gen/clouduseraccountsvm_beta/src/cmn.rs new file mode 100644 index 0000000000..0e31353ba3 --- /dev/null +++ b/gen/clouduseraccountsvm_beta/src/cmn.rs @@ -0,0 +1,762 @@ +// COPY OF 'src/rust/api/cmn.rs' +// DO NOT EDIT +use std::io::{self, Read, Seek, Cursor, Write, SeekFrom}; +use std; +use std::fmt::{self, Display}; +use std::str::FromStr; +use std::error; +use std::thread::sleep_ms; + +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::h1::LINE_ENDING; +use hyper::method::Method; +use hyper::status::StatusCode; + +use serde_json as json; + +/// 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 {} + +/// Identifies types for building methods of a particular resource type +pub trait MethodsBuilder {} + +/// Identifies types which represent builders for a particular resource method +pub trait CallBuilder {} + +/// Identifies types which can be inserted and deleted. +/// Types with this trait are most commonly used by clients of this API. +pub trait Resource {} + +/// Identifies types which are used in API responses. +pub trait ResponseResult {} + +/// Identifies types which are used in API requests. +pub trait RequestValue {} + +/// Identifies types which are not actually used by the API +/// This might be a bug within the google API schema. +pub trait UnusedType {} + +/// Identifies types which are only used as part of other types, which +/// usually are carrying the `Resource` trait. +pub trait Part {} + +/// 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 {} + +/// 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 +} + +/// A utility to represent detailed errors we might see in case there are BadRequests. +/// The latter happen if the sent parameters or request structures are unsound +#[derive(Deserialize, Serialize, Debug)] +pub struct ErrorResponse { + error: ServerError, +} + +#[derive(Deserialize, Serialize, Debug)] +pub struct ServerError { + errors: Vec, + code: u16, + message: String, +} + +#[derive(Deserialize, Serialize, Debug)] +pub struct ServerMessage { + domain: String, + reason: String, + message: String, + #[serde(rename="locationType")] + location_type: Option, + location: 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 successful. That way, the delegate 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. + /// + /// If you choose to retry after a duration, the duration should be chosen using the + /// [exponential backoff algorithm](http://en.wikipedia.org/wiki/Exponential_backoff). + /// + /// Return retry information. + fn http_error(&mut self, &hyper::Error) -> 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 it as a general information about the + /// impending failure. + /// The given Error provides information about why the token couldn't be acquired in the + /// first place + fn token(&mut self, err: &error::Error) -> Option { + let _ = err; + 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/canceled, 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()`. + /// It will also be called with None after a successful upload, which allows the delegate + /// to forget the URL. That way, we will not attempt to resume an upload that has already + /// finished. + fn store_upload_url(&mut self, url: Option<&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: &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. + /// + /// If you choose to retry after a duration, the duration should be chosen using the + /// [exponential backoff algorithm](http://en.wikipedia.org/wiki/Exponential_backoff). + fn http_failure(&mut self, _: &hyper::client::Response, Option, _: 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 {} + + +#[derive(Debug)] +pub enum Error { + /// The http connection failed + HttpError(hyper::Error), + + /// 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), + + /// Represents information about a request that was not understood by the server. + /// Details are included. + BadRequest(ErrorResponse), + + /// 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(Box), + + /// 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(String, json::Error), + + /// Indicates an HTTP repsonse with a non-success status code + Failure(hyper::client::Response), +} + + +impl Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + Error::HttpError(ref err) => err.fmt(f), + Error::UploadSizeLimitExceeded(ref resource_size, ref max_size) => + writeln!(f, "The media size {} exceeds the maximum allowed upload size of {}" + , resource_size, max_size), + Error::MissingAPIKey => { + (writeln!(f, "The application's API key was not found in the configuration")).ok(); + writeln!(f, "It is used as there are no Scopes defined for this method.") + }, + Error::BadRequest(ref err) => { + try!(writeln!(f, "Bad Requst ({}): {}", err.error.code, err.error.message)); + for err in err.error.errors.iter() { + try!(writeln!(f, " {}: {}, {}{}", + err.domain, + err.message, + err.reason, + match &err.location { + &Some(ref loc) => format!("@{}", loc), + &None => String::new(), + })); + } + Ok(()) + }, + Error::MissingToken(ref err) => + writeln!(f, "Token retrieval failed with error: {}", err), + Error::Cancelled => + writeln!(f, "Operation cancelled by delegate"), + Error::FieldClash(field) => + writeln!(f, "The custom parameter '{}' is already provided natively by the CallBuilder.", field), + Error::JsonDecodeError(ref json_str, ref err) + => writeln!(f, "{}: {}", err, json_str), + Error::Failure(ref response) => + writeln!(f, "Http status indicates failure: {:?}", response), + } + } +} + +impl error::Error for Error { + fn description(&self) -> &str { + match *self { + Error::HttpError(ref err) => err.description(), + Error::JsonDecodeError(_, ref err) => err.description(), + _ => "NO DESCRIPTION POSSIBLE - use `Display.fmt()` instead" + } + } + + fn cause(&self) -> Option<&error::Error> { + match *self { + Error::HttpError(ref err) => err.cause(), + Error::JsonDecodeError(_, ref err) => err.cause(), + _ => None + } + } +} + +/// A universal result type used as return for all calls. +pub type Result = std::result::Result; + +/// 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 + 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 following macro invocation needs to be expanded, as `include!` +// doens't support external macros +// header!{ +// #[doc="The `X-Upload-Content-Type` header."] +// (XUploadContentType, "X-Upload-Content-Type") => [Mime] + +// xupload_content_type { +// test_header!( +// test1, +// vec![b"text/plain"], +// Some(HeaderField( +// vec![Mime(TopLevel::Text, SubLevel::Plain, Vec::new())] +// ))); + +// } +// } + +/// The `X-Upload-Content-Type` header. +/// +/// Generated via rustc --pretty expanded -Z unstable-options, and manually +/// processed to be more readable. +#[derive(PartialEq, Debug, Clone)] +pub struct XUploadContentType(pub Mime); + +impl ::std::ops::Deref for XUploadContentType { + type Target = Mime; + fn deref<'a>(&'a self) -> &'a Mime { &self.0 } +} +impl ::std::ops::DerefMut for XUploadContentType { + fn deref_mut<'a>(&'a mut self) -> &'a mut Mime { &mut self.0 } +} +impl Header for XUploadContentType { + fn header_name() -> &'static str { "X-Upload-Content-Type" } + fn parse_header(raw: &[Vec]) -> hyper::error::Result { + hyper::header::parsing::from_one_raw_str(raw).map(XUploadContentType) + } +} +impl HeaderFormat for XUploadContentType { + fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { + Display::fmt(&**self, f) + } +} +impl Display for XUploadContentType { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Display::fmt(&**self, f) + } +} + +#[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]) -> hyper::error::Result { + Err(hyper::error::Error::Method) + } +} + + +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]) -> hyper::error::Result { + if raw.len() > 0 { + let v = &raw[0]; + if let Ok(s) = std::str::from_utf8(v) { + const PREFIX: &'static str = "bytes "; + if s.starts_with(PREFIX) { + if let Ok(c) = ::from_str(&s[PREFIX.len()..]) { + return Ok(RangeResponseHeader(c)) + } + } + } + } + Err(hyper::error::Error::Method) + } +} + +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, 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, A> ResumableUploadHelper<'a, A> + where A: oauth2::GetToken { + + fn query_transfer_status(&mut self) -> std::result::Result> { + 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, None) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + return Err(Ok(r)) + } + }; + return Ok(h.0.last) + } + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + return Err(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() { + Ok(s) => s, + Err(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 + }; + + self.reader.seek(SeekFrom::Start(start)).unwrap(); + loop { + let request_size = match self.content_length - start { + rs if rs > chunk_size => chunk_size, + rs => rs + }; + + 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 + } + // workaround https://github.com/rust-lang/rust/issues/22252 + let res = 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(); + match res { + 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, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + } + return Some(Ok(res)) + }, + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + return Some(Err(err)) + } + } + } + } +} + +// Copy of src/rust/cli/cmn.rs +// TODO(ST): Allow sharing common code between program types +pub fn remove_json_null_values(value: &mut json::value::Value) { + match *value { + json::value::Value::Object(ref mut map) => { + let mut for_removal = Vec::new(); + + for (key, mut value) in map.iter_mut() { + if value.is_null() { + for_removal.push(key.clone()); + } else { + remove_json_null_values(&mut value); + } + } + + for key in &for_removal { + map.remove(key); + } + } + _ => {} + } +} diff --git a/gen/clouduseraccountsvm_beta/src/lib.rs b/gen/clouduseraccountsvm_beta/src/lib.rs new file mode 100644 index 0000000000..223aed7ce1 --- /dev/null +++ b/gen/clouduseraccountsvm_beta/src/lib.rs @@ -0,0 +1,197 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/api/lib.rs.mako' +// DO NOT EDIT ! + +//! This documentation was generated from *Cloud User Accounts* crate version *0.1.9+20150924*, where *20150924* is the exact revision of the *clouduseraccounts:vm_beta* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +//! +//! Everything else about the *Cloud User Accounts* *vm_beta* API can be found at the +//! [official documentation site](https://cloud.google.com/compute/docs/access/user-accounts/api/latest/). +//! The original source code is [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/clouduseraccountsvm_beta). +//! # Features +//! +//! Handle the following *Resources* with ease from the central [hub](struct.CloudUserAccounts.html) ... +//! +//! * global accounts operations +//! * [*delete*](struct.GlobalAccountsOperationDeleteCall.html), [*get*](struct.GlobalAccountsOperationGetCall.html) and [*list*](struct.GlobalAccountsOperationListCall.html) +//! * [groups](struct.Group.html) +//! * [*add member*](struct.GroupAddMemberCall.html), [*delete*](struct.GroupDeleteCall.html), [*get*](struct.GroupGetCall.html), [*insert*](struct.GroupInsertCall.html), [*list*](struct.GroupListCall.html) and [*remove member*](struct.GroupRemoveMemberCall.html) +//! * linux +//! * [*get authorized keys view*](struct.LinuxGetAuthorizedKeysViewCall.html) and [*get linux account views*](struct.LinuxGetLinuxAccountViewCall.html) +//! * [users](struct.User.html) +//! * [*add public key*](struct.UserAddPublicKeyCall.html), [*delete*](struct.UserDeleteCall.html), [*get*](struct.UserGetCall.html), [*insert*](struct.UserInsertCall.html), [*list*](struct.UserListCall.html) and [*remove public key*](struct.UserRemovePublicKeyCall.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.CloudUserAccounts.html)** +//! * a central object to maintain state and allow accessing all *Activities* +//! * creates [*Method Builders*](trait.MethodsBuilder.html) which in turn +//! allow access to individual [*Call Builders*](trait.CallBuilder.html) +//! * **[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* +//! +//! All *structures* are marked with applicable traits to further categorize them and ease browsing. +//! +//! Generally speaking, you can invoke *Activities* like this: +//! +//! ```Rust,ignore +//! let r = hub.resource().activity(...).doit() +//! ``` +//! +//! Or specifically ... +//! +//! ```ignore +//! let r = hub.groups().delete(...).doit() +//! let r = hub.users().add_public_key(...).doit() +//! let r = hub.users().insert(...).doit() +//! let r = hub.groups().add_member(...).doit() +//! let r = hub.users().delete(...).doit() +//! let r = hub.users().remove_public_key(...).doit() +//! let r = hub.groups().insert(...).doit() +//! let r = hub.global_accounts_operations().get(...).doit() +//! let r = hub.groups().remove_member(...).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-clouduseraccountsvm_beta = "*" +//! ``` +//! +//! ## A complete example +//! +//! ```test_harness,no_run +//! extern crate hyper; +//! extern crate yup_oauth2 as oauth2; +//! extern crate google_clouduseraccountsvm_beta as clouduseraccountsvm_beta; +//! use clouduseraccountsvm_beta::PublicKey; +//! use clouduseraccountsvm_beta::{Result, Error}; +//! # #[test] fn egal() { +//! use std::default::Default; +//! use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +//! use clouduseraccountsvm_beta::CloudUserAccounts; +//! +//! // 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 = CloudUserAccounts::new(hyper::Client::new(), auth); +//! // As the method needs a request, you would usually fill it with the desired information +//! // into the respective structure. Some of the parts shown here might not be applicable ! +//! // Values shown here are possibly random and not representative ! +//! let mut req = PublicKey::default(); +//! +//! // You can configure optional parameters by calling 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().add_public_key(req, "project", "user") +//! .doit(); +//! +//! match result { +//! Err(e) => match e { +//! // The Error enum provides details about what exactly happened. +//! // You can also just use its `Debug`, `Display` or `Error` traits +//! Error::HttpError(_) +//! |Error::MissingAPIKey +//! |Error::MissingToken(_) +//! |Error::Cancelled +//! |Error::UploadSizeLimitExceeded(_, _) +//! |Error::Failure(_) +//! |Error::BadRequest(_) +//! |Error::FieldClash(_) +//! |Error::JsonDecodeError(_, _) => println!("{}", e), +//! }, +//! Ok(res) => println!("Success: {:?}", res), +//! } +//! # } +//! ``` +//! ## 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 Downloads +//! 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 identifiable 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 moved +//! +//! 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 +//! +//! + +// 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)] + +include!(concat!(env!("OUT_DIR"), "/lib.rs")); \ No newline at end of file diff --git a/gen/clouduseraccountsvm_beta/src/lib.rs.in b/gen/clouduseraccountsvm_beta/src/lib.rs.in new file mode 100644 index 0000000000..69d942accc --- /dev/null +++ b/gen/clouduseraccountsvm_beta/src/lib.rs.in @@ -0,0 +1,5774 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/api/lib.rs.in.mako' +// DO NOT EDIT ! + +extern crate hyper; +extern crate serde; +extern crate serde_json; +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 serde_json as json; +use std::io; +use std::fs; +use std::thread::sleep_ms; + +pub use cmn::{MultiPartReader, ToParts, MethodInfo, Result, Error, CallBuilder, Hub, ReadSeek, Part, + ResponseResult, RequestValue, NestedType, Delegate, DefaultDelegate, MethodsBuilder, + Resource, ErrorResponse, remove_json_null_values}; + + +// ############## +// 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 User Accounts + CloudUseraccountReadonly, + + /// View your data across Google Cloud Platform services + CloudPlatformReadOnly, + + /// View and manage your data across Google Cloud Platform services + CloudPlatform, + + /// Manage your Google Cloud User Accounts + CloudUseraccount, +} + +impl AsRef for Scope { + fn as_ref(&self) -> &str { + match *self { + Scope::CloudUseraccountReadonly => "https://www.googleapis.com/auth/cloud.useraccounts.readonly", + Scope::CloudPlatformReadOnly => "https://www.googleapis.com/auth/cloud-platform.read-only", + Scope::CloudPlatform => "https://www.googleapis.com/auth/cloud-platform", + Scope::CloudUseraccount => "https://www.googleapis.com/auth/cloud.useraccounts", + } + } +} + +impl Default for Scope { + fn default() -> Scope { + Scope::CloudUseraccountReadonly + } +} + + + +// ######## +// HUB ### +// ###### + +/// Central instance to access all CloudUserAccounts related resource activities +/// +/// # Examples +/// +/// Instantiate a new hub +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate yup_oauth2 as oauth2; +/// extern crate google_clouduseraccountsvm_beta as clouduseraccountsvm_beta; +/// use clouduseraccountsvm_beta::PublicKey; +/// use clouduseraccountsvm_beta::{Result, Error}; +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use clouduseraccountsvm_beta::CloudUserAccounts; +/// +/// // 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 = CloudUserAccounts::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req = PublicKey::default(); +/// +/// // You can configure optional parameters by calling 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().add_public_key(req, "project", "user") +/// .doit(); +/// +/// match result { +/// Err(e) => match e { +/// // The Error enum provides details about what exactly happened. +/// // You can also just use its `Debug`, `Display` or `Error` traits +/// Error::HttpError(_) +/// |Error::MissingAPIKey +/// |Error::MissingToken(_) +/// |Error::Cancelled +/// |Error::UploadSizeLimitExceeded(_, _) +/// |Error::Failure(_) +/// |Error::BadRequest(_) +/// |Error::FieldClash(_) +/// |Error::JsonDecodeError(_, _) => println!("{}", e), +/// }, +/// Ok(res) => println!("Success: {:?}", res), +/// } +/// # } +/// ``` +pub struct CloudUserAccounts { + client: RefCell, + auth: RefCell, + _user_agent: String, +} + +impl<'a, C, A> Hub for CloudUserAccounts {} + +impl<'a, C, A> CloudUserAccounts + where C: BorrowMut, A: oauth2::GetToken { + + pub fn new(client: C, authenticator: A) -> CloudUserAccounts { + CloudUserAccounts { + client: RefCell::new(client), + auth: RefCell::new(authenticator), + _user_agent: "google-api-rust-client/0.1.9".to_string(), + } + } + + pub fn global_accounts_operations(&'a self) -> GlobalAccountsOperationMethods<'a, C, A> { + GlobalAccountsOperationMethods { hub: &self } + } + pub fn groups(&'a self) -> GroupMethods<'a, C, A> { + GroupMethods { hub: &self } + } + pub fn linux(&'a self) -> LinuxMethods<'a, C, A> { + LinuxMethods { hub: &self } + } + pub fn users(&'a self) -> UserMethods<'a, C, 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.9`. + /// + /// 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 groups](struct.GroupListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct GroupList { + /// [Output Only] A token used to continue a truncated list request. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// [Output Only] A list of Group resources. + pub items: Option>, + /// [Output Only] Type of resource. Always clouduseraccounts#groupList for lists of groups. + pub kind: Option, + /// [Output Only] Unique identifier for the resource; defined by the server. + pub id: Option, + /// [Output Only] Server defined URL for this resource. + #[serde(rename="selfLink")] + pub self_link: Option, +} + +impl ResponseResult for GroupList {} + + +/// 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 linux account views linux](struct.LinuxGetLinuxAccountViewCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct LinuxGetLinuxAccountViewsResponse { + /// [Output Only] A list of authorized user accounts and groups. + pub resource: Option, +} + +impl ResponseResult for LinuxGetLinuxAccountViewsResponse {} + + +/// 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 member groups](struct.GroupAddMemberCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct GroupsAddMemberRequest { + /// Fully-qualified URLs of the User resources to add. + pub users: Option>, +} + +impl RequestValue for GroupsAddMemberRequest {} + + +/// [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 OperationWarningsData { + /// [Output Only] A key for the warning data. + pub key: Option, + /// [Output Only] A warning data value corresponding to the key. + pub value: Option, +} + +impl NestedType for OperationWarningsData {} +impl Part for OperationWarningsData {} + + +/// A list of all Linux accounts for this project. This API is only used by Compute Engine virtual machines to get information about user accounts for a project or instance. Linux resources are read-only views into users and groups managed by the Compute Engine Accounts 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 LinuxAccountViews { + /// [Output Only] Type of the resource. Always clouduseraccounts#linuxAccountViews for Linux resources. + pub kind: Option, + /// [Output Only] A list of all users within a project. + #[serde(rename="userViews")] + pub user_views: Option>, + /// [Output Only] A list of all groups within a project. + #[serde(rename="groupViews")] + pub group_views: Option>, +} + +impl Part for LinuxAccountViews {} + + +/// A detailed view of a Linux user 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 LinuxUserView { + /// [Output Only] The username of the account. + pub username: Option, + /// [Output Only] The path to the login shell for this account. + pub shell: Option, + /// [Output Only] The GECOS (user information) entry for this account. + pub gecos: Option, + /// [Output Only] User ID. + pub uid: Option, + /// [Output Only] The path to the home directory for this account. + #[serde(rename="homeDirectory")] + pub home_directory: Option, + /// [Output Only] User's default group ID. + pub gid: Option, +} + +impl Part for LinuxUserView {} + + +/// [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, Serialize, Deserialize)] +pub struct OperationWarnings { + /// [Output Only] Optional human-readable details for this warning. + pub message: Option, + /// [Output Only] The warning type identifier for this warning. + pub code: Option, + /// [Output Only] Metadata for this warning in key: value format. + pub data: Option>, +} + +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 global accounts operations](struct.GlobalAccountsOperationListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct OperationList { + /// [Output Only] A token used to continue a truncate. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// [Output Only] The Operation resources. + pub items: Option>, + /// [Output Only] Type of resource. Always compute#operations for Operations resource. + pub kind: Option, + /// [Output Only] Unique identifier for the resource; defined by the server. + pub id: Option, + /// [Output Only] Server-defined URL for this resource. + #[serde(rename="selfLink")] + pub self_link: Option, +} + +impl ResponseResult for OperationList {} + + +/// [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, Serialize, Deserialize)] +pub struct OperationError { + /// [Output Only] The array of errors encountered while processing this operation. + pub errors: Option>, +} + +impl NestedType for OperationError {} +impl Part for OperationError {} + + +/// [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, Serialize, Deserialize)] +pub struct OperationErrorErrors { + /// [Output Only] An optional, human-readable error message. + pub message: Option, + /// [Output Only] The error type identifier for this error. + pub code: Option, + /// [Output Only] Indicates the field in the request which caused the error. This property is optional. + pub location: Option, +} + +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 users](struct.UserListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct UserList { + /// [Output Only] A token used to continue a truncated list request. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// [Output Only] A list of User resources. + pub items: Option>, + /// [Output Only] Type of resource. Always clouduseraccounts#userList for lists of users. + pub kind: Option, + /// [Output Only] Unique identifier for the resource; defined by the server. + pub id: Option, + /// [Output Only] Server defined URL for this resource. + #[serde(rename="selfLink")] + pub self_link: Option, +} + +impl ResponseResult for UserList {} + + +/// A detailed view of a Linux 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 LinuxGroupView { + /// [Output Only] Group name. + #[serde(rename="groupName")] + pub group_name: Option, + /// [Output Only] The Group ID. + pub gid: Option, + /// [Output Only] List of user accounts that belong to the group. + pub members: Option>, +} + +impl Part for LinuxGroupView {} + + +/// A public key for authenticating to guests. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where 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 public key users](struct.UserAddPublicKeyCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct PublicKey { + /// Optional expiration timestamp. If provided, the timestamp must be in RFC3339 text format. If not provided, the public key never expires. + #[serde(rename="expirationTimestamp")] + pub expiration_timestamp: Option, + /// [Output Only] Creation timestamp in RFC3339 text format. + #[serde(rename="creationTimestamp")] + pub creation_timestamp: Option, + /// An optional textual description of the resource; provided by the client when the resource is created. + pub description: Option, + /// Public key text in SSH format, defined by RFC4253 section 6.6. + pub key: Option, + /// [Output Only] The fingerprint of the key is defined by RFC4716 to be the MD5 digest of the public key. + pub fingerprint: Option, +} + +impl RequestValue for PublicKey {} + + +/// 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 member groups](struct.GroupRemoveMemberCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct GroupsRemoveMemberRequest { + /// Fully-qualified URLs of the User resources to remove. + pub users: Option>, +} + +impl RequestValue for GroupsRemoveMemberRequest {} + + +/// A User 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*). +/// +/// * [add public key users](struct.UserAddPublicKeyCall.html) (none) +/// * [list users](struct.UserListCall.html) (none) +/// * [delete users](struct.UserDeleteCall.html) (none) +/// * [insert users](struct.UserInsertCall.html) (request) +/// * [get users](struct.UserGetCall.html) (response) +/// * [remove public key users](struct.UserRemovePublicKeyCall.html) (none) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct User { + /// [Output Only] Type of the resource. Always clouduseraccounts#user for users. + pub kind: Option, + /// Name of the resource; provided by the client when the resource is created. + pub name: Option, + /// [Output Only] Public keys that this user may use to login. + #[serde(rename="publicKeys")] + pub public_keys: Option>, + /// [Output Only] A list of URLs to Group resources who contain the user. Users are only members of groups in the same project. + pub groups: Option>, + /// Email address of account's owner. This account will be validated to make sure it exists. The email can belong to any domain, but it must be tied to a Google account. + pub owner: Option, + /// [Output Only] Creation timestamp in RFC3339 text format. + #[serde(rename="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(rename="selfLink")] + pub self_link: Option, + /// An optional textual description of the resource; provided by the client when the resource is created. + pub description: Option, +} + +impl RequestValue for User {} +impl Resource for User {} +impl ResponseResult for User {} + + +/// 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 authorized keys view linux](struct.LinuxGetAuthorizedKeysViewCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct LinuxGetAuthorizedKeysViewResponse { + /// [Output Only] A list of authorized public keys for a user. + pub resource: Option, +} + +impl ResponseResult for LinuxGetAuthorizedKeysViewResponse {} + + +/// A Group 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 groups](struct.GroupDeleteCall.html) (none) +/// * [remove member groups](struct.GroupRemoveMemberCall.html) (none) +/// * [get groups](struct.GroupGetCall.html) (response) +/// * [add member groups](struct.GroupAddMemberCall.html) (none) +/// * [insert groups](struct.GroupInsertCall.html) (request) +/// * [list groups](struct.GroupListCall.html) (none) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Group { + /// [Output Only] Type of the resource. Always clouduseraccounts#group for groups. + pub kind: Option, + /// Name of the resource; provided by the client when the resource is created. + pub name: Option, + /// [Output Only] A list of URLs to User resources who belong to the group. Users may only be members of groups in the same project. + pub members: Option>, + /// [Output Only] Creation timestamp in RFC3339 text format. + #[serde(rename="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(rename="selfLink")] + pub self_link: Option, + /// An optional textual description of the resource; provided by the client when the resource is created. + pub description: Option, +} + +impl RequestValue for Group {} +impl Resource for Group {} +impl ResponseResult for Group {} + + +/// A list of authorized public keys for a user 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 AuthorizedKeysView { + /// [Output Only] The list of authorized public keys in SSH format. + pub keys: Option>, + /// [Output Only] Whether the user has the ability to elevate on the instance that requested the authorized keys. + pub sudoer: Option, +} + +impl Part for AuthorizedKeysView {} + + +/// 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 groups](struct.GroupDeleteCall.html) (response) +/// * [add public key users](struct.UserAddPublicKeyCall.html) (response) +/// * [insert users](struct.UserInsertCall.html) (response) +/// * [add member groups](struct.GroupAddMemberCall.html) (response) +/// * [delete users](struct.UserDeleteCall.html) (response) +/// * [remove public key users](struct.UserRemovePublicKeyCall.html) (response) +/// * [insert groups](struct.GroupInsertCall.html) (response) +/// * [get global accounts operations](struct.GlobalAccountsOperationGetCall.html) (response) +/// * [remove member groups](struct.GroupRemoveMemberCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Operation { + /// [Output Only] Status of the operation. Can be one of the following: PENDING, RUNNING, or DONE. + pub status: Option, + /// [Output Only] The time that this operation was requested. This is in RFC3339 text format. + #[serde(rename="insertTime")] + pub insert_time: Option, + /// [Output Only] If warning messages are generated during processing of the operation, this field will be populated. + pub warnings: Option>, + /// [Output Only] If errors are generated during processing of the operation, this field will be populated. + pub error: Option, + /// [Output Only] Unique target ID which identifies a particular incarnation of the target. + #[serde(rename="targetId")] + pub target_id: Option, + /// [Output Only] URL of the resource the operation is mutating. + #[serde(rename="targetLink")] + pub target_link: Option, + /// [Output Only] The time that this operation was started by the server. This is in RFC3339 text format. + #[serde(rename="startTime")] + pub start_time: Option, + /// [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(rename="clientOperationId")] + pub client_operation_id: Option, + /// [Output Only] Creation timestamp in RFC3339 text format. + #[serde(rename="creationTimestamp")] + pub creation_timestamp: Option, + /// [Output Only] Unique identifier for the resource; defined by the server. + pub id: Option, + /// [Output Only] Type of the resource. Always compute#operation for Operation resources. + pub kind: Option, + /// [Output Only] Name of the resource. + pub name: Option, + /// [Output Only] URL of the zone where the operation resides. + pub zone: Option, + /// [Output Only] URL of the region where the operation resides. Only applicable for regional resources. + pub region: Option, + /// [Output Only] Server-defined URL for the resource. + #[serde(rename="selfLink")] + pub self_link: Option, + /// [Output Only] Type of the operation, such as insert, compute.instanceGroups.update, or compute.instanceGroups.delete. + #[serde(rename="operationType")] + pub operation_type: Option, + /// [Output Only] If the operation fails, this field contains the HTTP error message that was returned, such as NOT FOUND. + #[serde(rename="httpErrorMessage")] + pub http_error_message: Option, + /// [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 monotonically increase as the operation progresses. + pub progress: Option, + /// [Output Only] The time that this operation was completed. This is in RFC3339 text format. + #[serde(rename="endTime")] + pub end_time: Option, + /// [Output Only] If the operation fails, this field contains the HTTP error message that was returned, such as 404. + #[serde(rename="httpErrorStatusCode")] + pub http_error_status_code: Option, + /// [Output Only] An optional textual description of the current status of the operation. + #[serde(rename="statusMessage")] + pub status_message: Option, + /// [Output Only] User who requested the operation, for example: user@example.com. + pub user: Option, +} + +impl ResponseResult for Operation {} + + + +// ################### +// MethodBuilders ### +// ################# + +/// A builder providing access to all methods supported on *globalAccountsOperation* resources. +/// It is not used directly, but through the `CloudUserAccounts` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate yup_oauth2 as oauth2; +/// extern crate google_clouduseraccountsvm_beta as clouduseraccountsvm_beta; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use clouduseraccountsvm_beta::CloudUserAccounts; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = CloudUserAccounts::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.global_accounts_operations(); +/// # } +/// ``` +pub struct GlobalAccountsOperationMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a CloudUserAccounts, +} + +impl<'a, C, A> MethodsBuilder for GlobalAccountsOperationMethods<'a, C, A> {} + +impl<'a, C, A> GlobalAccountsOperationMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Deletes the specified operation resource. + /// + /// # Arguments + /// + /// * `project` - Project ID for this request. + /// * `operation` - Name of the Operations resource to delete. + pub fn delete(&self, project: &str, operation: &str) -> GlobalAccountsOperationDeleteCall<'a, C, A> { + GlobalAccountsOperationDeleteCall { + 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 operation resources contained within the specified project. + /// + /// # Arguments + /// + /// * `project` - Project ID for this request. + pub fn list(&self, project: &str) -> GlobalAccountsOperationListCall<'a, C, A> { + GlobalAccountsOperationListCall { + hub: self.hub, + _project: project.to_string(), + _page_token: Default::default(), + _order_by: 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. + /// + /// # Arguments + /// + /// * `project` - Project ID for this request. + /// * `operation` - Name of the Operations resource to return. + pub fn get(&self, project: &str, operation: &str) -> GlobalAccountsOperationGetCall<'a, C, A> { + GlobalAccountsOperationGetCall { + hub: self.hub, + _project: project.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 *user* resources. +/// It is not used directly, but through the `CloudUserAccounts` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate yup_oauth2 as oauth2; +/// extern crate google_clouduseraccountsvm_beta as clouduseraccountsvm_beta; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use clouduseraccountsvm_beta::CloudUserAccounts; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = CloudUserAccounts::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `add_public_key(...)`, `delete(...)`, `get(...)`, `insert(...)`, `list(...)` and `remove_public_key(...)` +/// // to build up your call. +/// let rb = hub.users(); +/// # } +/// ``` +pub struct UserMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a CloudUserAccounts, +} + +impl<'a, C, A> MethodsBuilder for UserMethods<'a, C, A> {} + +impl<'a, C, A> UserMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Adds a public key to the specified User resource with the data included in the request. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `project` - Project ID for this request. + /// * `user` - Name of the user for this request. + pub fn add_public_key(&self, request: PublicKey, project: &str, user: &str) -> UserAddPublicKeyCall<'a, C, A> { + UserAddPublicKeyCall { + hub: self.hub, + _request: request, + _project: project.to_string(), + _user: user.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 users contained within the specified project. + /// + /// # Arguments + /// + /// * `project` - Project ID for this request. + pub fn list(&self, project: &str) -> UserListCall<'a, C, A> { + UserListCall { + hub: self.hub, + _project: project.to_string(), + _page_token: Default::default(), + _order_by: 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 User resource in the specified project using the data included in the request. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `project` - Project ID for this request. + pub fn insert(&self, request: User, project: &str) -> UserInsertCall<'a, C, A> { + UserInsertCall { + hub: self.hub, + _request: request, + _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 User resource. + /// + /// # Arguments + /// + /// * `project` - Project ID for this request. + /// * `user` - Name of the user resource to return. + pub fn get(&self, project: &str, user: &str) -> UserGetCall<'a, C, A> { + UserGetCall { + hub: self.hub, + _project: project.to_string(), + _user: user.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Removes the specified public key from the user. + /// + /// # Arguments + /// + /// * `project` - Project ID for this request. + /// * `user` - Name of the user for this request. + /// * `fingerprint` - The fingerprint of the public key to delete. Public keys are identified by their fingerprint, which is defined by RFC4716 to be the MD5 digest of the public key. + pub fn remove_public_key(&self, project: &str, user: &str, fingerprint: &str) -> UserRemovePublicKeyCall<'a, C, A> { + UserRemovePublicKeyCall { + hub: self.hub, + _project: project.to_string(), + _user: user.to_string(), + _fingerprint: fingerprint.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 User resource. + /// + /// # Arguments + /// + /// * `project` - Project ID for this request. + /// * `user` - Name of the user resource to delete. + pub fn delete(&self, project: &str, user: &str) -> UserDeleteCall<'a, C, A> { + UserDeleteCall { + hub: self.hub, + _project: project.to_string(), + _user: user.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 `CloudUserAccounts` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate yup_oauth2 as oauth2; +/// extern crate google_clouduseraccountsvm_beta as clouduseraccountsvm_beta; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use clouduseraccountsvm_beta::CloudUserAccounts; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = CloudUserAccounts::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `add_member(...)`, `delete(...)`, `get(...)`, `insert(...)`, `list(...)` and `remove_member(...)` +/// // to build up your call. +/// let rb = hub.groups(); +/// # } +/// ``` +pub struct GroupMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a CloudUserAccounts, +} + +impl<'a, C, A> MethodsBuilder for GroupMethods<'a, C, A> {} + +impl<'a, C, A> GroupMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Deletes the specified Group resource. + /// + /// # Arguments + /// + /// * `project` - Project ID for this request. + /// * `groupName` - Name of the Group resource to delete. + pub fn delete(&self, project: &str, group_name: &str) -> GroupDeleteCall<'a, C, A> { + GroupDeleteCall { + hub: self.hub, + _project: project.to_string(), + _group_name: group_name.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 Group resource. + /// + /// # Arguments + /// + /// * `project` - Project ID for this request. + /// * `groupName` - Name of the Group resource to return. + pub fn get(&self, project: &str, group_name: &str) -> GroupGetCall<'a, C, A> { + GroupGetCall { + hub: self.hub, + _project: project.to_string(), + _group_name: group_name.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Adds users to the specified group. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `project` - Project ID for this request. + /// * `groupName` - Name of the group for this request. + pub fn add_member(&self, request: GroupsAddMemberRequest, project: &str, group_name: &str) -> GroupAddMemberCall<'a, C, A> { + GroupAddMemberCall { + hub: self.hub, + _request: request, + _project: project.to_string(), + _group_name: group_name.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Creates a Group resource in the specified project using the data included in the request. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `project` - Project ID for this request. + pub fn insert(&self, request: Group, project: &str) -> GroupInsertCall<'a, C, A> { + GroupInsertCall { + hub: self.hub, + _request: request, + _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 groups contained within the specified project. + /// + /// # Arguments + /// + /// * `project` - Project ID for this request. + pub fn list(&self, project: &str) -> GroupListCall<'a, C, A> { + GroupListCall { + hub: self.hub, + _project: project.to_string(), + _page_token: Default::default(), + _order_by: 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: + /// + /// Removes users from the specified group. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `project` - Project ID for this request. + /// * `groupName` - Name of the group for this request. + pub fn remove_member(&self, request: GroupsRemoveMemberRequest, project: &str, group_name: &str) -> GroupRemoveMemberCall<'a, C, A> { + GroupRemoveMemberCall { + hub: self.hub, + _request: request, + _project: project.to_string(), + _group_name: group_name.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *linux* resources. +/// It is not used directly, but through the `CloudUserAccounts` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate yup_oauth2 as oauth2; +/// extern crate google_clouduseraccountsvm_beta as clouduseraccountsvm_beta; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use clouduseraccountsvm_beta::CloudUserAccounts; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = CloudUserAccounts::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get_authorized_keys_view(...)` and `get_linux_account_views(...)` +/// // to build up your call. +/// let rb = hub.linux(); +/// # } +/// ``` +pub struct LinuxMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a CloudUserAccounts, +} + +impl<'a, C, A> MethodsBuilder for LinuxMethods<'a, C, A> {} + +impl<'a, C, A> LinuxMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a list of user accounts for an instance within a specific project. + /// + /// # Arguments + /// + /// * `project` - Project ID for this request. + /// * `zone` - Name of the zone for this request. + /// * `instance` - The fully-qualified URL of the virtual machine requesting the views. + pub fn get_linux_account_views(&self, project: &str, zone: &str, instance: &str) -> LinuxGetLinuxAccountViewCall<'a, C, A> { + LinuxGetLinuxAccountViewCall { + hub: self.hub, + _project: project.to_string(), + _zone: zone.to_string(), + _instance: instance.to_string(), + _page_token: Default::default(), + _order_by: 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 a list of authorized public keys for a specific user account. + /// + /// # Arguments + /// + /// * `project` - Project ID for this request. + /// * `zone` - Name of the zone for this request. + /// * `user` - The user account for which you want to get a list of authorized public keys. + /// * `instance` - The fully-qualified URL of the virtual machine requesting the view. + pub fn get_authorized_keys_view(&self, project: &str, zone: &str, user: &str, instance: &str) -> LinuxGetAuthorizedKeysViewCall<'a, C, A> { + LinuxGetAuthorizedKeysViewCall { + hub: self.hub, + _project: project.to_string(), + _zone: zone.to_string(), + _user: user.to_string(), + _instance: instance.to_string(), + _login: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + + + +// ################### +// CallBuilders ### +// ################# + +/// Deletes the specified operation resource. +/// +/// A builder for the *delete* method supported by a *globalAccountsOperation* resource. +/// It is not used directly, but through a `GlobalAccountsOperationMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_clouduseraccountsvm_beta as clouduseraccountsvm_beta; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use clouduseraccountsvm_beta::CloudUserAccounts; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = CloudUserAccounts::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling 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_accounts_operations().delete("project", "operation") +/// .doit(); +/// # } +/// ``` +pub struct GlobalAccountsOperationDeleteCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a CloudUserAccounts, + _project: String, + _operation: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for GlobalAccountsOperationDeleteCall<'a, C, A> {} + +impl<'a, C, A> GlobalAccountsOperationDeleteCall<'a, C, A> where 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: "clouduseraccounts.globalAccountsOperations.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 Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/clouduseraccounts/vm_beta/projects/{project}/global/operations/{operation}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().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 ["operation", "project"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = res; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Project ID for this request. + /// + /// 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) -> GlobalAccountsOperationDeleteCall<'a, C, A> { + self._project = new_value.to_string(); + self + } + /// Name of the Operations resource to delete. + /// + /// 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) -> GlobalAccountsOperationDeleteCall<'a, C, A> { + self._operation = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> GlobalAccountsOperationDeleteCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> GlobalAccountsOperationDeleteCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> GlobalAccountsOperationDeleteCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Retrieves the list of operation resources contained within the specified project. +/// +/// A builder for the *list* method supported by a *globalAccountsOperation* resource. +/// It is not used directly, but through a `GlobalAccountsOperationMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_clouduseraccountsvm_beta as clouduseraccountsvm_beta; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use clouduseraccountsvm_beta::CloudUserAccounts; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = CloudUserAccounts::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling 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_accounts_operations().list("project") +/// .page_token("accusam") +/// .order_by("takimata") +/// .max_results(31) +/// .filter("amet.") +/// .doit(); +/// # } +/// ``` +pub struct GlobalAccountsOperationListCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a CloudUserAccounts, + _project: String, + _page_token: Option, + _order_by: Option, + _max_results: Option, + _filter: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for GlobalAccountsOperationListCall<'a, C, A> {} + +impl<'a, C, A> GlobalAccountsOperationListCall<'a, C, A> where 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: "clouduseraccounts.globalAccountsOperations.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._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._filter { + params.push(("filter", value.to_string())); + } + for &field in ["alt", "project", "pageToken", "orderBy", "maxResults", "filter"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/clouduseraccounts/vm_beta/projects/{project}/global/operations".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudUseraccountReadonly.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Project ID for this request. + /// + /// 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) -> GlobalAccountsOperationListCall<'a, C, A> { + self._project = new_value.to_string(); + self + } + /// Specifies a page token to use. Use this parameter if you want to list the next page of results. Set pageToken to the nextPageToken returned by a previous list request. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> GlobalAccountsOperationListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource name. + /// + /// You can also sort results in descending order based on the creation timestamp using orderBy="creationTimestamp desc". This sorts results based on the creationTimestamp field in reverse chronological order (newest result first). Use this to sort resources like operations so that the newest operation is returned first. + /// + /// Currently, only sorting by name or creationTimestamp desc is supported. + /// + /// Sets the *order by* query property to the given value. + pub fn order_by(mut self, new_value: &str) -> GlobalAccountsOperationListCall<'a, C, A> { + self._order_by = Some(new_value.to_string()); + self + } + /// Maximum count of results to be returned. + /// + /// Sets the *max results* query property to the given value. + pub fn max_results(mut self, new_value: u32) -> GlobalAccountsOperationListCall<'a, C, A> { + self._max_results = Some(new_value); + self + } + /// Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must be in the format: FIELD_NAME COMPARISON_STRING LITERAL_STRING. + /// + /// The FIELD_NAME is the name of the field you want to compare. Only atomic field types are supported (string, number, boolean). The COMPARISON_STRING must be either eq (equals) or ne (not equals). The LITERAL_STRING is the string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field. + /// + /// For example, filter=name ne example-instance. + /// + /// Sets the *filter* query property to the given value. + pub fn filter(mut self, new_value: &str) -> GlobalAccountsOperationListCall<'a, C, A> { + self._filter = Some(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> GlobalAccountsOperationListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> GlobalAccountsOperationListCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudUseraccountReadonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> GlobalAccountsOperationListCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Retrieves the specified operation resource. +/// +/// A builder for the *get* method supported by a *globalAccountsOperation* resource. +/// It is not used directly, but through a `GlobalAccountsOperationMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_clouduseraccountsvm_beta as clouduseraccountsvm_beta; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use clouduseraccountsvm_beta::CloudUserAccounts; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = CloudUserAccounts::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling 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_accounts_operations().get("project", "operation") +/// .doit(); +/// # } +/// ``` +pub struct GlobalAccountsOperationGetCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a CloudUserAccounts, + _project: String, + _operation: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for GlobalAccountsOperationGetCall<'a, C, A> {} + +impl<'a, C, A> GlobalAccountsOperationGetCall<'a, C, A> where 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: "clouduseraccounts.globalAccountsOperations.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 Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/clouduseraccounts/vm_beta/projects/{project}/global/operations/{operation}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudUseraccountReadonly.as_ref().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 ["operation", "project"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Project ID for this request. + /// + /// 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) -> GlobalAccountsOperationGetCall<'a, C, A> { + self._project = new_value.to_string(); + self + } + /// Name of the Operations resource to return. + /// + /// 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) -> GlobalAccountsOperationGetCall<'a, C, A> { + self._operation = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> GlobalAccountsOperationGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> GlobalAccountsOperationGetCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudUseraccountReadonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> GlobalAccountsOperationGetCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Adds a public key to the specified User resource with the data included in the request. +/// +/// A builder for the *addPublicKey* method supported by a *user* resource. +/// It is not used directly, but through a `UserMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_clouduseraccountsvm_beta as clouduseraccountsvm_beta; +/// use clouduseraccountsvm_beta::PublicKey; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use clouduseraccountsvm_beta::CloudUserAccounts; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = CloudUserAccounts::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req = PublicKey::default(); +/// +/// // You can configure optional parameters by calling 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().add_public_key(req, "project", "user") +/// .doit(); +/// # } +/// ``` +pub struct UserAddPublicKeyCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a CloudUserAccounts, + _request: PublicKey, + _project: String, + _user: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for UserAddPublicKeyCall<'a, C, A> {} + +impl<'a, C, A> UserAddPublicKeyCall<'a, C, A> where 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: "clouduseraccounts.users.addPublicKey", + 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(("user", self._user.to_string())); + for &field in ["alt", "project", "user"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/clouduseraccounts/vm_beta/projects/{project}/global/users/{user}/addPublicKey".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{user}", "user")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["user", "project"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: PublicKey) -> UserAddPublicKeyCall<'a, C, A> { + self._request = new_value; + self + } + /// Project ID for this request. + /// + /// 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) -> UserAddPublicKeyCall<'a, C, A> { + self._project = new_value.to_string(); + self + } + /// Name of the user for this request. + /// + /// Sets the *user* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn user(mut self, new_value: &str) -> UserAddPublicKeyCall<'a, C, A> { + self._user = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserAddPublicKeyCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> UserAddPublicKeyCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> UserAddPublicKeyCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Retrieves a list of users contained within the specified project. +/// +/// A builder for the *list* method supported by a *user* resource. +/// It is not used directly, but through a `UserMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_clouduseraccountsvm_beta as clouduseraccountsvm_beta; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use clouduseraccountsvm_beta::CloudUserAccounts; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = CloudUserAccounts::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling 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("project") +/// .page_token("gubergren") +/// .order_by("sadipscing") +/// .max_results(70) +/// .filter("ea") +/// .doit(); +/// # } +/// ``` +pub struct UserListCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a CloudUserAccounts, + _project: String, + _page_token: Option, + _order_by: Option, + _max_results: Option, + _filter: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for UserListCall<'a, C, A> {} + +impl<'a, C, A> UserListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, UserList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "clouduseraccounts.users.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._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._filter { + params.push(("filter", value.to_string())); + } + for &field in ["alt", "project", "pageToken", "orderBy", "maxResults", "filter"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/clouduseraccounts/vm_beta/projects/{project}/global/users".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudUseraccountReadonly.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Project ID for this request. + /// + /// 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) -> UserListCall<'a, C, A> { + self._project = new_value.to_string(); + self + } + /// Specifies a page token to use. Use this parameter if you want to list the next page of results. Set pageToken to the nextPageToken returned by a previous list request. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> UserListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource name. + /// + /// You can also sort results in descending order based on the creation timestamp using orderBy="creationTimestamp desc". This sorts results based on the creationTimestamp field in reverse chronological order (newest result first). Use this to sort resources like operations so that the newest operation is returned first. + /// + /// Currently, only sorting by name or creationTimestamp desc is supported. + /// + /// Sets the *order by* query property to the given value. + pub fn order_by(mut self, new_value: &str) -> UserListCall<'a, C, A> { + self._order_by = Some(new_value.to_string()); + self + } + /// Maximum count of results to be returned. + /// + /// Sets the *max results* query property to the given value. + pub fn max_results(mut self, new_value: u32) -> UserListCall<'a, C, A> { + self._max_results = Some(new_value); + self + } + /// Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must be in the format: FIELD_NAME COMPARISON_STRING LITERAL_STRING. + /// + /// The FIELD_NAME is the name of the field you want to compare. Only atomic field types are supported (string, number, boolean). The COMPARISON_STRING must be either eq (equals) or ne (not equals). The LITERAL_STRING is the string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field. + /// + /// For example, filter=name ne example-instance. + /// + /// Sets the *filter* query property to the given value. + pub fn filter(mut self, new_value: &str) -> UserListCall<'a, C, A> { + self._filter = Some(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudUseraccountReadonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Creates a User resource in the specified project using the data included in the request. +/// +/// A builder for the *insert* method supported by a *user* resource. +/// It is not used directly, but through a `UserMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_clouduseraccountsvm_beta as clouduseraccountsvm_beta; +/// use clouduseraccountsvm_beta::User; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use clouduseraccountsvm_beta::CloudUserAccounts; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = CloudUserAccounts::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the 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(); +/// +/// // You can configure optional parameters by calling 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, "project") +/// .doit(); +/// # } +/// ``` +pub struct UserInsertCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a CloudUserAccounts, + _request: User, + _project: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for UserInsertCall<'a, C, A> {} + +impl<'a, C, A> UserInsertCall<'a, C, A> where 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: "clouduseraccounts.users.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 Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/clouduseraccounts/vm_beta/projects/{project}/global/users".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// Project ID for this request. + /// + /// 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) -> UserInsertCall<'a, C, A> { + self._project = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserInsertCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Returns the specified User resource. +/// +/// A builder for the *get* method supported by a *user* resource. +/// It is not used directly, but through a `UserMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_clouduseraccountsvm_beta as clouduseraccountsvm_beta; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use clouduseraccountsvm_beta::CloudUserAccounts; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = CloudUserAccounts::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling 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("project", "user") +/// .doit(); +/// # } +/// ``` +pub struct UserGetCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a CloudUserAccounts, + _project: String, + _user: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for UserGetCall<'a, C, A> {} + +impl<'a, C, A> UserGetCall<'a, C, A> where 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: "clouduseraccounts.users.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(("user", self._user.to_string())); + for &field in ["alt", "project", "user"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/clouduseraccounts/vm_beta/projects/{project}/global/users/{user}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudUseraccountReadonly.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{user}", "user")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["user", "project"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Project ID for this request. + /// + /// 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) -> UserGetCall<'a, C, A> { + self._project = new_value.to_string(); + self + } + /// Name of the user resource to return. + /// + /// Sets the *user* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn user(mut self, new_value: &str) -> UserGetCall<'a, C, A> { + self._user = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudUseraccountReadonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Removes the specified public key from the user. +/// +/// A builder for the *removePublicKey* method supported by a *user* resource. +/// It is not used directly, but through a `UserMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_clouduseraccountsvm_beta as clouduseraccountsvm_beta; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use clouduseraccountsvm_beta::CloudUserAccounts; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = CloudUserAccounts::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling 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().remove_public_key("project", "user", "fingerprint") +/// .doit(); +/// # } +/// ``` +pub struct UserRemovePublicKeyCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a CloudUserAccounts, + _project: String, + _user: String, + _fingerprint: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for UserRemovePublicKeyCall<'a, C, A> {} + +impl<'a, C, A> UserRemovePublicKeyCall<'a, C, A> where 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: "clouduseraccounts.users.removePublicKey", + 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(("user", self._user.to_string())); + params.push(("fingerprint", self._fingerprint.to_string())); + for &field in ["alt", "project", "user", "fingerprint"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/clouduseraccounts/vm_beta/projects/{project}/global/users/{user}/removePublicKey".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{user}", "user")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["user", "project"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Project ID for this request. + /// + /// 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) -> UserRemovePublicKeyCall<'a, C, A> { + self._project = new_value.to_string(); + self + } + /// Name of the user for this request. + /// + /// Sets the *user* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn user(mut self, new_value: &str) -> UserRemovePublicKeyCall<'a, C, A> { + self._user = new_value.to_string(); + self + } + /// The fingerprint of the public key to delete. Public keys are identified by their fingerprint, which is defined by RFC4716 to be the MD5 digest of the public key. + /// + /// Sets the *fingerprint* 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. + pub fn fingerprint(mut self, new_value: &str) -> UserRemovePublicKeyCall<'a, C, A> { + self._fingerprint = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserRemovePublicKeyCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> UserRemovePublicKeyCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> UserRemovePublicKeyCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Deletes the specified User resource. +/// +/// A builder for the *delete* method supported by a *user* resource. +/// It is not used directly, but through a `UserMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_clouduseraccountsvm_beta as clouduseraccountsvm_beta; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use clouduseraccountsvm_beta::CloudUserAccounts; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = CloudUserAccounts::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling 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("project", "user") +/// .doit(); +/// # } +/// ``` +pub struct UserDeleteCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a CloudUserAccounts, + _project: String, + _user: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for UserDeleteCall<'a, C, A> {} + +impl<'a, C, A> UserDeleteCall<'a, C, A> where 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: "clouduseraccounts.users.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(("user", self._user.to_string())); + for &field in ["alt", "project", "user"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/clouduseraccounts/vm_beta/projects/{project}/global/users/{user}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{user}", "user")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["user", "project"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Project ID for this request. + /// + /// 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) -> UserDeleteCall<'a, C, A> { + self._project = new_value.to_string(); + self + } + /// Name of the user resource to delete. + /// + /// Sets the *user* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn user(mut self, new_value: &str) -> UserDeleteCall<'a, C, A> { + self._user = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserDeleteCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Deletes the specified Group resource. +/// +/// A builder for the *delete* method supported by a *group* resource. +/// It is not used directly, but through a `GroupMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_clouduseraccountsvm_beta as clouduseraccountsvm_beta; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use clouduseraccountsvm_beta::CloudUserAccounts; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = CloudUserAccounts::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling 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("project", "groupName") +/// .doit(); +/// # } +/// ``` +pub struct GroupDeleteCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a CloudUserAccounts, + _project: String, + _group_name: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for GroupDeleteCall<'a, C, A> {} + +impl<'a, C, A> GroupDeleteCall<'a, C, A> where 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: "clouduseraccounts.groups.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(("groupName", self._group_name.to_string())); + for &field in ["alt", "project", "groupName"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/clouduseraccounts/vm_beta/projects/{project}/global/groups/{groupName}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{groupName}", "groupName")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["groupName", "project"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Project ID for this request. + /// + /// 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) -> GroupDeleteCall<'a, C, A> { + self._project = new_value.to_string(); + self + } + /// Name of the Group resource to delete. + /// + /// Sets the *group 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 group_name(mut self, new_value: &str) -> GroupDeleteCall<'a, C, A> { + self._group_name = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> GroupDeleteCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Returns the specified Group resource. +/// +/// A builder for the *get* method supported by a *group* resource. +/// It is not used directly, but through a `GroupMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_clouduseraccountsvm_beta as clouduseraccountsvm_beta; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use clouduseraccountsvm_beta::CloudUserAccounts; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = CloudUserAccounts::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling 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("project", "groupName") +/// .doit(); +/// # } +/// ``` +pub struct GroupGetCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a CloudUserAccounts, + _project: String, + _group_name: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for GroupGetCall<'a, C, A> {} + +impl<'a, C, A> GroupGetCall<'a, C, A> where 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: "clouduseraccounts.groups.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(("groupName", self._group_name.to_string())); + for &field in ["alt", "project", "groupName"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/clouduseraccounts/vm_beta/projects/{project}/global/groups/{groupName}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudUseraccountReadonly.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{groupName}", "groupName")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["groupName", "project"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Project ID for this request. + /// + /// 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) -> GroupGetCall<'a, C, A> { + self._project = new_value.to_string(); + self + } + /// Name of the Group resource to return. + /// + /// Sets the *group 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 group_name(mut self, new_value: &str) -> GroupGetCall<'a, C, A> { + self._group_name = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> GroupGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudUseraccountReadonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Adds users to the specified group. +/// +/// A builder for the *addMember* method supported by a *group* resource. +/// It is not used directly, but through a `GroupMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_clouduseraccountsvm_beta as clouduseraccountsvm_beta; +/// use clouduseraccountsvm_beta::GroupsAddMemberRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use clouduseraccountsvm_beta::CloudUserAccounts; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = CloudUserAccounts::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req = GroupsAddMemberRequest::default(); +/// +/// // You can configure optional parameters by calling 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().add_member(req, "project", "groupName") +/// .doit(); +/// # } +/// ``` +pub struct GroupAddMemberCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a CloudUserAccounts, + _request: GroupsAddMemberRequest, + _project: String, + _group_name: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for GroupAddMemberCall<'a, C, A> {} + +impl<'a, C, A> GroupAddMemberCall<'a, C, A> where 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: "clouduseraccounts.groups.addMember", + 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(("groupName", self._group_name.to_string())); + for &field in ["alt", "project", "groupName"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/clouduseraccounts/vm_beta/projects/{project}/global/groups/{groupName}/addMember".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{groupName}", "groupName")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["groupName", "project"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: GroupsAddMemberRequest) -> GroupAddMemberCall<'a, C, A> { + self._request = new_value; + self + } + /// Project ID for this request. + /// + /// 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) -> GroupAddMemberCall<'a, C, A> { + self._project = new_value.to_string(); + self + } + /// Name of the group for this request. + /// + /// Sets the *group 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 group_name(mut self, new_value: &str) -> GroupAddMemberCall<'a, C, A> { + self._group_name = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> GroupAddMemberCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> GroupAddMemberCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> GroupAddMemberCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Creates a Group resource in the specified project using the data included in the request. +/// +/// A builder for the *insert* method supported by a *group* resource. +/// It is not used directly, but through a `GroupMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_clouduseraccountsvm_beta as clouduseraccountsvm_beta; +/// use clouduseraccountsvm_beta::Group; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use clouduseraccountsvm_beta::CloudUserAccounts; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = CloudUserAccounts::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the 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(); +/// +/// // You can configure optional parameters by calling 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, "project") +/// .doit(); +/// # } +/// ``` +pub struct GroupInsertCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a CloudUserAccounts, + _request: Group, + _project: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for GroupInsertCall<'a, C, A> {} + +impl<'a, C, A> GroupInsertCall<'a, C, A> where 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: "clouduseraccounts.groups.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 Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/clouduseraccounts/vm_beta/projects/{project}/global/groups".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// Project ID for this request. + /// + /// 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) -> GroupInsertCall<'a, C, A> { + self._project = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> GroupInsertCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Retrieves the list of groups contained within the specified project. +/// +/// A builder for the *list* method supported by a *group* resource. +/// It is not used directly, but through a `GroupMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_clouduseraccountsvm_beta as clouduseraccountsvm_beta; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use clouduseraccountsvm_beta::CloudUserAccounts; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = CloudUserAccounts::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling 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("project") +/// .page_token("dolor") +/// .order_by("eirmod") +/// .max_results(58) +/// .filter("amet") +/// .doit(); +/// # } +/// ``` +pub struct GroupListCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a CloudUserAccounts, + _project: String, + _page_token: Option, + _order_by: Option, + _max_results: Option, + _filter: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for GroupListCall<'a, C, A> {} + +impl<'a, C, A> GroupListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, GroupList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "clouduseraccounts.groups.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._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._filter { + params.push(("filter", value.to_string())); + } + for &field in ["alt", "project", "pageToken", "orderBy", "maxResults", "filter"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/clouduseraccounts/vm_beta/projects/{project}/global/groups".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudUseraccountReadonly.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Project ID for this request. + /// + /// 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) -> GroupListCall<'a, C, A> { + self._project = new_value.to_string(); + self + } + /// Specifies a page token to use. Use this parameter if you want to list the next page of results. Set pageToken to the nextPageToken returned by a previous list request. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> GroupListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource name. + /// + /// You can also sort results in descending order based on the creation timestamp using orderBy="creationTimestamp desc". This sorts results based on the creationTimestamp field in reverse chronological order (newest result first). Use this to sort resources like operations so that the newest operation is returned first. + /// + /// Currently, only sorting by name or creationTimestamp desc is supported. + /// + /// Sets the *order by* query property to the given value. + pub fn order_by(mut self, new_value: &str) -> GroupListCall<'a, C, A> { + self._order_by = Some(new_value.to_string()); + self + } + /// Maximum count of results to be returned. + /// + /// Sets the *max results* query property to the given value. + pub fn max_results(mut self, new_value: u32) -> GroupListCall<'a, C, A> { + self._max_results = Some(new_value); + self + } + /// Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must be in the format: FIELD_NAME COMPARISON_STRING LITERAL_STRING. + /// + /// The FIELD_NAME is the name of the field you want to compare. Only atomic field types are supported (string, number, boolean). The COMPARISON_STRING must be either eq (equals) or ne (not equals). The LITERAL_STRING is the string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field. + /// + /// For example, filter=name ne example-instance. + /// + /// Sets the *filter* query property to the given value. + pub fn filter(mut self, new_value: &str) -> GroupListCall<'a, C, A> { + self._filter = Some(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> GroupListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudUseraccountReadonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Removes users from the specified group. +/// +/// A builder for the *removeMember* method supported by a *group* resource. +/// It is not used directly, but through a `GroupMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_clouduseraccountsvm_beta as clouduseraccountsvm_beta; +/// use clouduseraccountsvm_beta::GroupsRemoveMemberRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use clouduseraccountsvm_beta::CloudUserAccounts; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = CloudUserAccounts::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req = GroupsRemoveMemberRequest::default(); +/// +/// // You can configure optional parameters by calling 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().remove_member(req, "project", "groupName") +/// .doit(); +/// # } +/// ``` +pub struct GroupRemoveMemberCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a CloudUserAccounts, + _request: GroupsRemoveMemberRequest, + _project: String, + _group_name: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for GroupRemoveMemberCall<'a, C, A> {} + +impl<'a, C, A> GroupRemoveMemberCall<'a, C, A> where 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: "clouduseraccounts.groups.removeMember", + 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(("groupName", self._group_name.to_string())); + for &field in ["alt", "project", "groupName"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/clouduseraccounts/vm_beta/projects/{project}/global/groups/{groupName}/removeMember".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{groupName}", "groupName")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["groupName", "project"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: GroupsRemoveMemberRequest) -> GroupRemoveMemberCall<'a, C, A> { + self._request = new_value; + self + } + /// Project ID for this request. + /// + /// 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) -> GroupRemoveMemberCall<'a, C, A> { + self._project = new_value.to_string(); + self + } + /// Name of the group for this request. + /// + /// Sets the *group 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 group_name(mut self, new_value: &str) -> GroupRemoveMemberCall<'a, C, A> { + self._group_name = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> GroupRemoveMemberCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> GroupRemoveMemberCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> GroupRemoveMemberCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Retrieves a list of user accounts for an instance within a specific project. +/// +/// A builder for the *getLinuxAccountViews* method supported by a *linux* resource. +/// It is not used directly, but through a `LinuxMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_clouduseraccountsvm_beta as clouduseraccountsvm_beta; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use clouduseraccountsvm_beta::CloudUserAccounts; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = CloudUserAccounts::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.linux().get_linux_account_views("project", "zone", "instance") +/// .page_token("aliquyam") +/// .order_by("accusam") +/// .max_results(45) +/// .filter("sea") +/// .doit(); +/// # } +/// ``` +pub struct LinuxGetLinuxAccountViewCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a CloudUserAccounts, + _project: String, + _zone: String, + _instance: String, + _page_token: Option, + _order_by: Option, + _max_results: Option, + _filter: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for LinuxGetLinuxAccountViewCall<'a, C, A> {} + +impl<'a, C, A> LinuxGetLinuxAccountViewCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, LinuxGetLinuxAccountViewsResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "clouduseraccounts.linux.getLinuxAccountViews", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((9 + 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())); + 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._filter { + params.push(("filter", value.to_string())); + } + for &field in ["alt", "project", "zone", "instance", "pageToken", "orderBy", "maxResults", "filter"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/clouduseraccounts/vm_beta/projects/{project}/zones/{zone}/linuxAccountViews".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().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 ["zone", "project"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Project ID for this request. + /// + /// 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) -> LinuxGetLinuxAccountViewCall<'a, C, A> { + self._project = new_value.to_string(); + self + } + /// Name of the zone for this request. + /// + /// 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) -> LinuxGetLinuxAccountViewCall<'a, C, A> { + self._zone = new_value.to_string(); + self + } + /// The fully-qualified URL of the virtual machine requesting the views. + /// + /// Sets the *instance* 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. + pub fn instance(mut self, new_value: &str) -> LinuxGetLinuxAccountViewCall<'a, C, A> { + self._instance = new_value.to_string(); + self + } + /// Specifies a page token to use. Use this parameter if you want to list the next page of results. Set pageToken to the nextPageToken returned by a previous list request. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> LinuxGetLinuxAccountViewCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource name. + /// + /// You can also sort results in descending order based on the creation timestamp using orderBy="creationTimestamp desc". This sorts results based on the creationTimestamp field in reverse chronological order (newest result first). Use this to sort resources like operations so that the newest operation is returned first. + /// + /// Currently, only sorting by name or creationTimestamp desc is supported. + /// + /// Sets the *order by* query property to the given value. + pub fn order_by(mut self, new_value: &str) -> LinuxGetLinuxAccountViewCall<'a, C, A> { + self._order_by = Some(new_value.to_string()); + self + } + /// Maximum count of results to be returned. + /// + /// Sets the *max results* query property to the given value. + pub fn max_results(mut self, new_value: u32) -> LinuxGetLinuxAccountViewCall<'a, C, A> { + self._max_results = Some(new_value); + self + } + /// Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must be in the format: FIELD_NAME COMPARISON_STRING LITERAL_STRING. + /// + /// The FIELD_NAME is the name of the field you want to compare. Only atomic field types are supported (string, number, boolean). The COMPARISON_STRING must be either eq (equals) or ne (not equals). The LITERAL_STRING is the string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field. + /// + /// For example, filter=name ne example-instance. + /// + /// Sets the *filter* query property to the given value. + pub fn filter(mut self, new_value: &str) -> LinuxGetLinuxAccountViewCall<'a, C, A> { + self._filter = Some(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> LinuxGetLinuxAccountViewCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> LinuxGetLinuxAccountViewCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> LinuxGetLinuxAccountViewCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Returns a list of authorized public keys for a specific user account. +/// +/// A builder for the *getAuthorizedKeysView* method supported by a *linux* resource. +/// It is not used directly, but through a `LinuxMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_clouduseraccountsvm_beta as clouduseraccountsvm_beta; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use clouduseraccountsvm_beta::CloudUserAccounts; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = CloudUserAccounts::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.linux().get_authorized_keys_view("project", "zone", "user", "instance") +/// .login(false) +/// .doit(); +/// # } +/// ``` +pub struct LinuxGetAuthorizedKeysViewCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a CloudUserAccounts, + _project: String, + _zone: String, + _user: String, + _instance: String, + _login: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for LinuxGetAuthorizedKeysViewCall<'a, C, A> {} + +impl<'a, C, A> LinuxGetAuthorizedKeysViewCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, LinuxGetAuthorizedKeysViewResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "clouduseraccounts.linux.getAuthorizedKeysView", + 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(("user", self._user.to_string())); + params.push(("instance", self._instance.to_string())); + if let Some(value) = self._login { + params.push(("login", value.to_string())); + } + for &field in ["alt", "project", "zone", "user", "instance", "login"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/clouduseraccounts/vm_beta/projects/{project}/zones/{zone}/authorizedKeysView/{user}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{zone}", "zone"), ("{user}", "user")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + 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 ["user", "zone", "project"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Project ID for this request. + /// + /// 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) -> LinuxGetAuthorizedKeysViewCall<'a, C, A> { + self._project = new_value.to_string(); + self + } + /// Name of the zone for this request. + /// + /// 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) -> LinuxGetAuthorizedKeysViewCall<'a, C, A> { + self._zone = new_value.to_string(); + self + } + /// The user account for which you want to get a list of authorized public keys. + /// + /// Sets the *user* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn user(mut self, new_value: &str) -> LinuxGetAuthorizedKeysViewCall<'a, C, A> { + self._user = new_value.to_string(); + self + } + /// The fully-qualified URL of the virtual machine requesting the view. + /// + /// Sets the *instance* 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. + pub fn instance(mut self, new_value: &str) -> LinuxGetAuthorizedKeysViewCall<'a, C, A> { + self._instance = new_value.to_string(); + self + } + /// Whether the view was requested as part of a user-initiated login. + /// + /// Sets the *login* query property to the given value. + pub fn login(mut self, new_value: bool) -> LinuxGetAuthorizedKeysViewCall<'a, C, A> { + self._login = Some(new_value); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> LinuxGetAuthorizedKeysViewCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> LinuxGetAuthorizedKeysViewCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> LinuxGetAuthorizedKeysViewCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + diff --git a/gen/compute1-cli/Cargo.toml b/gen/compute1-cli/Cargo.toml index 9f63c1d174..087d42e5f3 100644 --- a/gen/compute1-cli/Cargo.toml +++ b/gen/compute1-cli/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-compute1-cli" -version = "0.3.2+20150713" +version = "0.3.2+20151015" 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-cli" diff --git a/gen/compute1-cli/README.md b/gen/compute1-cli/README.md index 865edf8d4a..903df10eed 100644 --- a/gen/compute1-cli/README.md +++ b/gen/compute1-cli/README.md @@ -24,7 +24,7 @@ Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/ma # Usage -This documentation was generated from the *compute* API at revision *20150713*. The CLI is at version *0.3.2*. +This documentation was generated from the *compute* API at revision *20151015*. The CLI is at version *0.3.2*. ```bash compute1 [options] @@ -98,6 +98,13 @@ compute1 [options] list [-p ]... [-o ] patch (-r )... [-p ]... [-o ] update (-r )... [-p ]... [-o ] + https-health-checks + delete [-p ]... [-o ] + get [-p ]... [-o ] + insert (-r )... [-p ]... [-o ] + list [-p ]... [-o ] + patch (-r )... [-p ]... [-o ] + update (-r )... [-p ]... [-o ] images delete [-p ]... [-o ] deprecate (-r )... [-p ]... [-o ] @@ -183,12 +190,24 @@ compute1 [options] delete [-p ]... [-o ] get [-p ]... [-o ] list [-p ]... [-o ] + ssl-certificates + delete [-p ]... [-o ] + get [-p ]... [-o ] + insert (-r )... [-p ]... [-o ] + list [-p ]... [-o ] target-http-proxies delete [-p ]... [-o ] get [-p ]... [-o ] insert (-r )... [-p ]... [-o ] list [-p ]... [-o ] set-url-map (-r )... [-p ]... [-o ] + target-https-proxies + delete [-p ]... [-o ] + get [-p ]... [-o ] + insert (-r )... [-p ]... [-o ] + list [-p ]... [-o ] + set-ssl-certificates (-r )... [-p ]... [-o ] + set-url-map (-r )... [-p ]... [-o ] target-instances aggregated-list [-p ]... [-o ] delete [-p ]... [-o ] diff --git a/gen/compute1-cli/mkdocs.yml b/gen/compute1-cli/mkdocs.yml index a9c7ce2310..ef8bcea35d 100644 --- a/gen/compute1-cli/mkdocs.yml +++ b/gen/compute1-cli/mkdocs.yml @@ -1,4 +1,4 @@ -site_name: compute v0.3.2+20150713 +site_name: compute v0.3.2+20151015 site_url: http://byron.github.io/google-apis-rs/google-compute1-cli site_description: Write integrating applications with bcore @@ -68,6 +68,12 @@ pages: - ['http-health-checks_list.md', 'Http Health Checks', 'List'] - ['http-health-checks_patch.md', 'Http Health Checks', 'Patch'] - ['http-health-checks_update.md', 'Http Health Checks', 'Update'] +- ['https-health-checks_delete.md', 'Https Health Checks', 'Delete'] +- ['https-health-checks_get.md', 'Https Health Checks', 'Get'] +- ['https-health-checks_insert.md', 'Https Health Checks', 'Insert'] +- ['https-health-checks_list.md', 'Https Health Checks', 'List'] +- ['https-health-checks_patch.md', 'Https Health Checks', 'Patch'] +- ['https-health-checks_update.md', 'Https Health Checks', 'Update'] - ['images_delete.md', 'Images', 'Delete'] - ['images_deprecate.md', 'Images', 'Deprecate'] - ['images_get.md', 'Images', 'Get'] @@ -140,11 +146,21 @@ pages: - ['snapshots_delete.md', 'Snapshots', 'Delete'] - ['snapshots_get.md', 'Snapshots', 'Get'] - ['snapshots_list.md', 'Snapshots', 'List'] +- ['ssl-certificates_delete.md', 'Ssl Certificates', 'Delete'] +- ['ssl-certificates_get.md', 'Ssl Certificates', 'Get'] +- ['ssl-certificates_insert.md', 'Ssl Certificates', 'Insert'] +- ['ssl-certificates_list.md', 'Ssl Certificates', 'List'] - ['target-http-proxies_delete.md', 'Target Http Proxies', 'Delete'] - ['target-http-proxies_get.md', 'Target Http Proxies', 'Get'] - ['target-http-proxies_insert.md', 'Target Http Proxies', 'Insert'] - ['target-http-proxies_list.md', 'Target Http Proxies', 'List'] - ['target-http-proxies_set-url-map.md', 'Target Http Proxies', 'Set Url Map'] +- ['target-https-proxies_delete.md', 'Target Https Proxies', 'Delete'] +- ['target-https-proxies_get.md', 'Target Https Proxies', 'Get'] +- ['target-https-proxies_insert.md', 'Target Https Proxies', 'Insert'] +- ['target-https-proxies_list.md', 'Target Https Proxies', 'List'] +- ['target-https-proxies_set-ssl-certificates.md', 'Target Https Proxies', 'Set Ssl Certificates'] +- ['target-https-proxies_set-url-map.md', 'Target Https Proxies', 'Set Url Map'] - ['target-instances_aggregated-list.md', 'Target Instances', 'Aggregated List'] - ['target-instances_delete.md', 'Target Instances', 'Delete'] - ['target-instances_get.md', 'Target Instances', 'Get'] diff --git a/gen/compute1-cli/src/main.rs b/gen/compute1-cli/src/main.rs index 7d1beb572b..0635d18403 100644 --- a/gen/compute1-cli/src/main.rs +++ b/gen/compute1-cli/src/main.rs @@ -4176,6 +4176,463 @@ impl<'n, 'a> Engine<'n, 'a> { } } + fn _https_health_checks_delete(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.https_health_checks().delete(opt.value_of("project").unwrap_or(""), opt.value_of("https-health-check").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _https_health_checks_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.https_health_checks().get(opt.value_of("project").unwrap_or(""), opt.value_of("https-health-check").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _https_health_checks_insert(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "description" => Some(("description", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "timeout-sec" => Some(("timeoutSec", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "check-interval-sec" => Some(("checkIntervalSec", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "port" => Some(("port", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "unhealthy-threshold" => Some(("unhealthyThreshold", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "healthy-threshold" => Some(("healthyThreshold", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "host" => Some(("host", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "request-path" => Some(("requestPath", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "creation-timestamp" => Some(("creationTimestamp", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "self-link" => Some(("selfLink", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["check-interval-sec", "creation-timestamp", "description", "healthy-threshold", "host", "id", "kind", "name", "port", "request-path", "self-link", "timeout-sec", "unhealthy-threshold"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::HttpsHealthCheck = json::value::from_value(object).unwrap(); + let mut call = self.hub.https_health_checks().insert(request, opt.value_of("project").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _https_health_checks_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.https_health_checks().list(opt.value_of("project").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "max-results" => { + call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer")); + }, + "filter" => { + call = call.filter(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["filter", "page-token", "max-results"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _https_health_checks_patch(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "description" => Some(("description", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "timeout-sec" => Some(("timeoutSec", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "check-interval-sec" => Some(("checkIntervalSec", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "port" => Some(("port", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "unhealthy-threshold" => Some(("unhealthyThreshold", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "healthy-threshold" => Some(("healthyThreshold", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "host" => Some(("host", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "request-path" => Some(("requestPath", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "creation-timestamp" => Some(("creationTimestamp", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "self-link" => Some(("selfLink", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["check-interval-sec", "creation-timestamp", "description", "healthy-threshold", "host", "id", "kind", "name", "port", "request-path", "self-link", "timeout-sec", "unhealthy-threshold"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::HttpsHealthCheck = json::value::from_value(object).unwrap(); + let mut call = self.hub.https_health_checks().patch(request, opt.value_of("project").unwrap_or(""), opt.value_of("https-health-check").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _https_health_checks_update(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "description" => Some(("description", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "timeout-sec" => Some(("timeoutSec", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "check-interval-sec" => Some(("checkIntervalSec", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "port" => Some(("port", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "unhealthy-threshold" => Some(("unhealthyThreshold", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "healthy-threshold" => Some(("healthyThreshold", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "host" => Some(("host", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "request-path" => Some(("requestPath", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "creation-timestamp" => Some(("creationTimestamp", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "self-link" => Some(("selfLink", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["check-interval-sec", "creation-timestamp", "description", "healthy-threshold", "host", "id", "kind", "name", "port", "request-path", "self-link", "timeout-sec", "unhealthy-threshold"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::HttpsHealthCheck = json::value::from_value(object).unwrap(); + let mut call = self.hub.https_health_checks().update(request, opt.value_of("project").unwrap_or(""), opt.value_of("https-health-check").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + fn _images_delete(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) -> Result<(), DoitError> { let mut call = self.hub.images().delete(opt.value_of("project").unwrap_or(""), opt.value_of("image").unwrap_or("")); @@ -4895,10 +5352,6 @@ impl<'n, 'a> Engine<'n, 'a> { let type_info: Option<(&'static str, JsonTypeInfo)> = match &temp_cursor.to_string()[..] { - "target-size" => Some(("targetSize", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), - "description" => Some(("description", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), - "zone" => Some(("zone", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), - "instance-group" => Some(("instanceGroup", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "current-actions.none" => Some(("currentActions.none", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), "current-actions.recreating" => Some(("currentActions.recreating", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), "current-actions.creating" => Some(("currentActions.creating", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), @@ -4906,6 +5359,10 @@ impl<'n, 'a> Engine<'n, 'a> { "current-actions.abandoning" => Some(("currentActions.abandoning", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), "current-actions.deleting" => Some(("currentActions.deleting", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), "current-actions.refreshing" => Some(("currentActions.refreshing", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "description" => Some(("description", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "zone" => Some(("zone", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "instance-group" => Some(("instanceGroup", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "target-size" => Some(("targetSize", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "target-pools" => Some(("targetPools", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), "base-instance-name" => Some(("baseInstanceName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), @@ -5828,10 +6285,9 @@ impl<'n, 'a> Engine<'n, 'a> { let type_info: Option<(&'static str, JsonTypeInfo)> = match &temp_cursor.to_string()[..] { - "port-name" => Some(("portName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "instance-state" => Some(("instanceState", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), _ => { - let suggestion = FieldCursor::did_you_mean(key, &vec!["instance-state", "port-name"]); + let suggestion = FieldCursor::did_you_mean(key, &vec!["instance-state"]); err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); None } @@ -9066,6 +9522,264 @@ impl<'n, 'a> Engine<'n, 'a> { } } + fn _ssl_certificates_delete(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.ssl_certificates().delete(opt.value_of("project").unwrap_or(""), opt.value_of("ssl-certificate").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _ssl_certificates_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.ssl_certificates().get(opt.value_of("project").unwrap_or(""), opt.value_of("ssl-certificate").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _ssl_certificates_insert(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "certificate" => Some(("certificate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "private-key" => Some(("privateKey", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "creation-timestamp" => Some(("creationTimestamp", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "self-link" => Some(("selfLink", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "description" => Some(("description", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["certificate", "creation-timestamp", "description", "id", "kind", "name", "private-key", "self-link"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::SslCertificate = json::value::from_value(object).unwrap(); + let mut call = self.hub.ssl_certificates().insert(request, opt.value_of("project").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _ssl_certificates_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.ssl_certificates().list(opt.value_of("project").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "max-results" => { + call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer")); + }, + "filter" => { + call = call.filter(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["filter", "page-token", "max-results"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + fn _target_http_proxies_delete(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) -> Result<(), DoitError> { let mut call = self.hub.target_http_proxies().delete(opt.value_of("project").unwrap_or(""), opt.value_of("target-http-proxy").unwrap_or("")); @@ -9408,6 +10122,434 @@ impl<'n, 'a> Engine<'n, 'a> { } } + fn _target_https_proxies_delete(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.target_https_proxies().delete(opt.value_of("project").unwrap_or(""), opt.value_of("target-https-proxy").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _target_https_proxies_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.target_https_proxies().get(opt.value_of("project").unwrap_or(""), opt.value_of("target-https-proxy").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _target_https_proxies_insert(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "description" => Some(("description", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "ssl-certificates" => Some(("sslCertificates", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "url-map" => Some(("urlMap", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "creation-timestamp" => Some(("creationTimestamp", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "self-link" => Some(("selfLink", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["creation-timestamp", "description", "id", "kind", "name", "self-link", "ssl-certificates", "url-map"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::TargetHttpsProxy = json::value::from_value(object).unwrap(); + let mut call = self.hub.target_https_proxies().insert(request, opt.value_of("project").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _target_https_proxies_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.target_https_proxies().list(opt.value_of("project").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "max-results" => { + call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer")); + }, + "filter" => { + call = call.filter(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["filter", "page-token", "max-results"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _target_https_proxies_set_ssl_certificates(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "ssl-certificates" => Some(("sslCertificates", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["ssl-certificates"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::TargetHttpsProxiesSetSslCertificatesRequest = json::value::from_value(object).unwrap(); + let mut call = self.hub.target_https_proxies().set_ssl_certificates(request, opt.value_of("project").unwrap_or(""), opt.value_of("target-https-proxy").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _target_https_proxies_set_url_map(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "url-map" => Some(("urlMap", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["url-map"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::UrlMapReference = json::value::from_value(object).unwrap(); + let mut call = self.hub.target_https_proxies().set_url_map(request, opt.value_of("project").unwrap_or(""), opt.value_of("target-https-proxy").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + fn _target_instances_aggregated_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) -> Result<(), DoitError> { let mut call = self.hub.target_instances().aggregated_list(opt.value_of("project").unwrap_or("")); @@ -11615,7 +12757,6 @@ impl<'n, 'a> Engine<'n, 'a> { "description" => Some(("description", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "peer-ip" => Some(("peerIp", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "region" => Some(("region", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), - "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "status" => Some(("status", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "shared-secret-hash" => Some(("sharedSecretHash", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "target-vpn-gateway" => Some(("targetVpnGateway", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), @@ -11623,9 +12764,9 @@ impl<'n, 'a> Engine<'n, 'a> { "creation-timestamp" => Some(("creationTimestamp", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "self-link" => Some(("selfLink", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), - "ike-networks" => Some(("ikeNetworks", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), _ => { - let suggestion = FieldCursor::did_you_mean(key, &vec!["creation-timestamp", "description", "detailed-status", "id", "ike-networks", "ike-version", "kind", "name", "peer-ip", "region", "self-link", "shared-secret", "shared-secret-hash", "status", "target-vpn-gateway"]); + let suggestion = FieldCursor::did_you_mean(key, &vec!["creation-timestamp", "description", "detailed-status", "id", "ike-version", "kind", "name", "peer-ip", "region", "self-link", "shared-secret", "shared-secret-hash", "status", "target-vpn-gateway"]); err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); None } @@ -12289,6 +13430,32 @@ impl<'n, 'a> Engine<'n, 'a> { } } }, + ("https-health-checks", Some(opt)) => { + match opt.subcommand() { + ("delete", Some(opt)) => { + call_result = self._https_health_checks_delete(opt, dry_run, &mut err); + }, + ("get", Some(opt)) => { + call_result = self._https_health_checks_get(opt, dry_run, &mut err); + }, + ("insert", Some(opt)) => { + call_result = self._https_health_checks_insert(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._https_health_checks_list(opt, dry_run, &mut err); + }, + ("patch", Some(opt)) => { + call_result = self._https_health_checks_patch(opt, dry_run, &mut err); + }, + ("update", Some(opt)) => { + call_result = self._https_health_checks_update(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("https-health-checks".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, ("images", Some(opt)) => { match opt.subcommand() { ("delete", Some(opt)) => { @@ -12609,6 +13776,26 @@ impl<'n, 'a> Engine<'n, 'a> { } } }, + ("ssl-certificates", Some(opt)) => { + match opt.subcommand() { + ("delete", Some(opt)) => { + call_result = self._ssl_certificates_delete(opt, dry_run, &mut err); + }, + ("get", Some(opt)) => { + call_result = self._ssl_certificates_get(opt, dry_run, &mut err); + }, + ("insert", Some(opt)) => { + call_result = self._ssl_certificates_insert(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._ssl_certificates_list(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("ssl-certificates".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, ("target-http-proxies", Some(opt)) => { match opt.subcommand() { ("delete", Some(opt)) => { @@ -12632,6 +13819,32 @@ impl<'n, 'a> Engine<'n, 'a> { } } }, + ("target-https-proxies", Some(opt)) => { + match opt.subcommand() { + ("delete", Some(opt)) => { + call_result = self._target_https_proxies_delete(opt, dry_run, &mut err); + }, + ("get", Some(opt)) => { + call_result = self._target_https_proxies_get(opt, dry_run, &mut err); + }, + ("insert", Some(opt)) => { + call_result = self._target_https_proxies_insert(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._target_https_proxies_list(opt, dry_run, &mut err); + }, + ("set-ssl-certificates", Some(opt)) => { + call_result = self._target_https_proxies_set_ssl_certificates(opt, dry_run, &mut err); + }, + ("set-url-map", Some(opt)) => { + call_result = self._target_https_proxies_set_url_map(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("target-https-proxies".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, ("target-instances", Some(opt)) => { match opt.subcommand() { ("aggregated-list", Some(opt)) => { @@ -14659,6 +15872,183 @@ fn main() { ]), ]), + ("https-health-checks", "methods: 'delete', 'get', 'insert', 'list', 'patch' and 'update'", vec![ + ("delete", + Some(r##"Deletes the specified HttpsHealthCheck resource."##), + "Details at http://byron.github.io/google-apis-rs/google_compute1_cli/https-health-checks_delete", + vec![ + (Some(r##"project"##), + None, + Some(r##"Name of the project scoping this request."##), + Some(true), + Some(false)), + + (Some(r##"https-health-check"##), + None, + Some(r##"Name of the HttpsHealthCheck resource to delete."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("get", + Some(r##"Returns the specified HttpsHealthCheck resource."##), + "Details at http://byron.github.io/google-apis-rs/google_compute1_cli/https-health-checks_get", + vec![ + (Some(r##"project"##), + None, + Some(r##"Name of the project scoping this request."##), + Some(true), + Some(false)), + + (Some(r##"https-health-check"##), + None, + Some(r##"Name of the HttpsHealthCheck resource to return."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("insert", + Some(r##"Creates a HttpsHealthCheck resource in the specified project using the data included in the request."##), + "Details at http://byron.github.io/google-apis-rs/google_compute1_cli/https-health-checks_insert", + vec![ + (Some(r##"project"##), + None, + Some(r##"Name of the project scoping this request."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Retrieves the list of HttpsHealthCheck resources available to the specified project."##), + "Details at http://byron.github.io/google-apis-rs/google_compute1_cli/https-health-checks_list", + vec![ + (Some(r##"project"##), + None, + Some(r##"Name of the project scoping this request."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("patch", + Some(r##"Updates a HttpsHealthCheck resource in the specified project using the data included in the request. This method supports patch semantics."##), + "Details at http://byron.github.io/google-apis-rs/google_compute1_cli/https-health-checks_patch", + vec![ + (Some(r##"project"##), + None, + Some(r##"Name of the project scoping this request."##), + Some(true), + Some(false)), + + (Some(r##"https-health-check"##), + None, + Some(r##"Name of the HttpsHealthCheck resource to update."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("update", + Some(r##"Updates a HttpsHealthCheck resource in the specified project using the data included in the request."##), + "Details at http://byron.github.io/google-apis-rs/google_compute1_cli/https-health-checks_update", + vec![ + (Some(r##"project"##), + None, + Some(r##"Name of the project scoping this request."##), + Some(true), + Some(false)), + + (Some(r##"https-health-check"##), + None, + Some(r##"Name of the HttpsHealthCheck resource to update."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + ("images", "methods: 'delete', 'deprecate', 'get', 'insert' and 'list'", vec![ ("delete", Some(r##"Deletes the specified image resource."##), @@ -14781,7 +16171,9 @@ fn main() { Some(false)), ]), ("list", - Some(r##"Retrieves the list of image resources available to the specified project."##), + Some(r##"Retrieves the list of private images available to the specified project. Private images are images you create that belong to your project. This method does not get any images that belong to other projects, including publicly-available images, like Debian 7. If you want to get a list of publicly-available images, use this method to make a request to the respective image project, such as debian-cloud or windows-cloud. + + See Accessing images for more information."##), "Details at http://byron.github.io/google-apis-rs/google_compute1_cli/images_list", vec![ (Some(r##"project"##), @@ -14806,7 +16198,7 @@ fn main() { ("instance-group-managers", "methods: 'abandon-instances', 'aggregated-list', 'delete', 'delete-instances', 'get', 'insert', 'list', 'list-managed-instances', 'recreate-instances', 'resize', 'set-instance-template' and 'set-target-pools'", vec![ ("abandon-instances", - Some(r##"Removes the specified instances from the managed instance group, and from any target pools where they are a member. The instances are not deleted. The managed instance group automatically reduces its targetSize value by the number of instances that you abandon from the group."##), + Some(r##"Schedules a group action to remove the specified instances from the managed instance group. Abandoning an instance does not delete the instance, but it does remove the instance from any target pools that are applied by the managed instance group. This method reduces the targetSize of the managed instance group by the number of instances that you abandon. This operation is marked as DONE when the action is scheduled even if the instances have not yet been removed from the group. You must separately verify the status of the abandoning action with the listmanagedinstances method."##), "Details at http://byron.github.io/google-apis-rs/google_compute1_cli/instance-group-managers_abandon-instances", vec![ (Some(r##"project"##), @@ -14817,13 +16209,13 @@ fn main() { (Some(r##"zone"##), None, - Some(r##"The URL of the zone where the managed instance group is located."##), + Some(r##"The name of the zone where the managed instance group is located."##), Some(true), Some(false)), (Some(r##"instance-group-manager"##), None, - Some(r##"The name of the instance group manager."##), + Some(r##"The name of the managed instance group."##), Some(true), Some(false)), @@ -14846,7 +16238,7 @@ fn main() { Some(false)), ]), ("aggregated-list", - Some(r##"Retrieves the list of managed instance groups, and groups them by project and zone."##), + Some(r##"Retrieves the list of managed instance groups and groups them by zone."##), "Details at http://byron.github.io/google-apis-rs/google_compute1_cli/instance-group-managers_aggregated-list", vec![ (Some(r##"project"##), @@ -14868,7 +16260,7 @@ fn main() { Some(false)), ]), ("delete", - Some(r##"Deletes the specified managed instance group resource."##), + Some(r##"Deletes the specified managed instance group and all of the instances in that group."##), "Details at http://byron.github.io/google-apis-rs/google_compute1_cli/instance-group-managers_delete", vec![ (Some(r##"project"##), @@ -14879,13 +16271,13 @@ fn main() { (Some(r##"zone"##), None, - Some(r##"The URL of the zone where the managed instance group is located."##), + Some(r##"The name of the zone where the managed instance group is located."##), Some(true), Some(false)), (Some(r##"instance-group-manager"##), None, - Some(r##"The name of the instance group manager to delete."##), + Some(r##"The name of the managed instance group to delete."##), Some(true), Some(false)), @@ -14902,7 +16294,7 @@ fn main() { Some(false)), ]), ("delete-instances", - Some(r##"Deletes the specified instances. The instances are deleted and removed from the instance group and any target pools where they are a member. The managed instance group automatically reduces its targetSize value by the number of instances that you delete."##), + Some(r##"Schedules a group action to delete the specified instances in the managed instance group. The instances are also removed from any target pools of which they were a member. This method reduces the targetSize of the managed instance group by the number of instances that you delete. This operation is marked as DONE when the action is scheduled even if the instances are still being deleted. You must separately verify the status of the deleting action with the listmanagedinstances method."##), "Details at http://byron.github.io/google-apis-rs/google_compute1_cli/instance-group-managers_delete-instances", vec![ (Some(r##"project"##), @@ -14913,13 +16305,13 @@ fn main() { (Some(r##"zone"##), None, - Some(r##"The URL of the zone where the managed instance group is located."##), + Some(r##"The name of the zone where the managed instance group is located."##), Some(true), Some(false)), (Some(r##"instance-group-manager"##), None, - Some(r##"The name of the instance group manager."##), + Some(r##"The name of the managed instance group."##), Some(true), Some(false)), @@ -14942,7 +16334,7 @@ fn main() { Some(false)), ]), ("get", - Some(r##"Returns the specified managed instance group resource."##), + Some(r##"Returns all of the details about the specified managed instance group."##), "Details at http://byron.github.io/google-apis-rs/google_compute1_cli/instance-group-managers_get", vec![ (Some(r##"project"##), @@ -14953,13 +16345,13 @@ fn main() { (Some(r##"zone"##), None, - Some(r##"The URL of the zone where the managed instance group is located."##), + Some(r##"The name of the zone where the managed instance group is located."##), Some(true), Some(false)), (Some(r##"instance-group-manager"##), None, - Some(r##"The name of the instance group manager resource."##), + Some(r##"The name of the managed instance group."##), Some(true), Some(false)), @@ -14976,7 +16368,7 @@ fn main() { Some(false)), ]), ("insert", - Some(r##"Creates a managed instance group resource in the specified project using the data that is included in the request."##), + Some(r##"Creates a managed instance group using the information that you specify in the request. After the group is created, it schedules an action to create instances in the group using the specified instance template. This operation is marked as DONE when the group is created even if the instances in the group have not yet been created. You must separately verify the status of the individual instances with the listmanagedinstances method."##), "Details at http://byron.github.io/google-apis-rs/google_compute1_cli/instance-group-managers_insert", vec![ (Some(r##"project"##), @@ -14987,7 +16379,7 @@ fn main() { (Some(r##"zone"##), None, - Some(r##"The URL of the zone where the managed instance group is located."##), + Some(r##"The name of the zone where you want to create the managed instance group."##), Some(true), Some(false)), @@ -15021,7 +16413,7 @@ fn main() { (Some(r##"zone"##), None, - Some(r##"The URL of the zone where the managed instance group is located."##), + Some(r##"The name of the zone where the managed instance group is located."##), Some(true), Some(false)), @@ -15038,7 +16430,7 @@ fn main() { Some(false)), ]), ("list-managed-instances", - Some(r##"Lists managed instances."##), + Some(r##"Lists all of the instances in the managed instance group. Each instance in the list has a currentAction, which indicates the action that the managed instance group is performing on the instance. For example, if the group is still creating an instance, the currentAction is CREATING. If a previous action failed, the list displays the errors for that failed action."##), "Details at http://byron.github.io/google-apis-rs/google_compute1_cli/instance-group-managers_list-managed-instances", vec![ (Some(r##"project"##), @@ -15049,7 +16441,7 @@ fn main() { (Some(r##"zone"##), None, - Some(r##"The URL of the zone where the managed instance group is located."##), + Some(r##"The name of the zone where the managed instance group is located."##), Some(true), Some(false)), @@ -15072,7 +16464,7 @@ fn main() { Some(false)), ]), ("recreate-instances", - Some(r##"Recreates the specified instances. The instances are deleted, then recreated using the managed instance group's current instance template."##), + Some(r##"Schedules a group action to recreate the specified instances in the managed instance group. The instances are deleted and recreated using the current instance template for the managed instance group. This operation is marked as DONE when the action is scheduled even if the instances have not yet been recreated. You must separately verify the status of the recreating action with the listmanagedinstances method."##), "Details at http://byron.github.io/google-apis-rs/google_compute1_cli/instance-group-managers_recreate-instances", vec![ (Some(r##"project"##), @@ -15083,13 +16475,13 @@ fn main() { (Some(r##"zone"##), None, - Some(r##"The URL of the zone where the managed instance group is located."##), + Some(r##"The name of the zone where the managed instance group is located."##), Some(true), Some(false)), (Some(r##"instance-group-manager"##), None, - Some(r##"The name of the instance group manager."##), + Some(r##"The name of the managed instance group."##), Some(true), Some(false)), @@ -15112,7 +16504,7 @@ fn main() { Some(false)), ]), ("resize", - Some(r##"Resizes the managed instance group. If you increase the size, the group creates new instances using the current instance template. If you decrease the size, the group removes instances in the order that is outlined in Resizing a managed instance group."##), + Some(r##"Resizes the managed instance group. If you increase the size, the group creates new instances using the current instance template. If you decrease the size, the group deletes instances. The resize operation is marked DONE when the resize actions are scheduled even if the group has not yet added or deleted any instances. You must separately verify the status of the creating or deleting actions with the listmanagedinstances method."##), "Details at http://byron.github.io/google-apis-rs/google_compute1_cli/instance-group-managers_resize", vec![ (Some(r##"project"##), @@ -15123,13 +16515,13 @@ fn main() { (Some(r##"zone"##), None, - Some(r##"The URL of the zone where the managed instance group is located."##), + Some(r##"The name of the zone where the managed instance group is located."##), Some(true), Some(false)), (Some(r##"instance-group-manager"##), None, - Some(r##"The name of the instance group manager."##), + Some(r##"The name of the managed instance group."##), Some(true), Some(false)), @@ -15163,13 +16555,13 @@ fn main() { (Some(r##"zone"##), None, - Some(r##"The URL of the zone where the managed instance group is located."##), + Some(r##"The name of the zone where the managed instance group is located."##), Some(true), Some(false)), (Some(r##"instance-group-manager"##), None, - Some(r##"The name of the instance group manager."##), + Some(r##"The name of the managed instance group."##), Some(true), Some(false)), @@ -15192,7 +16584,7 @@ fn main() { Some(false)), ]), ("set-target-pools", - Some(r##"Modifies the target pools to which all new instances in this group are assigned. The target pools for existing instances in the group do not change unless you recreate them."##), + Some(r##"Modifies the target pools to which all instances in this managed instance group are assigned. The target pools automatically apply to all of the instances in the managed instance group. This operation is marked DONE when you make the request even if the instances have not yet been added to their target pools. The change might take some time to apply to all of the instances in the group depending on the size of the group."##), "Details at http://byron.github.io/google-apis-rs/google_compute1_cli/instance-group-managers_set-target-pools", vec![ (Some(r##"project"##), @@ -15203,13 +16595,13 @@ fn main() { (Some(r##"zone"##), None, - Some(r##"The URL of the zone where the managed instance group is located."##), + Some(r##"The name of the zone where the managed instance group is located."##), Some(true), Some(false)), (Some(r##"instance-group-manager"##), None, - Some(r##"The name of the instance group manager."##), + Some(r##"The name of the managed instance group."##), Some(true), Some(false)), @@ -15235,7 +16627,7 @@ fn main() { ("instance-groups", "methods: 'add-instances', 'aggregated-list', 'delete', 'get', 'insert', 'list', 'list-instances', 'remove-instances' and 'set-named-ports'", vec![ ("add-instances", - Some(r##"Adds a list of instances to an instance group. All of the instances in the instance group must be in the same network."##), + Some(r##"Adds a list of instances to the specified instance group. All of the instances in the instance group must be in the same network/subnetwork. TODO: Change to comment to state "if IG is load balanced.""##), "Details at http://byron.github.io/google-apis-rs/google_compute1_cli/instance-groups_add-instances", vec![ (Some(r##"project"##), @@ -15246,7 +16638,7 @@ fn main() { (Some(r##"zone"##), None, - Some(r##"The URL of the zone where the instance group is located."##), + Some(r##"The name of the zone where the instance group is located."##), Some(true), Some(false)), @@ -15275,7 +16667,7 @@ fn main() { Some(false)), ]), ("aggregated-list", - Some(r##"Retrieves the list of instance groups, and sorts them by zone."##), + Some(r##"Retrieves the list of instance groups and sorts them by zone."##), "Details at http://byron.github.io/google-apis-rs/google_compute1_cli/instance-groups_aggregated-list", vec![ (Some(r##"project"##), @@ -15297,7 +16689,7 @@ fn main() { Some(false)), ]), ("delete", - Some(r##"Deletes the specified instance group."##), + Some(r##"Deletes the specified instance group. The instances in the group are not deleted."##), "Details at http://byron.github.io/google-apis-rs/google_compute1_cli/instance-groups_delete", vec![ (Some(r##"project"##), @@ -15308,7 +16700,7 @@ fn main() { (Some(r##"zone"##), None, - Some(r##"The URL of the zone where the instance group is located."##), + Some(r##"The name of the zone where the instance group is located."##), Some(true), Some(false)), @@ -15342,7 +16734,7 @@ fn main() { (Some(r##"zone"##), None, - Some(r##"The URL of the zone where the instance group is located."##), + Some(r##"The name of the zone where the instance group is located."##), Some(true), Some(false)), @@ -15376,7 +16768,7 @@ fn main() { (Some(r##"zone"##), None, - Some(r##"The URL of the zone where the instance group is located."##), + Some(r##"The name of the zone where you want to create the instance group."##), Some(true), Some(false)), @@ -15410,7 +16802,7 @@ fn main() { (Some(r##"zone"##), None, - Some(r##"The URL of the zone where the instance group is located."##), + Some(r##"The name of the zone where the instance group is located."##), Some(true), Some(false)), @@ -15427,7 +16819,7 @@ fn main() { Some(false)), ]), ("list-instances", - Some(r##"Lists instances in an instance group. The parameters for this method specify whether the list filters instances by state and named ports information."##), + Some(r##"Lists the instances in the specified instance group."##), "Details at http://byron.github.io/google-apis-rs/google_compute1_cli/instance-groups_list-instances", vec![ (Some(r##"project"##), @@ -15438,7 +16830,7 @@ fn main() { (Some(r##"zone"##), None, - Some(r##"The URL of the zone where the instance group is located."##), + Some(r##"The name of the zone where the instance group is located."##), Some(true), Some(false)), @@ -15467,7 +16859,7 @@ fn main() { Some(false)), ]), ("remove-instances", - Some(r##"Removes a list of instances from an instance group."##), + Some(r##"Removes one or more instances from the specified instance group, but does not delete those instances."##), "Details at http://byron.github.io/google-apis-rs/google_compute1_cli/instance-groups_remove-instances", vec![ (Some(r##"project"##), @@ -15478,7 +16870,7 @@ fn main() { (Some(r##"zone"##), None, - Some(r##"The URL of the zone where the instance group is located."##), + Some(r##"The name of the zone where the instance group is located."##), Some(true), Some(false)), @@ -15507,7 +16899,7 @@ fn main() { Some(false)), ]), ("set-named-ports", - Some(r##"Sets the named ports in an instance group."##), + Some(r##"Sets the named ports for the specified instance group."##), "Details at http://byron.github.io/google-apis-rs/google_compute1_cli/instance-groups_set-named-ports", vec![ (Some(r##"project"##), @@ -15518,7 +16910,7 @@ fn main() { (Some(r##"zone"##), None, - Some(r##"The URL of the zone where the instance group is located."##), + Some(r##"The name of the zone where the instance group is located."##), Some(true), Some(false)), @@ -15705,7 +17097,7 @@ fn main() { Some(false)), ]), ("aggregated-list", - None, + Some(r##"Retrieves aggregated list of instance resources."##), "Details at http://byron.github.io/google-apis-rs/google_compute1_cli/instances_aggregated-list", vec![ (Some(r##"project"##), @@ -15898,7 +17290,7 @@ fn main() { (Some(r##"zone"##), None, - Some(r##"The name of the The name of the zone for this request.."##), + Some(r##"The name of the zone for this request."##), Some(true), Some(false)), @@ -16988,6 +18380,115 @@ fn main() { ]), ]), + ("ssl-certificates", "methods: 'delete', 'get', 'insert' and 'list'", vec![ + ("delete", + Some(r##"Deletes the specified SslCertificate resource."##), + "Details at http://byron.github.io/google-apis-rs/google_compute1_cli/ssl-certificates_delete", + vec![ + (Some(r##"project"##), + None, + Some(r##"Name of the project scoping this request."##), + Some(true), + Some(false)), + + (Some(r##"ssl-certificate"##), + None, + Some(r##"Name of the SslCertificate resource to delete."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("get", + Some(r##"Returns the specified SslCertificate resource."##), + "Details at http://byron.github.io/google-apis-rs/google_compute1_cli/ssl-certificates_get", + vec![ + (Some(r##"project"##), + None, + Some(r##"Name of the project scoping this request."##), + Some(true), + Some(false)), + + (Some(r##"ssl-certificate"##), + None, + Some(r##"Name of the SslCertificate resource to return."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("insert", + Some(r##"Creates a SslCertificate resource in the specified project using the data included in the request."##), + "Details at http://byron.github.io/google-apis-rs/google_compute1_cli/ssl-certificates_insert", + vec![ + (Some(r##"project"##), + None, + Some(r##"Name of the project scoping this request."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Retrieves the list of SslCertificate resources available to the specified project."##), + "Details at http://byron.github.io/google-apis-rs/google_compute1_cli/ssl-certificates_list", + vec![ + (Some(r##"project"##), + None, + Some(r##"Name of the project scoping this request."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + ("target-http-proxies", "methods: 'delete', 'get', 'insert', 'list' and 'set-url-map'", vec![ ("delete", Some(r##"Deletes the specified TargetHttpProxy resource."##), @@ -17131,6 +18632,183 @@ fn main() { ]), ]), + ("target-https-proxies", "methods: 'delete', 'get', 'insert', 'list', 'set-ssl-certificates' and 'set-url-map'", vec![ + ("delete", + Some(r##"Deletes the specified TargetHttpsProxy resource."##), + "Details at http://byron.github.io/google-apis-rs/google_compute1_cli/target-https-proxies_delete", + vec![ + (Some(r##"project"##), + None, + Some(r##"Name of the project scoping this request."##), + Some(true), + Some(false)), + + (Some(r##"target-https-proxy"##), + None, + Some(r##"Name of the TargetHttpsProxy resource to delete."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("get", + Some(r##"Returns the specified TargetHttpsProxy resource."##), + "Details at http://byron.github.io/google-apis-rs/google_compute1_cli/target-https-proxies_get", + vec![ + (Some(r##"project"##), + None, + Some(r##"Name of the project scoping this request."##), + Some(true), + Some(false)), + + (Some(r##"target-https-proxy"##), + None, + Some(r##"Name of the TargetHttpsProxy resource to return."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("insert", + Some(r##"Creates a TargetHttpsProxy resource in the specified project using the data included in the request."##), + "Details at http://byron.github.io/google-apis-rs/google_compute1_cli/target-https-proxies_insert", + vec![ + (Some(r##"project"##), + None, + Some(r##"Name of the project scoping this request."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Retrieves the list of TargetHttpsProxy resources available to the specified project."##), + "Details at http://byron.github.io/google-apis-rs/google_compute1_cli/target-https-proxies_list", + vec![ + (Some(r##"project"##), + None, + Some(r##"Name of the project scoping this request."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("set-ssl-certificates", + Some(r##"Replaces SslCertificates for TargetHttpsProxy."##), + "Details at http://byron.github.io/google-apis-rs/google_compute1_cli/target-https-proxies_set-ssl-certificates", + vec![ + (Some(r##"project"##), + None, + Some(r##"Name of the project scoping this request."##), + Some(true), + Some(false)), + + (Some(r##"target-https-proxy"##), + None, + Some(r##"Name of the TargetHttpsProxy resource whose URL map is to be set."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("set-url-map", + Some(r##"Changes the URL map for TargetHttpsProxy."##), + "Details at http://byron.github.io/google-apis-rs/google_compute1_cli/target-https-proxies_set-url-map", + vec![ + (Some(r##"project"##), + None, + Some(r##"Name of the project scoping this request."##), + Some(true), + Some(false)), + + (Some(r##"target-https-proxy"##), + None, + Some(r##"Name of the TargetHttpsProxy resource whose URL map is to be set."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + ("target-instances", "methods: 'aggregated-list', 'delete', 'get', 'insert' and 'list'", vec![ ("aggregated-list", Some(r##"Retrieves the list of target instances grouped by scope."##), @@ -18352,7 +20030,7 @@ fn main() { let mut app = App::new("compute1") .author("Sebastian Thiel ") - .version("0.3.2+20150713") + .version("0.3.2+20151015") .about("API for the Google Compute Engine service.") .after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_compute1_cli") .arg(Arg::with_name("url") diff --git a/gen/compute1/Cargo.toml b/gen/compute1/Cargo.toml index 04b0e4f03f..6a5f4df2bf 100644 --- a/gen/compute1/Cargo.toml +++ b/gen/compute1/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-compute1" -version = "0.1.9+20150713" +version = "0.1.9+20151015" 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" diff --git a/gen/compute1/README.md b/gen/compute1/README.md index c20f451ecc..484edf0f0e 100644 --- a/gen/compute1/README.md +++ b/gen/compute1/README.md @@ -5,7 +5,7 @@ DO NOT EDIT ! --> The `google-compute1` library allows access to all features of the *Google compute* service. -This documentation was generated from *compute* crate version *0.1.9+20150713*, where *20150713* is the exact revision of the *compute:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +This documentation was generated from *compute* crate version *0.1.9+20151015*, where *20151015* is the exact revision of the *compute:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. Everything else about the *compute* *v1* API can be found at the [official documentation site](https://developers.google.com/compute/docs/reference/latest/). @@ -35,6 +35,8 @@ Handle the following *Resources* with ease from the central [hub](http://byron.g * [*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) +* [https health checks](http://byron.github.io/google-apis-rs/google_compute1/struct.HttpsHealthCheck.html) + * [*delete*](http://byron.github.io/google-apis-rs/google_compute1/struct.HttpsHealthCheckDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google_compute1/struct.HttpsHealthCheckGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google_compute1/struct.HttpsHealthCheckInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google_compute1/struct.HttpsHealthCheckListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google_compute1/struct.HttpsHealthCheckPatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google_compute1/struct.HttpsHealthCheckUpdateCall.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 group managers](http://byron.github.io/google-apis-rs/google_compute1/struct.InstanceGroupManager.html) @@ -61,8 +63,12 @@ Handle the following *Resources* with ease from the central [hub](http://byron.g * [*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) +* [ssl certificates](http://byron.github.io/google-apis-rs/google_compute1/struct.SslCertificate.html) + * [*delete*](http://byron.github.io/google-apis-rs/google_compute1/struct.SslCertificateDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google_compute1/struct.SslCertificateGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google_compute1/struct.SslCertificateInsertCall.html) and [*list*](http://byron.github.io/google-apis-rs/google_compute1/struct.SslCertificateListCall.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 https proxies](http://byron.github.io/google-apis-rs/google_compute1/struct.TargetHttpsProxy.html) + * [*delete*](http://byron.github.io/google-apis-rs/google_compute1/struct.TargetHttpsProxyDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google_compute1/struct.TargetHttpsProxyGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google_compute1/struct.TargetHttpsProxyInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google_compute1/struct.TargetHttpsProxyListCall.html), [*set ssl certificates*](http://byron.github.io/google-apis-rs/google_compute1/struct.TargetHttpsProxySetSslCertificateCall.html) and [*set url map*](http://byron.github.io/google-apis-rs/google_compute1/struct.TargetHttpsProxySetUrlMapCall.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) @@ -110,9 +116,12 @@ Or specifically ... ```ignore let r = hub.instance_group_managers().resize(...).doit() +let r = hub.ssl_certificates().delete(...).doit() let r = hub.autoscalers().patch(...).doit() +let r = hub.target_https_proxies().delete(...).doit() let r = hub.firewalls().patch(...).doit() let r = hub.vpn_tunnels().delete(...).doit() +let r = hub.global_forwarding_rules().set_target(...).doit() let r = hub.instances().insert(...).doit() let r = hub.global_forwarding_rules().delete(...).doit() let r = hub.vpn_tunnels().insert(...).doit() @@ -124,7 +133,7 @@ let r = hub.instances().delete(...).doit() let r = hub.target_pools().add_health_check(...).doit() let r = hub.instance_group_managers().insert(...).doit() let r = hub.global_addresses().insert(...).doit() -let r = hub.global_forwarding_rules().set_target(...).doit() +let r = hub.https_health_checks().delete(...).doit() let r = hub.autoscalers().insert(...).doit() let r = hub.instance_groups().insert(...).doit() let r = hub.instance_group_managers().delete_instances(...).doit() @@ -133,7 +142,9 @@ let r = hub.target_pools().insert(...).doit() let r = hub.instances().set_disk_auto_delete(...).doit() let r = hub.instance_group_managers().set_target_pools(...).doit() let r = hub.disks().insert(...).doit() +let r = hub.https_health_checks().insert(...).doit() let r = hub.target_pools().remove_health_check(...).doit() +let r = hub.target_https_proxies().set_url_map(...).doit() let r = hub.backend_services().delete(...).doit() let r = hub.url_maps().insert(...).doit() let r = hub.instances().add_access_config(...).doit() @@ -156,10 +167,12 @@ let r = hub.target_pools().set_backup(...).doit() let r = hub.routes().insert(...).doit() let r = hub.instance_groups().delete(...).doit() let r = hub.instances().delete_access_config(...).doit() +let r = hub.target_https_proxies().set_ssl_certificates(...).doit() let r = hub.networks().insert(...).doit() let r = hub.instance_group_managers().abandon_instances(...).doit() let r = hub.instances().set_tags(...).doit() let r = hub.snapshots().delete(...).doit() +let r = hub.target_https_proxies().insert(...).doit() let r = hub.instances().detach_disk(...).doit() let r = hub.backend_services().update(...).doit() let r = hub.instance_group_managers().recreate_instances(...).doit() @@ -172,8 +185,10 @@ let r = hub.images().deprecate(...).doit() let r = hub.http_health_checks().patch(...).doit() let r = hub.images().insert(...).doit() let r = hub.instance_groups().set_named_ports(...).doit() +let r = hub.ssl_certificates().insert(...).doit() let r = hub.projects().move_instance(...).doit() let r = hub.autoscalers().delete(...).doit() +let r = hub.https_health_checks().update(...).doit() let r = hub.url_maps().patch(...).doit() let r = hub.instances().stop(...).doit() let r = hub.target_pools().add_instance(...).doit() @@ -183,12 +198,13 @@ let r = hub.firewalls().update(...).doit() let r = hub.instance_templates().delete(...).doit() let r = hub.projects().set_usage_export_bucket(...).doit() let r = hub.target_http_proxies().insert(...).doit() -let r = hub.networks().delete(...).doit() +let r = hub.url_maps().update(...).doit() let r = hub.instance_templates().insert(...).doit() let r = hub.target_instances().delete(...).doit() let r = hub.target_vpn_gateways().delete(...).doit() let r = hub.global_addresses().delete(...).doit() -let r = hub.url_maps().update(...).doit() +let r = hub.https_health_checks().patch(...).doit() +let r = hub.networks().delete(...).doit() let r = hub.url_maps().delete(...).doit() let r = hub.instances().reset(...).doit() let r = hub.backend_services().insert(...).doit() diff --git a/gen/compute1/src/lib.rs b/gen/compute1/src/lib.rs index ebba35e9f7..85561d3b1e 100644 --- a/gen/compute1/src/lib.rs +++ b/gen/compute1/src/lib.rs @@ -2,7 +2,7 @@ // This file was generated automatically from 'src/mako/api/lib.rs.mako' // DO NOT EDIT ! -//! This documentation was generated from *compute* crate version *0.1.9+20150713*, where *20150713* is the exact revision of the *compute:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +//! This documentation was generated from *compute* crate version *0.1.9+20151015*, where *20151015* is the exact revision of the *compute:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. //! //! Everything else about the *compute* *v1* API can be found at the //! [official documentation site](https://developers.google.com/compute/docs/reference/latest/). @@ -33,6 +33,8 @@ //! * [*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) +//! * [https health checks](struct.HttpsHealthCheck.html) +//! * [*delete*](struct.HttpsHealthCheckDeleteCall.html), [*get*](struct.HttpsHealthCheckGetCall.html), [*insert*](struct.HttpsHealthCheckInsertCall.html), [*list*](struct.HttpsHealthCheckListCall.html), [*patch*](struct.HttpsHealthCheckPatchCall.html) and [*update*](struct.HttpsHealthCheckUpdateCall.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 group managers](struct.InstanceGroupManager.html) @@ -59,8 +61,12 @@ //! * [*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) +//! * [ssl certificates](struct.SslCertificate.html) +//! * [*delete*](struct.SslCertificateDeleteCall.html), [*get*](struct.SslCertificateGetCall.html), [*insert*](struct.SslCertificateInsertCall.html) and [*list*](struct.SslCertificateListCall.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 https proxies](struct.TargetHttpsProxy.html) +//! * [*delete*](struct.TargetHttpsProxyDeleteCall.html), [*get*](struct.TargetHttpsProxyGetCall.html), [*insert*](struct.TargetHttpsProxyInsertCall.html), [*list*](struct.TargetHttpsProxyListCall.html), [*set ssl certificates*](struct.TargetHttpsProxySetSslCertificateCall.html) and [*set url map*](struct.TargetHttpsProxySetUrlMapCall.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) @@ -110,9 +116,12 @@ //! //! ```ignore //! let r = hub.instance_group_managers().resize(...).doit() +//! let r = hub.ssl_certificates().delete(...).doit() //! let r = hub.autoscalers().patch(...).doit() +//! let r = hub.target_https_proxies().delete(...).doit() //! let r = hub.firewalls().patch(...).doit() //! let r = hub.vpn_tunnels().delete(...).doit() +//! let r = hub.global_forwarding_rules().set_target(...).doit() //! let r = hub.instances().insert(...).doit() //! let r = hub.global_forwarding_rules().delete(...).doit() //! let r = hub.vpn_tunnels().insert(...).doit() @@ -124,7 +133,7 @@ //! let r = hub.target_pools().add_health_check(...).doit() //! let r = hub.instance_group_managers().insert(...).doit() //! let r = hub.global_addresses().insert(...).doit() -//! let r = hub.global_forwarding_rules().set_target(...).doit() +//! let r = hub.https_health_checks().delete(...).doit() //! let r = hub.autoscalers().insert(...).doit() //! let r = hub.instance_groups().insert(...).doit() //! let r = hub.instance_group_managers().delete_instances(...).doit() @@ -133,7 +142,9 @@ //! let r = hub.instances().set_disk_auto_delete(...).doit() //! let r = hub.instance_group_managers().set_target_pools(...).doit() //! let r = hub.disks().insert(...).doit() +//! let r = hub.https_health_checks().insert(...).doit() //! let r = hub.target_pools().remove_health_check(...).doit() +//! let r = hub.target_https_proxies().set_url_map(...).doit() //! let r = hub.backend_services().delete(...).doit() //! let r = hub.url_maps().insert(...).doit() //! let r = hub.instances().add_access_config(...).doit() @@ -156,10 +167,12 @@ //! let r = hub.routes().insert(...).doit() //! let r = hub.instance_groups().delete(...).doit() //! let r = hub.instances().delete_access_config(...).doit() +//! let r = hub.target_https_proxies().set_ssl_certificates(...).doit() //! let r = hub.networks().insert(...).doit() //! let r = hub.instance_group_managers().abandon_instances(...).doit() //! let r = hub.instances().set_tags(...).doit() //! let r = hub.snapshots().delete(...).doit() +//! let r = hub.target_https_proxies().insert(...).doit() //! let r = hub.instances().detach_disk(...).doit() //! let r = hub.backend_services().update(...).doit() //! let r = hub.instance_group_managers().recreate_instances(...).doit() @@ -172,8 +185,10 @@ //! let r = hub.http_health_checks().patch(...).doit() //! let r = hub.images().insert(...).doit() //! let r = hub.instance_groups().set_named_ports(...).doit() +//! let r = hub.ssl_certificates().insert(...).doit() //! let r = hub.projects().move_instance(...).doit() //! let r = hub.autoscalers().delete(...).doit() +//! let r = hub.https_health_checks().update(...).doit() //! let r = hub.url_maps().patch(...).doit() //! let r = hub.instances().stop(...).doit() //! let r = hub.target_pools().add_instance(...).doit() @@ -183,12 +198,13 @@ //! let r = hub.instance_templates().delete(...).doit() //! let r = hub.projects().set_usage_export_bucket(...).doit() //! let r = hub.target_http_proxies().insert(...).doit() -//! let r = hub.networks().delete(...).doit() +//! let r = hub.url_maps().update(...).doit() //! let r = hub.instance_templates().insert(...).doit() //! let r = hub.target_instances().delete(...).doit() //! let r = hub.target_vpn_gateways().delete(...).doit() //! let r = hub.global_addresses().delete(...).doit() -//! let r = hub.url_maps().update(...).doit() +//! let r = hub.https_health_checks().patch(...).doit() +//! let r = hub.networks().delete(...).doit() //! let r = hub.url_maps().delete(...).doit() //! let r = hub.instances().reset(...).doit() //! let r = hub.backend_services().insert(...).doit() diff --git a/gen/compute1/src/lib.rs.in b/gen/compute1/src/lib.rs.in index c556c86afd..9b6732e805 100644 --- a/gen/compute1/src/lib.rs.in +++ b/gen/compute1/src/lib.rs.in @@ -183,6 +183,9 @@ impl<'a, C, A> Compute pub fn http_health_checks(&'a self) -> HttpHealthCheckMethods<'a, C, A> { HttpHealthCheckMethods { hub: &self } } + pub fn https_health_checks(&'a self) -> HttpsHealthCheckMethods<'a, C, A> { + HttpsHealthCheckMethods { hub: &self } + } pub fn images(&'a self) -> ImageMethods<'a, C, A> { ImageMethods { hub: &self } } @@ -222,9 +225,15 @@ impl<'a, C, A> Compute pub fn snapshots(&'a self) -> SnapshotMethods<'a, C, A> { SnapshotMethods { hub: &self } } + pub fn ssl_certificates(&'a self) -> SslCertificateMethods<'a, C, A> { + SslCertificateMethods { hub: &self } + } pub fn target_http_proxies(&'a self) -> TargetHttpProxyMethods<'a, C, A> { TargetHttpProxyMethods { hub: &self } } + pub fn target_https_proxies(&'a self) -> TargetHttpsProxyMethods<'a, C, A> { + TargetHttpsProxyMethods { hub: &self } + } pub fn target_instances(&'a self) -> TargetInstanceMethods<'a, C, A> { TargetInstanceMethods { hub: &self } } @@ -305,7 +314,7 @@ impl Part for ForwardingRulesScopedListWarningData {} /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct InstanceGroupsSetNamedPortsRequest { - /// The fingerprint of the named ports information, which is a hash of the contents. Use this field for optimistic locking when you update the named ports entries. + /// The fingerprint of the named ports information for this instance group. Use this optional property to prevent conflicts when multiple users change the named ports settings concurrently. Obtain the fingerprint with the instanceGroups.get method. Then, include the fingerprint in your request to ensure that you do not overwrite changes that were applied from another concurrent request. pub fingerprint: Option, /// The list of named ports to set for this instance group. #[serde(rename="namedPorts")] @@ -335,7 +344,7 @@ pub struct UrlMapList { pub kind: Option, /// [Output Only] Unique identifier for the resource. Set by the server. pub id: Option, - /// [Output Only] Server defined URL for this resource. + /// [Output Only] Server-defined URL for this resource. #[serde(rename="selfLink")] pub self_link: Option, } @@ -386,7 +395,7 @@ pub struct DiskType { pub valid_disk_size: Option, /// [Output Only] The deprecation status associated with this disk type. pub deprecated: Option, - /// [Output Only] Server defined default disk size in GB. + /// [Output Only] Server-defined default disk size in GB. #[serde(rename="defaultDiskSizeGb")] pub default_disk_size_gb: Option, /// [Output Only] Creation timestamp in RFC3339 text format. @@ -394,7 +403,7 @@ pub struct DiskType { 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. + /// [Output Only] Server-defined URL for the resource. #[serde(rename="selfLink")] pub self_link: Option, /// [Output Only] Name of the resource. @@ -441,7 +450,7 @@ pub struct VpnTunnelAggregatedList { pub kind: Option, /// [Output Only] Unique identifier for the resource; defined by the server. pub id: Option, - /// [Output Only] Server defined URL for this resource. + /// [Output Only] Server-defined URL for this resource. #[serde(rename="selfLink")] pub self_link: Option, } @@ -472,6 +481,34 @@ pub struct Metadata { impl RequestValue for Metadata {} +/// Contains a list of TargetHttpsProxy 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 https proxies](struct.TargetHttpsProxyListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct TargetHttpsProxyList { + /// [Output Only] A token used to continue a truncated list request. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// A list of TargetHttpsProxy resources. + pub items: Option>, + /// Type of resource. + pub kind: Option, + /// [Output Only] Unique identifier for the resource; defined by the server. + pub id: Option, + /// [Output Only] Server-defined URL for this resource. + #[serde(rename="selfLink")] + pub self_link: Option, +} + +impl ResponseResult for TargetHttpsProxyList {} + + /// There is no detailed description. /// /// # Activities @@ -483,7 +520,7 @@ impl RequestValue for Metadata {} /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct InstanceGroupManagersRecreateInstancesRequest { - /// The names of one or more instances to recreate. + /// The URL for one or more instances to recreate. pub instances: Option>, } @@ -538,7 +575,7 @@ impl Part for RouteWarnings {} /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct TargetHttpProxy { - /// [Output Only] Type of resource. Always compute#Operation for Operation resources. + /// [Output Only] Type of resource. Always compute#operation for Operation resources. pub kind: Option, /// An optional textual description of the resource; provided by the client when the resource is created. pub description: Option, @@ -550,7 +587,7 @@ pub struct TargetHttpProxy { 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. + /// [Output Only] Server-defined URL for the resource. #[serde(rename="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. @@ -596,7 +633,7 @@ pub struct AddressList { pub kind: Option, /// [Output Only] Unique identifier for the resource; defined by the server. pub id: Option, - /// [Output Only] Server defined URL for the resource. + /// [Output Only] Server-defined URL for the resource. #[serde(rename="selfLink")] pub self_link: Option, } @@ -604,17 +641,45 @@ pub struct AddressList { impl ResponseResult for AddressList {} +/// Contains a list of HttpsHealthCheck 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 https health checks](struct.HttpsHealthCheckListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct HttpsHealthCheckList { + /// [Output Only] A token used to continue a truncated list request. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// A list of HttpsHealthCheck resources. + pub items: Option>, + /// Type of resource. + pub kind: Option, + /// [Output Only] Unique identifier for the resource; defined by the server. + pub id: Option, + /// [Output Only] Server-defined URL for this resource. + #[serde(rename="selfLink")] + pub self_link: Option, +} + +impl ResponseResult for HttpsHealthCheckList {} + + /// 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 InstanceWithNamedPorts { - /// The status of the instance. + /// [Output Only] The status of the instance. pub status: Option, - /// The URL of the instance. + /// [Output Only] The URL of the instance. pub instance: Option, - /// The named ports that belong to this instance group. + /// [Output Only] The named ports that belong to this instance group. #[serde(rename="namedPorts")] pub named_ports: Option>, } @@ -651,26 +716,26 @@ impl Part for UrlMapValidationResult {} /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct InstanceGroupManagerActionsSummary { - /// no description provided + /// [Output Only] The number of instances in the managed instance group that are running and have no scheduled actions. pub none: Option, - /// no description provided + /// [Output Only] The number of instances in the managed instance group that are scheduled to be recreated or are currently being being recreated. Recreating an instance deletes the existing root persistent disk and creates a new disk from the image that is defined in the instance template. pub recreating: Option, - /// no description provided + /// [Output Only] The number of instances in the managed instance group that are scheduled to be created or are currently being created. pub creating: Option, - /// no description provided + /// [Output Only] The number of instances in the managed instance group that are being reconfigured with properties that do not require a restart or a recreate action. For example, setting or removing target pools for the instance. pub refreshing: Option, - /// no description provided + /// [Output Only] The total number of instances in the managed instance group that are scheduled to be abandoned. Abandoning an instance removes it from the managed instance group without deleting it. pub abandoning: Option, - /// no description provided + /// [Output Only] The number of instances in the managed instance group that are scheduled to be deleted or are currently being deleted. pub deleting: Option, - /// no description provided + /// [Output Only] The number of instances in the managed instance group that are scheduled to be restarted or are currently being restarted. pub restarting: Option, } impl Part for InstanceGroupManagerActionsSummary {} -/// 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. +/// 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. /// @@ -697,7 +762,7 @@ impl Part for PathMatcher {} /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct ManagedInstanceLastAttempt { - /// Encountered errors during the last attempt to create or delete the instance. + /// [Output Only] Encountered errors during the last attempt to create or delete the instance. pub errors: Option, } @@ -733,7 +798,7 @@ pub struct Region { 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. + /// [Output Only] Server-defined URL for the resource. #[serde(rename="selfLink")] pub self_link: Option, /// [Output Only] Name of the resource. @@ -786,12 +851,15 @@ pub struct Project { /// The location in Cloud Storage and naming method of the daily usage report. #[serde(rename="usageExportLocation")] pub usage_export_location: Option, + /// Restricted features enabled for use on this project. + #[serde(rename="enabledFeatures")] + pub enabled_features: Option>, /// [Output Only] Creation timestamp in RFC3339 text format. #[serde(rename="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. + /// [Output Only] Server-defined URL for the resource. #[serde(rename="selfLink")] pub self_link: Option, /// Name of the resource. @@ -804,7 +872,7 @@ impl ResponseResult for Project {} /// InstanceGroupManagers /// -/// Next available tag: 17 +/// Next available tag: 19 /// /// # Activities /// @@ -826,30 +894,27 @@ impl ResponseResult for Project {} /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct InstanceGroupManager { - /// [Output Only] The list of instance actions and the number of instances in this managed instance group that are scheduled for those actions. - #[serde(rename="currentActions")] - pub current_actions: Option, - /// An optional text description for the managed instance group. - pub description: Option, - /// The URL of the zone where the managed instance group is located. - pub zone: Option, - /// The autohealing policy for this managed instance group. You can specify only one value. - #[serde(rename="autoHealingPolicies")] - pub auto_healing_policies: Option>, - /// [Output Only] The fingerprint of the target pools information, which is a hash of the contents. This field is used for optimistic locking when updating the target pool entries. - pub fingerprint: Option, - /// [Output Only] The URL of the InstanceGroup resource. - #[serde(rename="instanceGroup")] - pub instance_group: Option, /// The target number of running instances for this managed instance group. Deleting or abandoning instances reduces this number. Resizing the group changes this number. #[serde(rename="targetSize")] pub target_size: Option, - /// [Output Only] A unique identifier for this managed instance group. The server defines this identifier. + /// An optional text description for the managed instance group. + pub description: Option, + /// The name of the zone where the managed instance group is located. + pub zone: Option, + /// [Output Only] The fingerprint of the target pools information. You can use this optional field for optimistic locking when you update the target pool entries. + pub fingerprint: Option, + /// [Output Only] The URL of the Instance Group resource. + #[serde(rename="instanceGroup")] + pub instance_group: Option, + /// [Output Only] The list of instance actions and the number of instances in this managed instance group that are scheduled for each of those actions. + #[serde(rename="currentActions")] + pub current_actions: Option, + /// [Output Only] A unique identifier for this resource type. The server generates this identifier. pub id: Option, /// The base instance name to use for instances in this group. The value must be 1-58 characters long. Instances are named by appending a hyphen and a random four-character string to the base instance name. The base instance name must comply with RFC1035. #[serde(rename="baseInstanceName")] pub base_instance_name: Option, - /// The URL of all TargetPool resources to which new instances in the instanceGroup field are added. Updating the target pool values does not affect existing instances. + /// The URLs for all TargetPool resources to which instances in the instanceGroup field are added. The target pools automatically apply to all of the instances in the managed instance group. #[serde(rename="targetPools")] pub target_pools: Option>, /// The URL of the instance template that is specified for this managed instance group. The group uses this template to create all new instances in the managed instance group. @@ -860,7 +925,7 @@ pub struct InstanceGroupManager { pub creation_timestamp: Option, /// [Output Only] The resource type, which is always compute#instanceGroupManager for managed instance groups. pub kind: Option, - /// [Output Only] Server defined URL for this managed instance group. + /// [Output Only] The URL for this managed instance group. The server defines this URL. #[serde(rename="selfLink")] pub self_link: Option, /// The name of the managed instance group. The name must be 1-63 characters long, and comply with RFC1035. @@ -929,7 +994,7 @@ impl RequestValue for ResourceGroupReference {} /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct InstanceGroupManagersListManagedInstancesResponse { - /// List of managed instances. If empty - all instances are listed. + /// [Output Only] The list of instances in the managed instance group. #[serde(rename="managedInstances")] pub managed_instances: Option>, } @@ -957,7 +1022,7 @@ pub struct MachineTypeList { pub kind: Option, /// [Output Only] Unique identifier for the resource; defined by the server. pub id: Option, - /// [Output Only] Server defined URL for this resource. + /// [Output Only] Server-defined URL for this resource. #[serde(rename="selfLink")] pub self_link: Option, } @@ -965,6 +1030,34 @@ pub struct MachineTypeList { impl ResponseResult for MachineTypeList {} +/// Contains a list of SslCertificate 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 ssl certificates](struct.SslCertificateListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct SslCertificateList { + /// [Output Only] A token used to continue a truncated list request. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// A list of SslCertificate resources. + pub items: Option>, + /// Type of resource. + pub kind: Option, + /// [Output Only] Unique identifier for the resource. Defined by the server. + pub id: Option, + /// [Output Only] Server-defined URL for this resource. + #[serde(rename="selfLink")] + pub self_link: Option, +} + +impl ResponseResult for SslCertificateList {} + + /// Contains a list of ForwardingRule resources. /// /// # Activities @@ -986,7 +1079,7 @@ pub struct ForwardingRuleList { pub kind: Option, /// [Output Only] Unique identifier for the resource. Set by the server. pub id: Option, - /// [Output Only] Server defined URL for this resource. + /// [Output Only] Server-defined URL for this resource. #[serde(rename="selfLink")] pub self_link: Option, } @@ -1014,7 +1107,7 @@ pub struct FirewallList { pub kind: Option, /// [Output Only] Unique identifier for the resource; defined by the server. pub id: Option, - /// [Output Only] Server defined URL for this resource. + /// [Output Only] Server-defined URL for this resource. #[serde(rename="selfLink")] pub self_link: Option, } @@ -1052,16 +1145,16 @@ impl Part for UrlMapTest {} /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct AutoscalerAggregatedList { - /// A token used to continue a truncated list request (output only). + /// [Output Only] A token used to continue a truncated list request. #[serde(rename="nextPageToken")] pub next_page_token: Option, /// A map of scoped autoscaler lists. pub items: Option>, /// Type of resource. pub kind: Option, - /// Unique identifier for the resource; defined by the server (output only). + /// [Output Only] Unique identifier for the resource; defined by the server. pub id: Option, - /// Server defined URL for this resource (output only). + /// [Output Only] Server-defined URL for this resource. #[serde(rename="selfLink")] pub self_link: Option, } @@ -1101,13 +1194,13 @@ pub struct InstanceGroupsListInstances { /// [Output Only] A token that is used to continue a truncated list request. #[serde(rename="nextPageToken")] pub next_page_token: Option, - /// A list of InstanceWithNamedPorts resources, which contains all named ports for the given instance. + /// [Output Only] A list of instances and any named ports that are assigned to those instances. pub items: Option>, /// [Output Only] The resource type, which is always compute#instanceGroupsListInstances for lists of instance groups. pub kind: Option, - /// [Output Only] A unique identifier for this list of instance groups. The server defines this identifier. + /// [Output Only] A unique identifier for this list of instance groups. The server generates this identifier. pub id: Option, - /// [Output Only] The URL for this list of instance groups. The server defines this URL. + /// [Output Only] The URL for this list of instance groups. The server generates this URL. #[serde(rename="selfLink")] pub self_link: Option, } @@ -1133,12 +1226,12 @@ pub struct InstanceTemplate { pub kind: Option, /// An optional text description for the instance template. pub description: Option, - /// The name of the instance template. The name must be 1-63 characters long, and comply with RFC1035. + /// 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] The creation timestamp for this instance template in RFC3339 text format. #[serde(rename="creationTimestamp")] pub creation_timestamp: Option, - /// The instance properties for the instance template resource. + /// The instance properties for this instance template. pub properties: Option, /// [Output Only] The URL for this instance template. The server defines this URL. #[serde(rename="selfLink")] @@ -1209,7 +1302,7 @@ pub struct RouteList { pub kind: Option, /// [Output Only] Unique identifier for the resource. Defined by the server. pub id: Option, - /// [Output Only] Server defined URL for this resource. + /// [Output Only] Server-defined URL for this resource. #[serde(rename="selfLink")] pub self_link: Option, } @@ -1319,62 +1412,42 @@ impl NestedType for VpnTunnelsScopedListWarningData {} impl Part for VpnTunnelsScopedListWarningData {} -/// Contains a list of Operation resources. +/// A TargetHttpsProxy resource. This resource defines an HTTPS 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*). /// -/// * [list region operations](struct.RegionOperationListCall.html) (response) -/// * [list zone operations](struct.ZoneOperationListCall.html) (response) -/// * [list global operations](struct.GlobalOperationListCall.html) (response) +/// * [get target https proxies](struct.TargetHttpsProxyGetCall.html) (response) +/// * [insert target https proxies](struct.TargetHttpsProxyInsertCall.html) (request) /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] -pub struct OperationList { - /// [Output Only] A token used to continue a truncate. - #[serde(rename="nextPageToken")] - pub next_page_token: Option, - /// [Output Only] The Operation resources. - pub items: Option>, - /// [Output Only] Type of resource. Always compute#operations for Operations resource. +pub struct TargetHttpsProxy { + /// 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, + /// URLs to SslCertificate resources that are used to authenticate connections to Backends. Currently exactly one SSL certificate must be specified. + #[serde(rename="sslCertificates")] + pub ssl_certificates: Option>, + /// URL to the UrlMap resource that defines the mapping from URL to the BackendService. + #[serde(rename="urlMap")] + pub url_map: Option, + /// [Output Only] Creation timestamp in RFC3339 text format. + #[serde(rename="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 this resource. + /// [Output Only] Server-defined URL for the resource. #[serde(rename="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 ResponseResult for OperationList {} - - -/// 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, Serialize, Deserialize)] -pub struct TargetHttpProxyList { - /// [Output Only] A token used to continue a truncated list request. - #[serde(rename="nextPageToken")] - pub next_page_token: Option, - /// A list of TargetHttpProxy resources. - pub items: Option>, - /// Type of resource. Always compute#targetHttpProxyList for lists of Target HTTP proxies. - pub kind: Option, - /// [Output Only] Unique identifier for the resource; defined by the server. - pub id: Option, - /// [Output Only] Server-defined URL for this resource. - #[serde(rename="selfLink")] - pub self_link: Option, -} - -impl ResponseResult for TargetHttpProxyList {} +impl RequestValue for TargetHttpsProxy {} +impl ResponseResult for TargetHttpsProxy {} /// There is no detailed description. @@ -1398,25 +1471,29 @@ impl ResponseResult for TargetHttpProxyList {} pub struct InstanceGroup { /// [Output Only] The resource type, which is always compute#instanceGroup for instance groups. pub kind: Option, - /// The URL of the network to which all instances in the instance group belong. + /// [Output Only] The URL of the network to which all instances in the instance group belong. pub network: Option, - /// The URL of the zone where the instance group is located. + /// [Output Only] The URL of the zone where the instance group is located. pub zone: Option, /// An optional text description for the instance group. pub description: Option, /// The name of the instance group. The name must be 1-63 characters long, and comply with RFC1035. pub name: Option, - /// [Output Only] The fingerprint of the named ports information. The system uses this fingerprint to detect conflicts when multiple users change the named ports information concurrently. + /// [Output Only] The fingerprint of the named ports. The system uses this fingerprint to detect conflicts when multiple users change the named ports concurrently. pub fingerprint: Option, - /// Assigns a name to a port number. For example: {name: ?http?, port: 80} This allows the system to reference ports by the assigned name instead of a port number. Named ports can also contain multiple ports. For example: [{name: ?http?, port: 80},{name: "http", port: 8080}] Named ports apply to all instances in this instance group. + /// Assigns a name to a port number. For example: {name: "http", port: 80} + /// + /// This allows the system to reference ports by the assigned name instead of a port number. Named ports can also contain multiple ports. For example: [{name: "http", port: 80},{name: "http", port: 8080}] + /// + /// Named ports apply to all instances in this instance group. #[serde(rename="namedPorts")] pub named_ports: Option>, /// [Output Only] The creation timestamp for this instance group in RFC3339 text format. #[serde(rename="creationTimestamp")] pub creation_timestamp: Option, - /// [Output Only] A unique identifier for this instance group. The server defines this identifier. + /// [Output Only] A unique identifier for this resource type. The server generates this identifier. pub id: Option, - /// [Output Only] The URL for this instance group. The server defines this URL. + /// [Output Only] The URL for this instance group. The server generates this URL. #[serde(rename="selfLink")] pub self_link: Option, /// [Output Only] The total number of instances in the instance group. @@ -1457,7 +1534,7 @@ pub struct Network { 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. + /// [Output Only] Server-defined URL for the resource. #[serde(rename="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. @@ -1499,7 +1576,7 @@ pub struct Zone { 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. + /// [Output Only] Server-defined URL for the resource. #[serde(rename="selfLink")] pub self_link: Option, /// [Output Only] Name of the resource. @@ -1536,7 +1613,7 @@ pub struct AccessConfig { impl RequestValue for AccessConfig {} -/// An HttpHealthCheck resource. This resource defines a template for how individual VMs should be checked for health, via HTTP. +/// An HttpHealthCheck resource. This resource defines a template for how individual instances should be checked for health, via HTTP. /// /// # Activities /// @@ -1559,27 +1636,27 @@ pub struct HttpHealthCheck { /// 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(rename="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. + /// 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, /// How often (in seconds) to send a health check. The default value is 5 seconds. #[serde(rename="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. + /// A so-far healthy instance will be marked unhealthy after this many consecutive failures. The default value is 2. #[serde(rename="unhealthyThreshold")] pub unhealthy_threshold: Option, - /// A so-far unhealthy VM will be marked healthy after this many consecutive successes. The default value is 2. + /// A so-far unhealthy instance will be marked healthy after this many consecutive successes. The default value is 2. #[serde(rename="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). + /// [Output Only] Unique identifier for the resource. Defined by the server. pub id: Option, - /// Creation timestamp in RFC3339 text format (output only). + /// [Output Only] Creation timestamp in RFC3339 text format. #[serde(rename="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). + /// [Output Only] Server-defined URL for the resource. #[serde(rename="selfLink")] pub self_link: Option, /// The request path of the HTTP health check request. The default value is "/". @@ -1625,16 +1702,16 @@ impl RequestValue for UsageExportLocation {} /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct AutoscalerList { - /// A token used to continue a truncated list request (output only). + /// [Output Only] A token used to continue a truncated list request. #[serde(rename="nextPageToken")] pub next_page_token: Option, /// A list of Autoscaler resources. pub items: Option>, /// Type of resource. pub kind: Option, - /// Unique identifier for the resource; defined by the server (output only). + /// [Output Only] Unique identifier for the resource; defined by the server. pub id: Option, - /// Server defined URL for this resource (output only). + /// [Output Only] Server-defined URL for this resource. #[serde(rename="selfLink")] pub self_link: Option, } @@ -1667,7 +1744,7 @@ impl Part for AutoscalingPolicyCpuUtilization {} /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct InstanceGroupsAddInstancesRequest { - /// The instances to add to the instance group. + /// The list of instances to add to the instance group. pub instances: Option>, } @@ -1874,13 +1951,13 @@ pub struct InstanceGroupManagerAggregatedList { /// [Output Only] A token that is used to continue a truncated list request. #[serde(rename="nextPageToken")] pub next_page_token: Option, - /// A map of filtered managed instance group lists. + /// [Output Only] A map of filtered managed instance group lists. pub items: Option>, - /// [Output Only] Type of the resource. Always compute#instanceGroupManagerAggregatedList for an aggregated list of managed instance groups. + /// [Output Only] The resource type, which is always compute#instanceGroupManagerAggregatedList for an aggregated list of managed instance groups. pub kind: Option, - /// [Output Only] A unique identifier for this aggregated list of managed instance groups. The server defines this identifier. + /// [Output Only] A unique identifier for this aggregated list of managed instance groups. The server generates this identifier. pub id: Option, - /// [Output Only] The URL for this aggregated list of managed instance groups. The server defines this URL. + /// [Output Only] The URL for this resource type. The server generates this URL. #[serde(rename="selfLink")] pub self_link: Option, } @@ -1938,6 +2015,102 @@ pub struct InstanceList { impl ResponseResult for InstanceList {} +/// An HttpsHealthCheck resource. This resource defines a template for how individual instances should be checked for health, via HTTPS. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where 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 https health checks](struct.HttpsHealthCheckGetCall.html) (response) +/// * [list https health checks](struct.HttpsHealthCheckListCall.html) (none) +/// * [insert https health checks](struct.HttpsHealthCheckInsertCall.html) (request) +/// * [patch https health checks](struct.HttpsHealthCheckPatchCall.html) (request) +/// * [update https health checks](struct.HttpsHealthCheckUpdateCall.html) (request) +/// * [delete https health checks](struct.HttpsHealthCheckDeleteCall.html) (none) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct HttpsHealthCheck { + /// 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 a greater value than checkIntervalSec. + #[serde(rename="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. 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, + /// How often (in seconds) to send a health check. The default value is 5 seconds. + #[serde(rename="checkIntervalSec")] + pub check_interval_sec: Option, + /// A so-far healthy instance will be marked unhealthy after this many consecutive failures. The default value is 2. + #[serde(rename="unhealthyThreshold")] + pub unhealthy_threshold: Option, + /// A so-far unhealthy instance will be marked healthy after this many consecutive successes. The default value is 2. + #[serde(rename="healthyThreshold")] + pub healthy_threshold: Option, + /// The value of the host header in the HTTPS 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, + /// [Output Only] Unique identifier for the resource; defined by the server. + pub id: Option, + /// [Output Only] Creation timestamp in RFC3339 text format. + #[serde(rename="creationTimestamp")] + pub creation_timestamp: Option, + /// The TCP port number for the HTTPS health check request. The default value is 443. + pub port: Option, + /// [Output Only] Server-defined URL for the resource. + #[serde(rename="selfLink")] + pub self_link: Option, + /// The request path of the HTTPS health check request. The default value is "/". + #[serde(rename="requestPath")] + pub request_path: Option, +} + +impl RequestValue for HttpsHealthCheck {} +impl Resource for HttpsHealthCheck {} +impl ResponseResult for HttpsHealthCheck {} + + +/// An SslCertificate resource. This resource provides a mechanism to upload an SSL key and certificate to global HTTPS loadbalancer to serve secure connections. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where 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 ssl certificates](struct.SslCertificateDeleteCall.html) (none) +/// * [get ssl certificates](struct.SslCertificateGetCall.html) (response) +/// * [insert ssl certificates](struct.SslCertificateInsertCall.html) (request) +/// * [list ssl certificates](struct.SslCertificateListCall.html) (none) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct SslCertificate { + /// [Output Only] Type of the resource. Always compute#sslCertificate for SSL certificates. + 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, + /// A local certificate file. The certificate must be in PEM format. The certificate chain must be no greater than 5 certs long. The chain must include at least one intermediate cert. + pub certificate: Option, + /// A write-only private key in PEM format. Only insert RPCs will include this field. + #[serde(rename="privateKey")] + pub private_key: Option, + /// [Output Only] Creation timestamp in RFC3339 text format. + #[serde(rename="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(rename="selfLink")] + pub self_link: Option, + /// An optional textual description of the resource. Provided by the client when the resource is created. + pub description: Option, +} + +impl RequestValue for SslCertificate {} +impl Resource for SslCertificate {} +impl ResponseResult for SslCertificate {} + + /// There is no detailed description. /// /// # Activities @@ -1949,9 +2122,9 @@ impl ResponseResult for InstanceList {} /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct InstanceGroupManagersSetTargetPoolsRequest { - /// The fingerprint of the target pools information, which is a hash of the contents. This field is used for optimistic locking when updating the target pool entries. + /// The fingerprint of the target pools information. Use this optional property to prevent conflicts when multiple users change the target pools settings concurrently. Obtain the fingerprint with the instanceGroupManagers.get method. Then, include the fingerprint in your request to ensure that you do not overwrite changes that were applied from another concurrent request. pub fingerprint: Option, - /// The list of target pool URLs that instances in this managed instance group belong to. When the managed instance group creates new instances, the group automatically adds those instances to the target pools that are specified in this parameter. Changing the value of this parameter does not change the target pools of existing instances in this managed instance group. + /// The list of target pool URLs that instances in this managed instance group belong to. The managed instance group applies these target pools to all of the instances in the group. Existing instances and new instances in the group all receive these target pool settings. #[serde(rename="targetPools")] pub target_pools: Option>, } @@ -2035,7 +2208,7 @@ pub struct NetworkList { pub kind: Option, /// [Output Only] Unique identifier for the resource. Defined by the server. pub id: Option, - /// [Output Only] Server defined URL for this resource . + /// [Output Only] Server-defined URL for this resource . #[serde(rename="selfLink")] pub self_link: Option, } @@ -2063,7 +2236,7 @@ pub struct ZoneList { pub kind: Option, /// [Output Only] Unique identifier for the resource; defined by the server. pub id: Option, - /// Server defined URL for this resource (output only). + /// [Output Only] Server-defined URL for this resource. #[serde(rename="selfLink")] pub self_link: Option, } @@ -2071,6 +2244,25 @@ pub struct ZoneList { impl ResponseResult for ZoneList {} +/// 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 ssl certificates target https proxies](struct.TargetHttpsProxySetSslCertificateCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct TargetHttpsProxiesSetSslCertificatesRequest { + /// New set of URLs to SslCertificate resources to associate with this TargetHttpProxy. Currently exactly one ssl certificate must be specified. + #[serde(rename="sslCertificates")] + pub ssl_certificates: Option>, +} + +impl RequestValue for TargetHttpsProxiesSetSslCertificatesRequest {} + + /// There is no detailed description. /// /// # Activities @@ -2082,7 +2274,7 @@ impl ResponseResult for ZoneList {} /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct InstanceReference { - /// no description provided + /// The URL for a specific instance. pub instance: Option, } @@ -2103,7 +2295,7 @@ pub struct InstanceTemplateList { /// [Output Only] A token that is used to continue a truncated list request. #[serde(rename="nextPageToken")] pub next_page_token: Option, - /// A list of InstanceTemplate resources. + /// [Output Only] list of InstanceTemplate resources. pub items: Option>, /// [Output Only] The resource type, which is always compute#instanceTemplatesListResponse for instance template lists. pub kind: Option, @@ -2128,16 +2320,16 @@ impl ResponseResult for InstanceTemplateList {} /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct TargetInstanceList { - /// A token used to continue a truncated list request (output only). + /// [Output Only] A token used to continue a truncated list request. #[serde(rename="nextPageToken")] pub next_page_token: Option, /// A list of TargetInstance resources. pub items: Option>, /// Type of resource. pub kind: Option, - /// Unique identifier for the resource; defined by the server (output only). + /// [Output Only] Unique identifier for the resource; defined by the server. pub id: Option, - /// Server defined URL for this resource (output only). + /// [Output Only] Server-defined URL for this resource. #[serde(rename="selfLink")] pub self_link: Option, } @@ -2156,16 +2348,16 @@ impl ResponseResult for TargetInstanceList {} /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct HttpHealthCheckList { - /// A token used to continue a truncated list request (output only). + /// [Output Only] A token used to continue a truncated list request. #[serde(rename="nextPageToken")] pub next_page_token: Option, /// A list of HttpHealthCheck resources. pub items: Option>, /// Type of resource. pub kind: Option, - /// Unique identifier for the resource; defined by the server (output only). + /// [Output Only] Unique identifier for the resource. Defined by the server. pub id: Option, - /// Server defined URL for this resource (output only). + /// [Output Only] Server-defined URL for this resource. #[serde(rename="selfLink")] pub self_link: Option, } @@ -2184,7 +2376,7 @@ impl ResponseResult for HttpHealthCheckList {} /// #[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. + /// Specifies a unique device name of your choice that is reflected into the /dev/disk/by-id/google-* 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(rename="deviceName")] @@ -2203,7 +2395,7 @@ pub struct AttachedDisk { 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 + /// Specifies the disk interface to use for attaching this disk, either SCSI or NVME. The default is SCSI. For performance characteristics of SCSI over NVMe, see Local SSD performance. 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, @@ -2225,17 +2417,24 @@ impl RequestValue for AttachedDisk {} /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct ManagedInstance { - /// The current action that the managed instance group has scheduled for the instance. + /// [Output Only] The current action that the managed instance group has scheduled for the instance. Possible values: + /// - NONE The instance is running, and the managed instance group does not have any scheduled actions for this instance. + /// - CREATING The managed instance group is creating this instance. + /// - RECREATING The managed instance group is recreating this instance. + /// - DELETING The managed instance group is permanently deleting this instance. + /// - ABANDONING The managed instance group is abandoning this instance. The instance will be removed from the instance group and from any target pools that are associated with this group. + /// - RESTARTING The managed instance group is restarting the instance. + /// - REFRESHING The managed instance group is applying configuration changes to the instance without stopping it. For example, the group can update the target pool list for an instance without stopping that instance. #[serde(rename="currentAction")] pub current_action: Option, - /// The URL of the instance (set even though instance does not exist yet). + /// [Output Only] The URL of the instance. The URL can exist even if the instance has not yet been created. pub instance: Option, - /// Information about the last attempt to create or delete the instance. + /// [Output Only] Information about the last attempt to create or delete the instance. #[serde(rename="lastAttempt")] pub last_attempt: Option, - /// The unique identifier for this resource (empty when instance does not exist). + /// [Output only] The unique identifier for this resource. This field is empty when instance does not exist. pub id: Option, - /// The status of the instance (empty when instance does not exist). + /// [Output Only] The status of the instance. This field is empty when the instance does not exist. #[serde(rename="instanceStatus")] pub instance_status: Option, } @@ -2263,7 +2462,7 @@ pub struct ForwardingRuleAggregatedList { pub kind: Option, /// [Output Only] Unique identifier for the resource; defined by the server. pub id: Option, - /// [Output Only] Server defined URL for this resource. + /// [Output Only] Server-defined URL for this resource. #[serde(rename="selfLink")] pub self_link: Option, } @@ -2303,16 +2502,16 @@ impl Part for TestFailure {} /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct TargetPoolAggregatedList { - /// A token used to continue a truncated list request (output only). + /// [Output Only] A token used to continue a truncated list request. #[serde(rename="nextPageToken")] pub next_page_token: Option, /// A map of scoped target pool lists. pub items: Option>, /// Type of resource. pub kind: Option, - /// Unique identifier for the resource; defined by the server (output only). + /// [Output Only] Unique identifier for the resource. Defined by the server. pub id: Option, - /// Server defined URL for this resource (output only). + /// [Output Only] Server-defined URL for this resource. #[serde(rename="selfLink")] pub self_link: Option, } @@ -2328,9 +2527,12 @@ impl ResponseResult for TargetPoolAggregatedList {} /// The list links the activity name, along with information about where it is used (one of *request* and *response*). /// /// * [resize instance group managers](struct.InstanceGroupManagerResizeCall.html) (response) +/// * [delete ssl certificates](struct.SslCertificateDeleteCall.html) (response) /// * [patch autoscalers](struct.AutoscalerPatchCall.html) (response) +/// * [delete target https proxies](struct.TargetHttpsProxyDeleteCall.html) (response) /// * [patch firewalls](struct.FirewallPatchCall.html) (response) /// * [delete vpn tunnels](struct.VpnTunnelDeleteCall.html) (response) +/// * [set target global forwarding rules](struct.GlobalForwardingRuleSetTargetCall.html) (response) /// * [insert instances](struct.InstanceInsertCall.html) (response) /// * [delete global forwarding rules](struct.GlobalForwardingRuleDeleteCall.html) (response) /// * [insert vpn tunnels](struct.VpnTunnelInsertCall.html) (response) @@ -2342,7 +2544,7 @@ impl ResponseResult for TargetPoolAggregatedList {} /// * [add health check target pools](struct.TargetPoolAddHealthCheckCall.html) (response) /// * [insert instance group managers](struct.InstanceGroupManagerInsertCall.html) (response) /// * [insert global addresses](struct.GlobalAddresseInsertCall.html) (response) -/// * [set target global forwarding rules](struct.GlobalForwardingRuleSetTargetCall.html) (response) +/// * [delete https health checks](struct.HttpsHealthCheckDeleteCall.html) (response) /// * [insert autoscalers](struct.AutoscalerInsertCall.html) (response) /// * [insert instance groups](struct.InstanceGroupInsertCall.html) (response) /// * [delete instances instance group managers](struct.InstanceGroupManagerDeleteInstanceCall.html) (response) @@ -2351,7 +2553,9 @@ impl ResponseResult for TargetPoolAggregatedList {} /// * [set disk auto delete instances](struct.InstanceSetDiskAutoDeleteCall.html) (response) /// * [set target pools instance group managers](struct.InstanceGroupManagerSetTargetPoolCall.html) (response) /// * [insert disks](struct.DiskInsertCall.html) (response) +/// * [insert https health checks](struct.HttpsHealthCheckInsertCall.html) (response) /// * [remove health check target pools](struct.TargetPoolRemoveHealthCheckCall.html) (response) +/// * [set url map target https proxies](struct.TargetHttpsProxySetUrlMapCall.html) (response) /// * [delete backend services](struct.BackendServiceDeleteCall.html) (response) /// * [insert url maps](struct.UrlMapInsertCall.html) (response) /// * [add access config instances](struct.InstanceAddAccessConfigCall.html) (response) @@ -2374,10 +2578,12 @@ impl ResponseResult for TargetPoolAggregatedList {} /// * [insert routes](struct.RouteInsertCall.html) (response) /// * [delete instance groups](struct.InstanceGroupDeleteCall.html) (response) /// * [delete access config instances](struct.InstanceDeleteAccessConfigCall.html) (response) +/// * [set ssl certificates target https proxies](struct.TargetHttpsProxySetSslCertificateCall.html) (response) /// * [insert networks](struct.NetworkInsertCall.html) (response) /// * [abandon instances instance group managers](struct.InstanceGroupManagerAbandonInstanceCall.html) (response) /// * [set tags instances](struct.InstanceSetTagCall.html) (response) /// * [delete snapshots](struct.SnapshotDeleteCall.html) (response) +/// * [insert target https proxies](struct.TargetHttpsProxyInsertCall.html) (response) /// * [detach disk instances](struct.InstanceDetachDiskCall.html) (response) /// * [update backend services](struct.BackendServiceUpdateCall.html) (response) /// * [recreate instances instance group managers](struct.InstanceGroupManagerRecreateInstanceCall.html) (response) @@ -2390,8 +2596,10 @@ impl ResponseResult for TargetPoolAggregatedList {} /// * [patch http health checks](struct.HttpHealthCheckPatchCall.html) (response) /// * [insert images](struct.ImageInsertCall.html) (response) /// * [set named ports instance groups](struct.InstanceGroupSetNamedPortCall.html) (response) +/// * [insert ssl certificates](struct.SslCertificateInsertCall.html) (response) /// * [move instance projects](struct.ProjectMoveInstanceCall.html) (response) /// * [delete autoscalers](struct.AutoscalerDeleteCall.html) (response) +/// * [update https health checks](struct.HttpsHealthCheckUpdateCall.html) (response) /// * [patch url maps](struct.UrlMapPatchCall.html) (response) /// * [stop instances](struct.InstanceStopCall.html) (response) /// * [add instance target pools](struct.TargetPoolAddInstanceCall.html) (response) @@ -2401,12 +2609,13 @@ impl ResponseResult for TargetPoolAggregatedList {} /// * [delete instance templates](struct.InstanceTemplateDeleteCall.html) (response) /// * [set usage export bucket projects](struct.ProjectSetUsageExportBucketCall.html) (response) /// * [insert target http proxies](struct.TargetHttpProxyInsertCall.html) (response) -/// * [delete networks](struct.NetworkDeleteCall.html) (response) +/// * [update url maps](struct.UrlMapUpdateCall.html) (response) /// * [insert instance templates](struct.InstanceTemplateInsertCall.html) (response) /// * [delete target instances](struct.TargetInstanceDeleteCall.html) (response) /// * [delete target vpn gateways](struct.TargetVpnGatewayDeleteCall.html) (response) /// * [delete global addresses](struct.GlobalAddresseDeleteCall.html) (response) -/// * [update url maps](struct.UrlMapUpdateCall.html) (response) +/// * [patch https health checks](struct.HttpsHealthCheckPatchCall.html) (response) +/// * [delete networks](struct.NetworkDeleteCall.html) (response) /// * [delete url maps](struct.UrlMapDeleteCall.html) (response) /// * [reset instances](struct.InstanceResetCall.html) (response) /// * [insert backend services](struct.BackendServiceInsertCall.html) (response) @@ -2448,7 +2657,7 @@ pub struct Operation { pub creation_timestamp: Option, /// [Output Only] Unique identifier for the resource; defined by the server. pub id: Option, - /// [Output Only] Type of the resource. Always compute#Operation for Operation resources. + /// [Output Only] Type of the resource. Always compute#operation for Operation resources. pub kind: Option, /// [Output Only] Name of the resource. pub name: Option, @@ -2456,10 +2665,10 @@ pub struct Operation { pub zone: Option, /// [Output Only] URL of the region where the operation resides. Only applicable for regional resources. pub region: Option, - /// [Output Only] Server defined URL for the resource. + /// [Output Only] Server-defined URL for the resource. #[serde(rename="selfLink")] pub self_link: Option, - /// [Output Only] Type of the operation, such as insert, update, and delete. + /// [Output Only] Type of the operation, such as insert, compute.instanceGroups.update, or compute.instanceGroups.delete. #[serde(rename="operationType")] pub operation_type: Option, /// [Output Only] If the operation fails, this field contains the HTTP error message that was returned, such as NOT FOUND. @@ -2494,7 +2703,7 @@ impl ResponseResult for Operation {} /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct InstanceGroupManagersDeleteInstancesRequest { - /// The names of one or more instances to delete. + /// The list of instances to delete from this managed instance group. Specify one or more instance URLs. pub instances: Option>, } @@ -2551,7 +2760,7 @@ pub struct Image { 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. + /// [Output Only] Server-defined URL for the resource. #[serde(rename="selfLink")] pub self_link: Option, /// The type of the image used to create this disk. The default and only value is RAW @@ -2584,7 +2793,7 @@ pub struct DiskList { pub kind: Option, /// [Output Only] Unique identifier for the resource; defined by the server. pub id: Option, - /// [Output Only] Server defined URL for this resource. + /// [Output Only] Server-defined URL for this resource. #[serde(rename="selfLink")] pub self_link: Option, } @@ -2685,6 +2894,34 @@ pub struct BackendServiceList { impl ResponseResult for BackendServiceList {} +/// 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, Serialize, Deserialize)] +pub struct TargetHttpProxyList { + /// [Output Only] A token used to continue a truncated list request. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// A list of TargetHttpProxy resources. + pub items: Option>, + /// Type of resource. Always compute#targetHttpProxyList for lists of Target HTTP proxies. + pub kind: Option, + /// [Output Only] Unique identifier for the resource; defined by the server. + pub id: Option, + /// [Output Only] Server-defined URL for this resource. + #[serde(rename="selfLink")] + pub self_link: Option, +} + +impl ResponseResult for TargetHttpProxyList {} + + /// Load balancing utilization policy. /// /// This type is not used in any activity, and only used as *part* of another schema. @@ -2719,7 +2956,7 @@ pub struct RegionList { pub kind: Option, /// [Output Only] Unique identifier for the resource; defined by the server. pub id: Option, - /// [Output Only] Server defined URL for this resource. + /// [Output Only] Server-defined URL for this resource. #[serde(rename="selfLink")] pub self_link: Option, } @@ -2943,21 +3180,32 @@ pub struct AddressesScopedList { impl Part for AddressesScopedList {} -/// There is no detailed description. +/// Contains a list of TargetVpnGateway resources. /// -/// This type is not used in any activity, and only used as *part* of another schema. +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where 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 vpn gateways](struct.TargetVpnGatewayListCall.html) (response) /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] -pub struct InstanceGroupManagerAutoHealingPolicy { - /// The URL for the HealthCheck that signals autohealing. - #[serde(rename="healthCheck")] - pub health_check: Option, - /// The action to perform when an instance becomes unhealthy. Possible values are RECREATE or RESTART. RECREATE replaces an unhealthy instance with a new instance that is based on the instance template for this managed instance group. RESTART performs a soft restart on an instance. If the instance cannot restart softly, the instance performs a hard restart. - #[serde(rename="actionType")] - pub action_type: Option, +pub struct TargetVpnGatewayList { + /// [Output Only] A token used to continue a truncated list request. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// [Output Only] A list of TargetVpnGateway resources. + pub items: Option>, + /// [Output Only] Type of resource. Always compute#targetVpnGateway for target VPN gateways. + pub kind: Option, + /// [Output Only] Unique identifier for the resource. Defined by the server. + pub id: Option, + /// [Output Only] Server-defined URL for the resource. + #[serde(rename="selfLink")] + pub self_link: Option, } -impl Part for InstanceGroupManagerAutoHealingPolicy {} +impl ResponseResult for TargetVpnGatewayList {} /// [Output Only] Informational warning which replaces the list of disk types when the list is empty. @@ -2996,9 +3244,9 @@ pub struct InstanceGroupAggregatedList { pub items: Option>, /// [Output Only] The resource type, which is always compute#instanceGroupAggregatedList for aggregated lists of instance groups. pub kind: Option, - /// [Output Only] A unique identifier for this aggregated list of instance groups. The server defines this identifier. + /// [Output Only] A unique identifier for this aggregated list of instance groups. The server generates this identifier. pub id: Option, - /// [Output Only] A unique identifier for this aggregated list of instance groups. The server defines this identifier. + /// [Output Only] The URL for this resource type. The server generates this URL. #[serde(rename="selfLink")] pub self_link: Option, } @@ -3085,7 +3333,7 @@ pub struct DiskAggregatedList { pub kind: Option, /// [Output Only] Unique identifier for the resource; defined by the server. pub id: Option, - /// [Output Only] Server defined URL for this resource. + /// [Output Only] Server-defined URL for this resource. #[serde(rename="selfLink")] pub self_link: Option, } @@ -3113,7 +3361,7 @@ pub struct OperationAggregatedList { pub kind: Option, /// [Output Only] Unique identifier for the resource; defined by the server. pub id: Option, - /// [Output Only] Server defined URL for this resource. + /// [Output Only] Server-defined URL for this resource. #[serde(rename="selfLink")] pub self_link: Option, } @@ -3173,7 +3421,7 @@ pub struct AddressAggregatedList { pub kind: Option, /// [Output Only] Unique identifier for the resource; defined by the server. pub id: Option, - /// [Output Only] Server defined URL for this resource. + /// [Output Only] Server-defined URL for this resource. #[serde(rename="selfLink")] pub self_link: Option, } @@ -3192,9 +3440,6 @@ impl ResponseResult for AddressAggregatedList {} /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct InstanceGroupsListInstancesRequest { - /// A filter for the named ports that are associated with instances in the instance group. If you specify this parameter, the generated list includes only instances that are associated with the specified named ports. If you do not specify this parameter, the generated list includes all instances regardless of their named ports. - #[serde(rename="portName")] - pub port_name: Option, /// A filter for the state of the instances in the instance group. Valid options are ALL or RUNNING. If you do not specify this parameter the list includes all instances regardless of their state. #[serde(rename="instanceState")] pub instance_state: Option, @@ -3232,16 +3477,16 @@ impl Part for TargetPoolsScopedListWarning {} /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct SnapshotList { - /// A token used to continue a truncated list request (output only). + /// [Output Only] A token used to continue a truncated list request. #[serde(rename="nextPageToken")] pub next_page_token: Option, /// A list of Snapshot resources. pub items: Option>, /// Type of resource. pub kind: Option, - /// Unique identifier for the resource; defined by the server (output only). + /// [Output Only] Unique identifier for the resource. Defined by the server. pub id: Option, - /// Server defined URL for this resource (output only). + /// [Output Only] Server-defined URL for this resource. #[serde(rename="selfLink")] pub self_link: Option, } @@ -3368,7 +3613,7 @@ pub struct DiskTypesScopedList { impl Part for DiskTypesScopedList {} -/// A BackendService resource. This resource defines a group of backend VMs together with their serving capacity. +/// A BackendService resource. This resource defines a group of backend virtual machines together with their serving capacity. /// /// # Activities /// @@ -3411,7 +3656,7 @@ pub struct BackendService { 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, - /// [Output Only] Server defined URL for the resource. + /// [Output Only] Server-defined URL for the resource. #[serde(rename="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. @@ -3467,7 +3712,7 @@ pub struct MachineType { 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. + /// [Output Only] Server-defined URL for the resource. #[serde(rename="selfLink")] pub self_link: Option, /// [Output Only] Name of the resource. @@ -3489,16 +3734,16 @@ impl ResponseResult for MachineType {} /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct ImageList { - /// A token used to continue a truncated list request (output only). + /// [Output Only] A token used to continue a truncated list request. #[serde(rename="nextPageToken")] pub next_page_token: Option, - /// A list of Image resources. + /// [Output Only] A list of Image resources. pub items: Option>, /// Type of resource. pub kind: Option, - /// Unique identifier for the resource; defined by the server (output only). + /// [Output Only] Unique identifier for the resource; defined by the server. pub id: Option, - /// Server defined URL for this resource (output only). + /// [Output Only] Server-defined URL for this resource. #[serde(rename="selfLink")] pub self_link: Option, } @@ -3562,11 +3807,11 @@ impl Part for ForwardingRulesScopedListWarning {} /// #[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. + /// The list of host patterns to match. They must be valid hostnames, except * will match any string of ([a-z0-9-.]*). In that case, * must be the first character and must be followed in the pattern by either - or .. pub hosts: Option>, /// An optional textual description. pub description: Option, - /// The name of the PathMatcher to match the path portion of the URL, if the this hostRule matches the URL's host portion. + /// The name of the PathMatcher to use to match the path portion of the URL if the hostRule matches the URL's host portion. #[serde(rename="pathMatcher")] pub path_matcher: Option, } @@ -3616,7 +3861,7 @@ pub struct Firewall { 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. + /// [Output Only] Server-defined URL for the resource. #[serde(rename="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: @@ -3633,41 +3878,43 @@ impl Resource for Firewall {} impl ResponseResult for Firewall {} -/// Contains a list of TargetVpnGateway resources. +/// 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 target vpn gateways](struct.TargetVpnGatewayListCall.html) (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, Serialize, Deserialize)] -pub struct TargetVpnGatewayList { - /// [Output Only] A token used to continue a truncated list request. +pub struct OperationList { + /// [Output Only] A token used to continue a truncate. #[serde(rename="nextPageToken")] pub next_page_token: Option, - /// [Output Only] A list of TargetVpnGateway resources. - pub items: Option>, - /// [Output Only] Type of resource. Always compute#targetVpnGateway for target VPN gateways. + /// [Output Only] The Operation resources. + pub items: Option>, + /// [Output Only] Type of resource. Always compute#operations for Operations resource. pub kind: Option, - /// [Output Only] Unique identifier for the resource. Defined by the server. + /// [Output Only] Unique identifier for the resource; defined by the server. pub id: Option, - /// [Output Only] Server-defined URL for the resource. + /// [Output Only] Server-defined URL for this resource. #[serde(rename="selfLink")] pub self_link: Option, } -impl ResponseResult for TargetVpnGatewayList {} +impl ResponseResult for OperationList {} -/// The named port information. For example: . +/// The named port. For example: . /// /// This type is not used in any activity, and only used as *part* of another schema. /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct NamedPort { - /// The name for this NamedPort. + /// The name for this named port. The name must be 1-63 characters long, and comply with RFC1035. pub name: Option, /// The port number, which can be a value between 1 and 65535. pub port: Option, @@ -3676,7 +3923,7 @@ pub struct NamedPort { impl Part for NamedPort {} -/// A TargetInstance resource. This resource defines an endpoint VM that terminates traffic of certain protocols. +/// A TargetInstance resource. This resource defines an endpoint instance that terminates traffic of certain protocols. /// /// # Activities /// @@ -3691,26 +3938,26 @@ impl Part for NamedPort {} /// #[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. + /// NAT option controlling how IPs are NAT'ed to the instance. Currently only NO_NAT (default value) is supported. #[serde(rename="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). + /// [Output Only] URL of the zone where the target instance resides. 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). + /// [Output Only] Creation timestamp in RFC3339 text format. #[serde(rename="creationTimestamp")] pub creation_timestamp: Option, - /// Unique identifier for the resource; defined by the server (output only). + /// [Output Only] Unique identifier for the resource; defined by the server. pub id: Option, - /// Server defined URL for the resource (output only). + /// [Output Only] Server-defined URL for the resource. #[serde(rename="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. + /// 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, } @@ -3730,16 +3977,16 @@ impl ResponseResult for TargetInstance {} /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct TargetInstanceAggregatedList { - /// A token used to continue a truncated list request (output only). + /// [Output Only] A token used to continue a truncated list request. #[serde(rename="nextPageToken")] pub next_page_token: Option, /// A map of scoped target instance lists. pub items: Option>, /// Type of resource. pub kind: Option, - /// Unique identifier for the resource; defined by the server (output only). + /// [Output Only] Unique identifier for the resource; defined by the server. pub id: Option, - /// Server defined URL for this resource (output only). + /// [Output Only] Server-defined URL for this resource. #[serde(rename="selfLink")] pub self_link: Option, } @@ -3747,7 +3994,7 @@ pub struct TargetInstanceAggregatedList { impl ResponseResult for TargetInstanceAggregatedList {} -/// [Output Only] A list of InstanceGroupManager resources. +/// [Output Only] A list of managed instance groups. /// /// # Activities /// @@ -3761,13 +4008,13 @@ pub struct InstanceGroupManagerList { /// [Output Only] A token that is used to continue a truncated list request. #[serde(rename="nextPageToken")] pub next_page_token: Option, - /// [Output Only] A list of managed instance group resources. + /// [Output Only] A list of managed instance groups. pub items: Option>, - /// [Output Only] Type of the resource. Always compute#instanceGroupManagerList for a list of managed instance group resources. + /// [Output Only] The resource type, which is always compute#instanceGroupManagerList for a list of managed instance groups. pub kind: Option, - /// [Output Only] A unique identifier for this managed instance group. The server defines this identifier. + /// [Output Only] A unique identifier for this resource type. The server generates this identifier. pub id: Option, - /// [Output Only] The URL for this managed instance group. The server defines this URL. + /// [Output Only] The URL for this resource type. The server generates this URL. #[serde(rename="selfLink")] pub self_link: Option, } @@ -3811,7 +4058,7 @@ pub struct DiskTypeAggregatedList { pub kind: Option, /// [Output Only] Unique identifier for the resource; defined by the server. pub id: Option, - /// [Output Only] Server defined URL for this resource. + /// [Output Only] Server-defined URL for this resource. #[serde(rename="selfLink")] pub self_link: Option, } @@ -3834,7 +4081,7 @@ pub struct InstancesScopedList { impl Part for InstancesScopedList {} -/// Encountered errors during the last attempt to create or delete the instance. +/// [Output Only] Encountered errors during the last attempt to create or delete the instance. /// /// This type is not used in any activity, and only used as *part* of another schema. /// @@ -3868,7 +4115,7 @@ pub struct MachineTypeAggregatedList { pub kind: Option, /// [Output Only] Unique identifier for the resource; defined by the server. pub id: Option, - /// [Output Only] Server defined URL for this resource. + /// [Output Only] Server-defined URL for this resource. #[serde(rename="selfLink")] pub self_link: Option, } @@ -3923,7 +4170,7 @@ impl Part for TargetInstancesScopedListWarning {} /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct InstanceGroupManagersAbandonInstancesRequest { - /// The names of instances to abandon from the managed instance group. + /// The URL for one or more instances to abandon from the managed instance group. pub instances: Option>, } @@ -3944,13 +4191,13 @@ pub struct InstanceGroupList { /// [Output Only] A token that is used to continue a truncated list request. #[serde(rename="nextPageToken")] pub next_page_token: Option, - /// A list of InstanceGroup resources. + /// A list of instance groups. pub items: Option>, /// [Output Only] The resource type, which is always compute#instanceGroupList for instance group lists. pub kind: Option, - /// [Output Only] A unique identifier for this list of instance groups. The server defines this identifier. + /// [Output Only] A unique identifier for this list of instance groups. The server generates this identifier. pub id: Option, - /// [Output Only] The URL for this instance group. The server defines this URL. + /// [Output Only] The URL for this resource type. The server generates this URL. #[serde(rename="selfLink")] pub self_link: Option, } @@ -4004,9 +4251,8 @@ pub struct VpnTunnel { pub peer_ip: Option, /// [Output Only] URL of the region where the VPN tunnel resides. pub region: Option, - /// IKE networks to use when establishing the VPN tunnel with peer VPN gateway. The value should be a CIDR formatted string, for example: 192.168.0.0/16. The ranges should be disjoint. - #[serde(rename="ikeNetworks")] - pub ike_networks: 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] The status of the VPN tunnel. pub status: Option, /// Hash of the shared secret. @@ -4015,19 +4261,17 @@ pub struct VpnTunnel { /// URL of the VPN gateway to which this VPN tunnel is associated. Provided by the client when the VPN tunnel is created. #[serde(rename="targetVpnGateway")] pub target_vpn_gateway: Option, - /// Shared secret used to set the secure session between the GCE VPN gateway and the peer VPN gateway. - #[serde(rename="sharedSecret")] - pub shared_secret: Option, /// [Output Only] Creation timestamp in RFC3339 text format. #[serde(rename="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. + /// [Output Only] Server-defined URL for the resource. #[serde(rename="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, + /// Shared secret used to set the secure session between the GCE VPN gateway and the peer VPN gateway. + #[serde(rename="sharedSecret")] + pub shared_secret: Option, } impl RequestValue for VpnTunnel {} @@ -4102,6 +4346,7 @@ impl Part for MetadataItems {} /// This type is used in activities, which are methods you may call on this type or where 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 https proxies](struct.TargetHttpsProxySetUrlMapCall.html) (request) /// * [set url map target http proxies](struct.TargetHttpProxySetUrlMapCall.html) (request) /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] @@ -4219,19 +4464,19 @@ pub struct Autoscaler { pub kind: 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 instance group resides (output only). + /// [Output Only] URL of the zone where the instance group resides. pub zone: 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. + /// 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, /// Autoscaling configuration. #[serde(rename="autoscalingPolicy")] pub autoscaling_policy: Option, - /// Creation timestamp in RFC3339 text format (output only). + /// [Output Only] Creation timestamp in RFC3339 text format. #[serde(rename="creationTimestamp")] pub creation_timestamp: Option, - /// Unique identifier for the resource; defined by the server (output only). + /// [Output Only] Unique identifier for the resource; defined by the server. pub id: Option, - /// Server defined URL for the resource (output only). + /// [Output Only] Server-defined URL for the resource. #[serde(rename="selfLink")] pub self_link: Option, /// URL of Instance Group Manager or Replica Pool which will be controlled by Autoscaler. @@ -4272,7 +4517,7 @@ impl Part for TargetVpnGatewaysScopedListWarning {} /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct InstanceGroupsRemoveInstancesRequest { - /// The instances to remove from the instance group. + /// The list of instances to remove from the instance group. pub instances: Option>, } @@ -4336,7 +4581,7 @@ pub struct Quota { impl Part for Quota {} -/// A TargetPool resource. This resource defines a pool of VMs, associated HttpHealthCheck resources, and the fallback TargetPool. +/// A TargetPool resource. This resource defines a pool of instances, associated HttpHealthCheck resources, and the fallback TargetPool. /// /// # Activities /// @@ -4359,41 +4604,44 @@ impl Part for Quota {} 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. + /// If set, backupPool must also be set. They together define the fallback behavior of the primary target pool: if the ratio of the healthy instances 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. + /// In case where failoverRatio is not set or all the instances 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 instances with the best effort, or to all instances when no instance is healthy. #[serde(rename="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). + /// [Output Only] URL of the region where the target pool resides. 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. + /// Sesssion affinity option, must be one of the following values: + /// NONE: Connections from the same client IP may go to any instance in the pool. + /// CLIENT_IP: Connections from the same client IP will go to the same instance in the pool while that instance remains healthy. + /// CLIENT_IP_PROTO: Connections from the same client IP with the same IP protocol will go to the same instance in the pool while that instance remains healthy. #[serde(rename="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. + /// A list of resource URLs to the member virtual machines 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]. + /// 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. + /// backupPool and failoverRatio together define the fallback behavior of the primary target pool: if the ratio of the healthy instances 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. + /// In case where failoverRatio and backupPool are not set, or all the instances 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 instances with the best effort, or to all instances when no instance is healthy. #[serde(rename="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. + /// A list of URLs to the HttpHealthCheck resource. A member instance in this pool is considered healthy if and only if all specified health checks pass. An empty list means all member instances will be considered healthy at all times. #[serde(rename="healthChecks")] pub health_checks: Option>, - /// Creation timestamp in RFC3339 text format (output only). + /// [Output Only] Creation timestamp in RFC3339 text format. #[serde(rename="creationTimestamp")] pub creation_timestamp: Option, - /// Unique identifier for the resource; defined by the server (output only). + /// [Output Only] Unique identifier for the resource; defined by the server. pub id: Option, - /// Server defined URL for the resource (output only). + /// [Output Only] Server-defined URL for the resource. #[serde(rename="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. + /// 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, } @@ -4465,7 +4713,7 @@ pub struct Address { 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. + /// [Output Only] Server-defined URL for the resource. #[serde(rename="selfLink")] pub self_link: Option, /// [Output Only] The URLs of the resources that are using this address. @@ -4494,7 +4742,7 @@ impl NestedType for MachineTypesScopedListWarning {} impl Part for MachineTypesScopedListWarning {} -/// 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. +/// A ForwardingRule resource. A ForwardingRule resource specifies which pool of target virtual machines to forward a packet to if it matches the given [IPAddress, IPProtocol, portRange] tuple. /// /// # Activities /// @@ -4512,11 +4760,11 @@ impl Part for MachineTypesScopedListWarning {} /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct ForwardingRule { - /// Type of the resource. + /// [Output Only] Type of the resource. Always compute#forwardingRule. 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. + /// Applicable only when IPProtocol is TCP, UDP, or SCTP, only packets addressed to ports in the specified range will be forwarded to target. Forwarding rules with the same `[IPAddress, IPProtocol]` pair must have disjoint port ranges. #[serde(rename="portRange")] pub port_range: Option, /// [Output Only] URL of the region where the regional forwarding rule resides. This field is not applicable to global forwarding rules. @@ -4526,7 +4774,7 @@ pub struct ForwardingRule { /// [Output Only] Creation timestamp in RFC3339 text format. #[serde(rename="creationTimestamp")] pub creation_timestamp: Option, - /// The IP protocol to which this rule applies, valid options are TCP, UDP, ESP, AH or SCTP. + /// The IP protocol to which this rule applies. Valid options are TCP, UDP, ESP, AH or SCTP. #[serde(rename="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. @@ -4578,9 +4826,9 @@ pub struct License { pub charges_use_fee: Option, /// [Output Only] Type of resource. Always compute#license for licenses. pub kind: Option, - /// Name of the resource. The name must be 1-63 characters long, and comply with RCF1035. + /// [Output Only] Name of the resource. The name is 1-63 characters long and complies with RFC1035. pub name: Option, - /// [Output Only] Server defined URL for the resource. + /// [Output Only] Server-defined URL for the resource. #[serde(rename="selfLink")] pub self_link: Option, } @@ -4609,7 +4857,7 @@ pub struct DiskTypeList { pub kind: Option, /// [Output Only] Unique identifier for the resource; defined by the server. pub id: Option, - /// [Output Only] Server defined URL for this resource. + /// [Output Only] Server-defined URL for this resource. #[serde(rename="selfLink")] pub self_link: Option, } @@ -4632,7 +4880,7 @@ pub struct AutoscalersScopedList { impl Part for AutoscalersScopedList {} -/// 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 nextHop 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 are dropped. +/// The route resource. A Route is a rule that specifies how certain packets should be handled by the virtual network. Routes are associated with instances by tag and the set of Routes for a particular instance is called its routing table. For each packet leaving a instance, the system searches that instance'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 nextHop field of the winning Route -- either to another instance destination, a instance gateway or a Google Compute Engien-operated gateway. Packets that do not match any Route in the sending instance's routing table are dropped. /// /// # Activities /// @@ -4736,7 +4984,7 @@ impl RequestValue for TargetReference {} /// #[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. @@ -4877,7 +5125,7 @@ pub struct UrlMap { pub creation_timestamp: Option, /// [Output Only] Unique identifier for the resource. Set by the server. pub id: Option, - /// [Output Only] Server defined URL for the resource. + /// [Output Only] Server-defined URL for the resource. #[serde(rename="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. @@ -4932,16 +5180,16 @@ impl Part for InstanceGroupsScopedList {} /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct TargetPoolList { - /// A token used to continue a truncated list request (output only). + /// [Output Only] A token used to continue a truncated list request. #[serde(rename="nextPageToken")] pub next_page_token: Option, /// A list of TargetPool resources. pub items: Option>, /// Type of resource. pub kind: Option, - /// Unique identifier for the resource; defined by the server (output only). + /// [Output Only] Unique identifier for the resource. Defined by the server. pub id: Option, - /// Server defined URL for this resource (output only). + /// [Output Only] Server-defined URL for this resource. #[serde(rename="selfLink")] pub self_link: Option, } @@ -4955,7 +5203,7 @@ impl ResponseResult for TargetPoolList {} /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct InstanceProperties { - /// A boolean that specifies if instances created from this template can send packets with source IP addresses other than their own or receive packets with destination IP addresses other than their own. If you use these instances as an IP gateway or as the next-hop in a Route resource, specify true. Otherwise, specify false. + /// Enables 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, specify true. If unsure, leave this set to false. See the canIpForward documentation for more information. #[serde(rename="canIpForward")] pub can_ip_forward: Option, /// An optional text description for the instances that are created from this instance template. @@ -4964,7 +5212,7 @@ pub struct InstanceProperties { pub tags: Option, /// An array of disks that are associated with the instances that are created from this template. pub disks: Option>, - /// A list of scheduling options for the instances that are created from this template. + /// Specifies the scheduling options for the instances that are created from this template. pub scheduling: Option, /// The machine type to use for instances that are created from this template. #[serde(rename="machineType")] @@ -4972,7 +5220,7 @@ pub struct InstanceProperties { /// A list of service accounts with specified scopes. Access tokens for these service accounts are available to the instances that are created from this template. Use metadata queries to obtain the access tokens for these instances. #[serde(rename="serviceAccounts")] pub service_accounts: Option>, - /// An array of network access 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 supported access configuration. If you do not specify any access configurations, the instances that are created from this template will have no external internet access. + /// An array of network access configurations for this interface. #[serde(rename="networkInterfaces")] pub network_interfaces: Option>, /// The metadata key/value pairs to assign to instances that are created from this template. These pairs can consist of custom metadata or predefined keys. See Project and instance metadata for more information. @@ -5048,12 +5296,12 @@ impl Part for ManagedInstanceLastAttemptErrorsErrors {} /// #[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). + /// Specifies whether the instance should be automatically restarted if it is terminated by Compute Engine (not terminated by a user). You can only set the automatic restart option for standard instances. Preemptible instances cannot be automatically restarted. #[serde(rename="automaticRestart")] pub automatic_restart: Option, - /// Whether the Instance is preemptible. + /// Whether the instance is preemptible. pub preemptible: Option, - /// Defines the maintenance behavior for this instance. The default behavior is MIGRATE. For more information, see Setting maintenance behavior. + /// Defines the maintenance behavior for this instance. For standard instances, the default behavior is MIGRATE. For preemptible instances, the default and only possible behavior is TERMINATE. For more information, see Setting maintenance behavior. #[serde(rename="onHostMaintenance")] pub on_host_maintenance: Option, } @@ -5814,7 +6062,7 @@ impl<'a, C, A> SnapshotMethods<'a, C, A> { -/// A builder providing access to all methods supported on *instanceGroupManager* resources. +/// A builder providing access to all methods supported on *diskType* resources. /// It is not used directly, but through the `Compute` hub. /// /// # Example @@ -5837,38 +6085,36 @@ impl<'a, C, A> SnapshotMethods<'a, C, A> { /// ::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 `abandon_instances(...)`, `aggregated_list(...)`, `delete(...)`, `delete_instances(...)`, `get(...)`, `insert(...)`, `list(...)`, `list_managed_instances(...)`, `recreate_instances(...)`, `resize(...)`, `set_instance_template(...)` and `set_target_pools(...)` +/// // like `aggregated_list(...)`, `get(...)` and `list(...)` /// // to build up your call. -/// let rb = hub.instance_group_managers(); +/// let rb = hub.disk_types(); /// # } /// ``` -pub struct InstanceGroupManagerMethods<'a, C, A> +pub struct DiskTypeMethods<'a, C, A> where C: 'a, A: 'a { hub: &'a Compute, } -impl<'a, C, A> MethodsBuilder for InstanceGroupManagerMethods<'a, C, A> {} +impl<'a, C, A> MethodsBuilder for DiskTypeMethods<'a, C, A> {} -impl<'a, C, A> InstanceGroupManagerMethods<'a, C, A> { +impl<'a, C, A> DiskTypeMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Resizes the managed instance group. If you increase the size, the group creates new instances using the current instance template. If you decrease the size, the group removes instances in the order that is outlined in Resizing a managed instance group. + /// Returns the specified disk type resource. /// /// # Arguments /// - /// * `project` - The project ID for this request. - /// * `zone` - The URL of the zone where the managed instance group is located. - /// * `instanceGroupManager` - The name of the instance group manager. - /// * `size` - The number of running instances that the managed instance group should maintain at any given time. The group automatically adds or removes instances to maintain the number of instances specified by this parameter. - pub fn resize(&self, project: &str, zone: &str, instance_group_manager: &str, size: i32) -> InstanceGroupManagerResizeCall<'a, C, A> { - InstanceGroupManagerResizeCall { + /// * `project` - Project ID for this request. + /// * `zone` - The name of the zone for this request. + /// * `diskType` - Name of the disk type resource to return. + pub fn get(&self, project: &str, zone: &str, disk_type: &str) -> DiskTypeGetCall<'a, C, A> { + DiskTypeGetCall { hub: self.hub, _project: project.to_string(), _zone: zone.to_string(), - _instance_group_manager: instance_group_manager.to_string(), - _size: size, + _disk_type: disk_type.to_string(), _delegate: Default::default(), _scopes: Default::default(), _additional_params: Default::default(), @@ -5877,77 +6123,13 @@ impl<'a, C, A> InstanceGroupManagerMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Retrieves a list of managed instance groups that are contained within the specified project and zone. + /// Retrieves the list of disk type resources grouped by scope. /// /// # Arguments /// - /// * `project` - The project ID for this request. - /// * `zone` - The URL of the zone where the managed instance group is located. - pub fn list(&self, project: &str, zone: &str) -> InstanceGroupManagerListCall<'a, C, A> { - InstanceGroupManagerListCall { - 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: - /// - /// Lists managed instances. - /// - /// # Arguments - /// - /// * `project` - The project ID for this request. - /// * `zone` - The URL of the zone where the managed instance group is located. - /// * `instanceGroupManager` - The name of the managed instance group. - pub fn list_managed_instances(&self, project: &str, zone: &str, instance_group_manager: &str) -> InstanceGroupManagerListManagedInstanceCall<'a, C, A> { - InstanceGroupManagerListManagedInstanceCall { - hub: self.hub, - _project: project.to_string(), - _zone: zone.to_string(), - _instance_group_manager: instance_group_manager.to_string(), - _delegate: Default::default(), - _scopes: Default::default(), - _additional_params: Default::default(), - } - } - - /// Create a builder to help you perform the following task: - /// - /// Creates a managed instance group resource in the specified project using the data that is included in the request. - /// - /// # Arguments - /// - /// * `request` - No description provided. - /// * `project` - The project ID for this request. - /// * `zone` - The URL of the zone where the managed instance group is located. - pub fn insert(&self, request: InstanceGroupManager, project: &str, zone: &str) -> InstanceGroupManagerInsertCall<'a, C, A> { - InstanceGroupManagerInsertCall { - hub: self.hub, - _request: request, - _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 managed instance groups, and groups them by project and zone. - /// - /// # Arguments - /// - /// * `project` - The project ID for this request. - pub fn aggregated_list(&self, project: &str) -> InstanceGroupManagerAggregatedListCall<'a, C, A> { - InstanceGroupManagerAggregatedListCall { + /// * `project` - Project ID for this request. + pub fn aggregated_list(&self, project: &str) -> DiskTypeAggregatedListCall<'a, C, A> { + DiskTypeAggregatedListCall { hub: self.hub, _project: project.to_string(), _page_token: Default::default(), @@ -5961,155 +6143,20 @@ impl<'a, C, A> InstanceGroupManagerMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Deletes the specified instances. The instances are deleted and removed from the instance group and any target pools where they are a member. The managed instance group automatically reduces its targetSize value by the number of instances that you delete. + /// Retrieves the list of disk type resources available to the specified project. /// /// # Arguments /// - /// * `request` - No description provided. - /// * `project` - The project ID for this request. - /// * `zone` - The URL of the zone where the managed instance group is located. - /// * `instanceGroupManager` - The name of the instance group manager. - pub fn delete_instances(&self, request: InstanceGroupManagersDeleteInstancesRequest, project: &str, zone: &str, instance_group_manager: &str) -> InstanceGroupManagerDeleteInstanceCall<'a, C, A> { - InstanceGroupManagerDeleteInstanceCall { - hub: self.hub, - _request: request, - _project: project.to_string(), - _zone: zone.to_string(), - _instance_group_manager: instance_group_manager.to_string(), - _delegate: Default::default(), - _scopes: Default::default(), - _additional_params: Default::default(), - } - } - - /// Create a builder to help you perform the following task: - /// - /// Specifies the instance template to use when creating new instances in this group. The templates for existing instances in the group do not change unless you recreate them. - /// - /// # Arguments - /// - /// * `request` - No description provided. - /// * `project` - The project ID for this request. - /// * `zone` - The URL of the zone where the managed instance group is located. - /// * `instanceGroupManager` - The name of the instance group manager. - pub fn set_instance_template(&self, request: InstanceGroupManagersSetInstanceTemplateRequest, project: &str, zone: &str, instance_group_manager: &str) -> InstanceGroupManagerSetInstanceTemplateCall<'a, C, A> { - InstanceGroupManagerSetInstanceTemplateCall { - hub: self.hub, - _request: request, - _project: project.to_string(), - _zone: zone.to_string(), - _instance_group_manager: instance_group_manager.to_string(), - _delegate: Default::default(), - _scopes: Default::default(), - _additional_params: Default::default(), - } - } - - /// Create a builder to help you perform the following task: - /// - /// Modifies the target pools to which all new instances in this group are assigned. The target pools for existing instances in the group do not change unless you recreate them. - /// - /// # Arguments - /// - /// * `request` - No description provided. - /// * `project` - The project ID for this request. - /// * `zone` - The URL of the zone where the managed instance group is located. - /// * `instanceGroupManager` - The name of the instance group manager. - pub fn set_target_pools(&self, request: InstanceGroupManagersSetTargetPoolsRequest, project: &str, zone: &str, instance_group_manager: &str) -> InstanceGroupManagerSetTargetPoolCall<'a, C, A> { - InstanceGroupManagerSetTargetPoolCall { - hub: self.hub, - _request: request, - _project: project.to_string(), - _zone: zone.to_string(), - _instance_group_manager: instance_group_manager.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 managed instance group resource. - /// - /// # Arguments - /// - /// * `project` - The project ID for this request. - /// * `zone` - The URL of the zone where the managed instance group is located. - /// * `instanceGroupManager` - The name of the instance group manager to delete. - pub fn delete(&self, project: &str, zone: &str, instance_group_manager: &str) -> InstanceGroupManagerDeleteCall<'a, C, A> { - InstanceGroupManagerDeleteCall { + /// * `project` - Project ID for this request. + /// * `zone` - The name of the zone for this request. + pub fn list(&self, project: &str, zone: &str) -> DiskTypeListCall<'a, C, A> { + DiskTypeListCall { hub: self.hub, _project: project.to_string(), _zone: zone.to_string(), - _instance_group_manager: instance_group_manager.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 managed instance group resource. - /// - /// # Arguments - /// - /// * `project` - The project ID for this request. - /// * `zone` - The URL of the zone where the managed instance group is located. - /// * `instanceGroupManager` - The name of the instance group manager resource. - pub fn get(&self, project: &str, zone: &str, instance_group_manager: &str) -> InstanceGroupManagerGetCall<'a, C, A> { - InstanceGroupManagerGetCall { - hub: self.hub, - _project: project.to_string(), - _zone: zone.to_string(), - _instance_group_manager: instance_group_manager.to_string(), - _delegate: Default::default(), - _scopes: Default::default(), - _additional_params: Default::default(), - } - } - - /// Create a builder to help you perform the following task: - /// - /// Removes the specified instances from the managed instance group, and from any target pools where they are a member. The instances are not deleted. The managed instance group automatically reduces its targetSize value by the number of instances that you abandon from the group. - /// - /// # Arguments - /// - /// * `request` - No description provided. - /// * `project` - The project ID for this request. - /// * `zone` - The URL of the zone where the managed instance group is located. - /// * `instanceGroupManager` - The name of the instance group manager. - pub fn abandon_instances(&self, request: InstanceGroupManagersAbandonInstancesRequest, project: &str, zone: &str, instance_group_manager: &str) -> InstanceGroupManagerAbandonInstanceCall<'a, C, A> { - InstanceGroupManagerAbandonInstanceCall { - hub: self.hub, - _request: request, - _project: project.to_string(), - _zone: zone.to_string(), - _instance_group_manager: instance_group_manager.to_string(), - _delegate: Default::default(), - _scopes: Default::default(), - _additional_params: Default::default(), - } - } - - /// Create a builder to help you perform the following task: - /// - /// Recreates the specified instances. The instances are deleted, then recreated using the managed instance group's current instance template. - /// - /// # Arguments - /// - /// * `request` - No description provided. - /// * `project` - The project ID for this request. - /// * `zone` - The URL of the zone where the managed instance group is located. - /// * `instanceGroupManager` - The name of the instance group manager. - pub fn recreate_instances(&self, request: InstanceGroupManagersRecreateInstancesRequest, project: &str, zone: &str, instance_group_manager: &str) -> InstanceGroupManagerRecreateInstanceCall<'a, C, A> { - InstanceGroupManagerRecreateInstanceCall { - hub: self.hub, - _request: request, - _project: project.to_string(), - _zone: zone.to_string(), - _instance_group_manager: instance_group_manager.to_string(), + _page_token: Default::default(), + _max_results: Default::default(), + _filter: Default::default(), _delegate: Default::default(), _scopes: Default::default(), _additional_params: Default::default(), @@ -6404,7 +6451,7 @@ impl<'a, C, A> InstanceMethods<'a, C, A> { /// # Arguments /// /// * `project` - Project ID for this request. - /// * `zone` - The name of the The name of the zone for this request.. + /// * `zone` - The name of the zone for this request. /// * `instance` - Name of the instance resource to return. pub fn get(&self, project: &str, zone: &str, instance: &str) -> InstanceGetCall<'a, C, A> { InstanceGetCall { @@ -6597,6 +6644,9 @@ impl<'a, C, A> InstanceMethods<'a, C, A> { } } + /// Create a builder to help you perform the following task: + /// + /// Retrieves aggregated list of instance resources. /// /// # Arguments /// @@ -6838,7 +6888,9 @@ impl<'a, C, A> ImageMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Retrieves the list of image resources available to the specified project. + /// Retrieves the list of private images available to the specified project. Private images are images you create that belong to your project. This method does not get any images that belong to other projects, including publicly-available images, like Debian 7. If you want to get a list of publicly-available images, use this method to make a request to the respective image project, such as debian-cloud or windows-cloud. + /// + /// See Accessing images for more information. /// /// # Arguments /// @@ -6999,6 +7051,166 @@ impl<'a, C, A> LicenseMethods<'a, C, A> { +/// A builder providing access to all methods supported on *targetHttpsProxy* 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(...)`, `set_ssl_certificates(...)` and `set_url_map(...)` +/// // to build up your call. +/// let rb = hub.target_https_proxies(); +/// # } +/// ``` +pub struct TargetHttpsProxyMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Compute, +} + +impl<'a, C, A> MethodsBuilder for TargetHttpsProxyMethods<'a, C, A> {} + +impl<'a, C, A> TargetHttpsProxyMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Deletes the specified TargetHttpsProxy resource. + /// + /// # Arguments + /// + /// * `project` - Name of the project scoping this request. + /// * `targetHttpsProxy` - Name of the TargetHttpsProxy resource to delete. + pub fn delete(&self, project: &str, target_https_proxy: &str) -> TargetHttpsProxyDeleteCall<'a, C, A> { + TargetHttpsProxyDeleteCall { + hub: self.hub, + _project: project.to_string(), + _target_https_proxy: target_https_proxy.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 TargetHttpsProxy resource. + /// + /// # Arguments + /// + /// * `project` - Name of the project scoping this request. + /// * `targetHttpsProxy` - Name of the TargetHttpsProxy resource to return. + pub fn get(&self, project: &str, target_https_proxy: &str) -> TargetHttpsProxyGetCall<'a, C, A> { + TargetHttpsProxyGetCall { + hub: self.hub, + _project: project.to_string(), + _target_https_proxy: target_https_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 TargetHttpsProxy. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `project` - Name of the project scoping this request. + /// * `targetHttpsProxy` - Name of the TargetHttpsProxy resource whose URL map is to be set. + pub fn set_url_map(&self, request: UrlMapReference, project: &str, target_https_proxy: &str) -> TargetHttpsProxySetUrlMapCall<'a, C, A> { + TargetHttpsProxySetUrlMapCall { + hub: self.hub, + _request: request, + _project: project.to_string(), + _target_https_proxy: target_https_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 TargetHttpsProxy resource in the specified project using the data included in the request. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `project` - Name of the project scoping this request. + pub fn insert(&self, request: TargetHttpsProxy, project: &str) -> TargetHttpsProxyInsertCall<'a, C, A> { + TargetHttpsProxyInsertCall { + hub: self.hub, + _request: request, + _project: project.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Replaces SslCertificates for TargetHttpsProxy. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `project` - Name of the project scoping this request. + /// * `targetHttpsProxy` - Name of the TargetHttpsProxy resource whose URL map is to be set. + pub fn set_ssl_certificates(&self, request: TargetHttpsProxiesSetSslCertificatesRequest, project: &str, target_https_proxy: &str) -> TargetHttpsProxySetSslCertificateCall<'a, C, A> { + TargetHttpsProxySetSslCertificateCall { + hub: self.hub, + _request: request, + _project: project.to_string(), + _target_https_proxy: target_https_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 TargetHttpsProxy resources available to the specified project. + /// + /// # Arguments + /// + /// * `project` - Name of the project scoping this request. + pub fn list(&self, project: &str) -> TargetHttpsProxyListCall<'a, C, A> { + TargetHttpsProxyListCall { + 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 *network* resources. /// It is not used directly, but through the `Compute` hub. /// @@ -7467,12 +7679,12 @@ impl<'a, C, A> InstanceGroupMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Deletes the specified instance group. + /// Deletes the specified instance group. The instances in the group are not deleted. /// /// # Arguments /// /// * `project` - The project ID for this request. - /// * `zone` - The URL of the zone where the instance group is located. + /// * `zone` - The name of the zone where the instance group is located. /// * `instanceGroup` - The name of the instance group to delete. pub fn delete(&self, project: &str, zone: &str, instance_group: &str) -> InstanceGroupDeleteCall<'a, C, A> { InstanceGroupDeleteCall { @@ -7488,13 +7700,13 @@ impl<'a, C, A> InstanceGroupMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Lists instances in an instance group. The parameters for this method specify whether the list filters instances by state and named ports information. + /// Lists the instances in the specified instance group. /// /// # Arguments /// /// * `request` - No description provided. /// * `project` - The project ID for this request. - /// * `zone` - The URL of the zone where the instance group is located. + /// * `zone` - The name of the zone where the instance group is located. /// * `instanceGroup` - The name of the instance group from which you want to generate a list of included instances. pub fn list_instances(&self, request: InstanceGroupsListInstancesRequest, project: &str, zone: &str, instance_group: &str) -> InstanceGroupListInstanceCall<'a, C, A> { InstanceGroupListInstanceCall { @@ -7520,7 +7732,7 @@ impl<'a, C, A> InstanceGroupMethods<'a, C, A> { /// /// * `request` - No description provided. /// * `project` - The project ID for this request. - /// * `zone` - The URL of the zone where the instance group is located. + /// * `zone` - The name of the zone where you want to create the instance group. pub fn insert(&self, request: InstanceGroup, project: &str, zone: &str) -> InstanceGroupInsertCall<'a, C, A> { InstanceGroupInsertCall { hub: self.hub, @@ -7540,7 +7752,7 @@ impl<'a, C, A> InstanceGroupMethods<'a, C, A> { /// # Arguments /// /// * `project` - The project ID for this request. - /// * `zone` - The URL of the zone where the instance group is located. + /// * `zone` - The name of the zone where the instance group is located. /// * `instanceGroup` - The name of the instance group. pub fn get(&self, project: &str, zone: &str, instance_group: &str) -> InstanceGroupGetCall<'a, C, A> { InstanceGroupGetCall { @@ -7556,13 +7768,13 @@ impl<'a, C, A> InstanceGroupMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Removes a list of instances from an instance group. + /// Removes one or more instances from the specified instance group, but does not delete those instances. /// /// # Arguments /// /// * `request` - No description provided. /// * `project` - The project ID for this request. - /// * `zone` - The URL of the zone where the instance group is located. + /// * `zone` - The name of the zone where the instance group is located. /// * `instanceGroup` - The name of the instance group where the specified instances will be removed. pub fn remove_instances(&self, request: InstanceGroupsRemoveInstancesRequest, project: &str, zone: &str, instance_group: &str) -> InstanceGroupRemoveInstanceCall<'a, C, A> { InstanceGroupRemoveInstanceCall { @@ -7579,13 +7791,13 @@ impl<'a, C, A> InstanceGroupMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Adds a list of instances to an instance group. All of the instances in the instance group must be in the same network. + /// Adds a list of instances to the specified instance group. All of the instances in the instance group must be in the same network/subnetwork. TODO: Change to comment to state "if IG is load balanced." /// /// # Arguments /// /// * `request` - No description provided. /// * `project` - The project ID for this request. - /// * `zone` - The URL of the zone where the instance group is located. + /// * `zone` - The name of the zone where the instance group is located. /// * `instanceGroup` - The name of the instance group where you are adding instances. pub fn add_instances(&self, request: InstanceGroupsAddInstancesRequest, project: &str, zone: &str, instance_group: &str) -> InstanceGroupAddInstanceCall<'a, C, A> { InstanceGroupAddInstanceCall { @@ -7602,13 +7814,13 @@ impl<'a, C, A> InstanceGroupMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Sets the named ports in an instance group. + /// Sets the named ports for the specified instance group. /// /// # Arguments /// /// * `request` - No description provided. /// * `project` - The project ID for this request. - /// * `zone` - The URL of the zone where the instance group is located. + /// * `zone` - The name of the zone where the instance group is located. /// * `instanceGroup` - The name of the instance group where the named ports are updated. pub fn set_named_ports(&self, request: InstanceGroupsSetNamedPortsRequest, project: &str, zone: &str, instance_group: &str) -> InstanceGroupSetNamedPortCall<'a, C, A> { InstanceGroupSetNamedPortCall { @@ -7625,7 +7837,7 @@ impl<'a, C, A> InstanceGroupMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Retrieves the list of instance groups, and sorts them by zone. + /// Retrieves the list of instance groups and sorts them by zone. /// /// # Arguments /// @@ -7650,7 +7862,7 @@ impl<'a, C, A> InstanceGroupMethods<'a, C, A> { /// # Arguments /// /// * `project` - The project ID for this request. - /// * `zone` - The URL of the zone where the instance group is located. + /// * `zone` - The name of the zone where the instance group is located. pub fn list(&self, project: &str, zone: &str) -> InstanceGroupListCall<'a, C, A> { InstanceGroupListCall { hub: self.hub, @@ -8487,6 +8699,166 @@ impl<'a, C, A> GlobalForwardingRuleMethods<'a, C, A> { +/// A builder providing access to all methods supported on *httpsHealthCheck* 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.https_health_checks(); +/// # } +/// ``` +pub struct HttpsHealthCheckMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Compute, +} + +impl<'a, C, A> MethodsBuilder for HttpsHealthCheckMethods<'a, C, A> {} + +impl<'a, C, A> HttpsHealthCheckMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Deletes the specified HttpsHealthCheck resource. + /// + /// # Arguments + /// + /// * `project` - Name of the project scoping this request. + /// * `httpsHealthCheck` - Name of the HttpsHealthCheck resource to delete. + pub fn delete(&self, project: &str, https_health_check: &str) -> HttpsHealthCheckDeleteCall<'a, C, A> { + HttpsHealthCheckDeleteCall { + hub: self.hub, + _project: project.to_string(), + _https_health_check: https_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 HttpsHealthCheck resources available to the specified project. + /// + /// # Arguments + /// + /// * `project` - Name of the project scoping this request. + pub fn list(&self, project: &str) -> HttpsHealthCheckListCall<'a, C, A> { + HttpsHealthCheckListCall { + 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 HttpsHealthCheck resource in the specified project using the data included in the request. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `project` - Name of the project scoping this request. + pub fn insert(&self, request: HttpsHealthCheck, project: &str) -> HttpsHealthCheckInsertCall<'a, C, A> { + HttpsHealthCheckInsertCall { + hub: self.hub, + _request: request, + _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 HttpsHealthCheck resource. + /// + /// # Arguments + /// + /// * `project` - Name of the project scoping this request. + /// * `httpsHealthCheck` - Name of the HttpsHealthCheck resource to return. + pub fn get(&self, project: &str, https_health_check: &str) -> HttpsHealthCheckGetCall<'a, C, A> { + HttpsHealthCheckGetCall { + hub: self.hub, + _project: project.to_string(), + _https_health_check: https_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 HttpsHealthCheck resource in the specified project using the data included in the request. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `project` - Name of the project scoping this request. + /// * `httpsHealthCheck` - Name of the HttpsHealthCheck resource to update. + pub fn update(&self, request: HttpsHealthCheck, project: &str, https_health_check: &str) -> HttpsHealthCheckUpdateCall<'a, C, A> { + HttpsHealthCheckUpdateCall { + hub: self.hub, + _request: request, + _project: project.to_string(), + _https_health_check: https_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 HttpsHealthCheck resource in the specified project using the data included in the request. This method supports patch semantics. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `project` - Name of the project scoping this request. + /// * `httpsHealthCheck` - Name of the HttpsHealthCheck resource to update. + pub fn patch(&self, request: HttpsHealthCheck, project: &str, https_health_check: &str) -> HttpsHealthCheckPatchCall<'a, C, A> { + HttpsHealthCheckPatchCall { + hub: self.hub, + _request: request, + _project: project.to_string(), + _https_health_check: https_health_check.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. /// @@ -8737,7 +9109,7 @@ impl<'a, C, A> TargetVpnGatewayMethods<'a, C, A> { -/// A builder providing access to all methods supported on *diskType* resources. +/// A builder providing access to all methods supported on *instanceGroupManager* resources. /// It is not used directly, but through the `Compute` hub. /// /// # Example @@ -8760,36 +9132,38 @@ impl<'a, C, A> TargetVpnGatewayMethods<'a, C, A> { /// ::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(...)` +/// // like `abandon_instances(...)`, `aggregated_list(...)`, `delete(...)`, `delete_instances(...)`, `get(...)`, `insert(...)`, `list(...)`, `list_managed_instances(...)`, `recreate_instances(...)`, `resize(...)`, `set_instance_template(...)` and `set_target_pools(...)` /// // to build up your call. -/// let rb = hub.disk_types(); +/// let rb = hub.instance_group_managers(); /// # } /// ``` -pub struct DiskTypeMethods<'a, C, A> +pub struct InstanceGroupManagerMethods<'a, C, A> where C: 'a, A: 'a { hub: &'a Compute, } -impl<'a, C, A> MethodsBuilder for DiskTypeMethods<'a, C, A> {} +impl<'a, C, A> MethodsBuilder for InstanceGroupManagerMethods<'a, C, A> {} -impl<'a, C, A> DiskTypeMethods<'a, C, A> { +impl<'a, C, A> InstanceGroupManagerMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Returns the specified disk type resource. + /// Resizes the managed instance group. If you increase the size, the group creates new instances using the current instance template. If you decrease the size, the group deletes instances. The resize operation is marked DONE when the resize actions are scheduled even if the group has not yet added or deleted any instances. You must separately verify the status of the creating or deleting actions with the listmanagedinstances method. /// /// # Arguments /// - /// * `project` - Project ID for this request. - /// * `zone` - The name of the zone for this request. - /// * `diskType` - Name of the disk type resource to return. - pub fn get(&self, project: &str, zone: &str, disk_type: &str) -> DiskTypeGetCall<'a, C, A> { - DiskTypeGetCall { + /// * `project` - The project ID for this request. + /// * `zone` - The name of the zone where the managed instance group is located. + /// * `instanceGroupManager` - The name of the managed instance group. + /// * `size` - The number of running instances that the managed instance group should maintain at any given time. The group automatically adds or removes instances to maintain the number of instances specified by this parameter. + pub fn resize(&self, project: &str, zone: &str, instance_group_manager: &str, size: i32) -> InstanceGroupManagerResizeCall<'a, C, A> { + InstanceGroupManagerResizeCall { hub: self.hub, _project: project.to_string(), _zone: zone.to_string(), - _disk_type: disk_type.to_string(), + _instance_group_manager: instance_group_manager.to_string(), + _size: size, _delegate: Default::default(), _scopes: Default::default(), _additional_params: Default::default(), @@ -8798,13 +9172,77 @@ impl<'a, C, A> DiskTypeMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Retrieves the list of disk type resources grouped by scope. + /// Retrieves a list of managed instance groups that are contained within the specified project and zone. /// /// # Arguments /// - /// * `project` - Project ID for this request. - pub fn aggregated_list(&self, project: &str) -> DiskTypeAggregatedListCall<'a, C, A> { - DiskTypeAggregatedListCall { + /// * `project` - The project ID for this request. + /// * `zone` - The name of the zone where the managed instance group is located. + pub fn list(&self, project: &str, zone: &str) -> InstanceGroupManagerListCall<'a, C, A> { + InstanceGroupManagerListCall { + 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: + /// + /// Lists all of the instances in the managed instance group. Each instance in the list has a currentAction, which indicates the action that the managed instance group is performing on the instance. For example, if the group is still creating an instance, the currentAction is CREATING. If a previous action failed, the list displays the errors for that failed action. + /// + /// # Arguments + /// + /// * `project` - The project ID for this request. + /// * `zone` - The name of the zone where the managed instance group is located. + /// * `instanceGroupManager` - The name of the managed instance group. + pub fn list_managed_instances(&self, project: &str, zone: &str, instance_group_manager: &str) -> InstanceGroupManagerListManagedInstanceCall<'a, C, A> { + InstanceGroupManagerListManagedInstanceCall { + hub: self.hub, + _project: project.to_string(), + _zone: zone.to_string(), + _instance_group_manager: instance_group_manager.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Creates a managed instance group using the information that you specify in the request. After the group is created, it schedules an action to create instances in the group using the specified instance template. This operation is marked as DONE when the group is created even if the instances in the group have not yet been created. You must separately verify the status of the individual instances with the listmanagedinstances method. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `project` - The project ID for this request. + /// * `zone` - The name of the zone where you want to create the managed instance group. + pub fn insert(&self, request: InstanceGroupManager, project: &str, zone: &str) -> InstanceGroupManagerInsertCall<'a, C, A> { + InstanceGroupManagerInsertCall { + hub: self.hub, + _request: request, + _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 managed instance groups and groups them by zone. + /// + /// # Arguments + /// + /// * `project` - The project ID for this request. + pub fn aggregated_list(&self, project: &str) -> InstanceGroupManagerAggregatedListCall<'a, C, A> { + InstanceGroupManagerAggregatedListCall { hub: self.hub, _project: project.to_string(), _page_token: Default::default(), @@ -8818,20 +9256,155 @@ impl<'a, C, A> DiskTypeMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Retrieves the list of disk type resources available to the specified project. + /// Schedules a group action to delete the specified instances in the managed instance group. The instances are also removed from any target pools of which they were a member. This method reduces the targetSize of the managed instance group by the number of instances that you delete. This operation is marked as DONE when the action is scheduled even if the instances are still being deleted. You must separately verify the status of the deleting action with the listmanagedinstances method. /// /// # Arguments /// - /// * `project` - Project ID for this request. - /// * `zone` - The name of the zone for this request. - pub fn list(&self, project: &str, zone: &str) -> DiskTypeListCall<'a, C, A> { - DiskTypeListCall { + /// * `request` - No description provided. + /// * `project` - The project ID for this request. + /// * `zone` - The name of the zone where the managed instance group is located. + /// * `instanceGroupManager` - The name of the managed instance group. + pub fn delete_instances(&self, request: InstanceGroupManagersDeleteInstancesRequest, project: &str, zone: &str, instance_group_manager: &str) -> InstanceGroupManagerDeleteInstanceCall<'a, C, A> { + InstanceGroupManagerDeleteInstanceCall { + hub: self.hub, + _request: request, + _project: project.to_string(), + _zone: zone.to_string(), + _instance_group_manager: instance_group_manager.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Specifies the instance template to use when creating new instances in this group. The templates for existing instances in the group do not change unless you recreate them. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `project` - The project ID for this request. + /// * `zone` - The name of the zone where the managed instance group is located. + /// * `instanceGroupManager` - The name of the managed instance group. + pub fn set_instance_template(&self, request: InstanceGroupManagersSetInstanceTemplateRequest, project: &str, zone: &str, instance_group_manager: &str) -> InstanceGroupManagerSetInstanceTemplateCall<'a, C, A> { + InstanceGroupManagerSetInstanceTemplateCall { + hub: self.hub, + _request: request, + _project: project.to_string(), + _zone: zone.to_string(), + _instance_group_manager: instance_group_manager.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Modifies the target pools to which all instances in this managed instance group are assigned. The target pools automatically apply to all of the instances in the managed instance group. This operation is marked DONE when you make the request even if the instances have not yet been added to their target pools. The change might take some time to apply to all of the instances in the group depending on the size of the group. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `project` - The project ID for this request. + /// * `zone` - The name of the zone where the managed instance group is located. + /// * `instanceGroupManager` - The name of the managed instance group. + pub fn set_target_pools(&self, request: InstanceGroupManagersSetTargetPoolsRequest, project: &str, zone: &str, instance_group_manager: &str) -> InstanceGroupManagerSetTargetPoolCall<'a, C, A> { + InstanceGroupManagerSetTargetPoolCall { + hub: self.hub, + _request: request, + _project: project.to_string(), + _zone: zone.to_string(), + _instance_group_manager: instance_group_manager.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 managed instance group and all of the instances in that group. + /// + /// # Arguments + /// + /// * `project` - The project ID for this request. + /// * `zone` - The name of the zone where the managed instance group is located. + /// * `instanceGroupManager` - The name of the managed instance group to delete. + pub fn delete(&self, project: &str, zone: &str, instance_group_manager: &str) -> InstanceGroupManagerDeleteCall<'a, C, A> { + InstanceGroupManagerDeleteCall { hub: self.hub, _project: project.to_string(), _zone: zone.to_string(), - _page_token: Default::default(), - _max_results: Default::default(), - _filter: Default::default(), + _instance_group_manager: instance_group_manager.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 details about the specified managed instance group. + /// + /// # Arguments + /// + /// * `project` - The project ID for this request. + /// * `zone` - The name of the zone where the managed instance group is located. + /// * `instanceGroupManager` - The name of the managed instance group. + pub fn get(&self, project: &str, zone: &str, instance_group_manager: &str) -> InstanceGroupManagerGetCall<'a, C, A> { + InstanceGroupManagerGetCall { + hub: self.hub, + _project: project.to_string(), + _zone: zone.to_string(), + _instance_group_manager: instance_group_manager.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Schedules a group action to remove the specified instances from the managed instance group. Abandoning an instance does not delete the instance, but it does remove the instance from any target pools that are applied by the managed instance group. This method reduces the targetSize of the managed instance group by the number of instances that you abandon. This operation is marked as DONE when the action is scheduled even if the instances have not yet been removed from the group. You must separately verify the status of the abandoning action with the listmanagedinstances method. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `project` - The project ID for this request. + /// * `zone` - The name of the zone where the managed instance group is located. + /// * `instanceGroupManager` - The name of the managed instance group. + pub fn abandon_instances(&self, request: InstanceGroupManagersAbandonInstancesRequest, project: &str, zone: &str, instance_group_manager: &str) -> InstanceGroupManagerAbandonInstanceCall<'a, C, A> { + InstanceGroupManagerAbandonInstanceCall { + hub: self.hub, + _request: request, + _project: project.to_string(), + _zone: zone.to_string(), + _instance_group_manager: instance_group_manager.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Schedules a group action to recreate the specified instances in the managed instance group. The instances are deleted and recreated using the current instance template for the managed instance group. This operation is marked as DONE when the action is scheduled even if the instances have not yet been recreated. You must separately verify the status of the recreating action with the listmanagedinstances method. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `project` - The project ID for this request. + /// * `zone` - The name of the zone where the managed instance group is located. + /// * `instanceGroupManager` - The name of the managed instance group. + pub fn recreate_instances(&self, request: InstanceGroupManagersRecreateInstancesRequest, project: &str, zone: &str, instance_group_manager: &str) -> InstanceGroupManagerRecreateInstanceCall<'a, C, A> { + InstanceGroupManagerRecreateInstanceCall { + hub: self.hub, + _request: request, + _project: project.to_string(), + _zone: zone.to_string(), + _instance_group_manager: instance_group_manager.to_string(), _delegate: Default::default(), _scopes: Default::default(), _additional_params: Default::default(), @@ -9392,6 +9965,124 @@ impl<'a, C, A> TargetHttpProxyMethods<'a, C, A> { +/// A builder providing access to all methods supported on *sslCertificate* 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.ssl_certificates(); +/// # } +/// ``` +pub struct SslCertificateMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Compute, +} + +impl<'a, C, A> MethodsBuilder for SslCertificateMethods<'a, C, A> {} + +impl<'a, C, A> SslCertificateMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Deletes the specified SslCertificate resource. + /// + /// # Arguments + /// + /// * `project` - Name of the project scoping this request. + /// * `sslCertificate` - Name of the SslCertificate resource to delete. + pub fn delete(&self, project: &str, ssl_certificate: &str) -> SslCertificateDeleteCall<'a, C, A> { + SslCertificateDeleteCall { + hub: self.hub, + _project: project.to_string(), + _ssl_certificate: ssl_certificate.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 SslCertificate resources available to the specified project. + /// + /// # Arguments + /// + /// * `project` - Name of the project scoping this request. + pub fn list(&self, project: &str) -> SslCertificateListCall<'a, C, A> { + SslCertificateListCall { + 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 SslCertificate resource in the specified project using the data included in the request. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `project` - Name of the project scoping this request. + pub fn insert(&self, request: SslCertificate, project: &str) -> SslCertificateInsertCall<'a, C, A> { + SslCertificateInsertCall { + hub: self.hub, + _request: request, + _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 SslCertificate resource. + /// + /// # Arguments + /// + /// * `project` - Name of the project scoping this request. + /// * `sslCertificate` - Name of the SslCertificate resource to return. + pub fn get(&self, project: &str, ssl_certificate: &str) -> SslCertificateGetCall<'a, C, A> { + SslCertificateGetCall { + hub: self.hub, + _project: project.to_string(), + _ssl_certificate: ssl_certificate.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. /// @@ -9813,27 +10504,6 @@ impl<'a, C, A> MethodsBuilder for VpnTunnelMethods<'a, C, A> {} impl<'a, C, A> VpnTunnelMethods<'a, C, A> { - /// Create a builder to help you perform the following task: - /// - /// Deletes the specified VpnTunnel resource. - /// - /// # Arguments - /// - /// * `project` - Project ID for this request. - /// * `region` - The name of the region for this request. - /// * `vpnTunnel` - Name of the VpnTunnel resource to delete. - pub fn delete(&self, project: &str, region: &str, vpn_tunnel: &str) -> VpnTunnelDeleteCall<'a, C, A> { - VpnTunnelDeleteCall { - hub: self.hub, - _project: project.to_string(), - _region: region.to_string(), - _vpn_tunnel: vpn_tunnel.to_string(), - _delegate: Default::default(), - _scopes: Default::default(), - _additional_params: Default::default(), - } - } - /// Create a builder to help you perform the following task: /// /// Creates a VpnTunnel resource in the specified project and region using the data included in the request. @@ -9855,6 +10525,27 @@ impl<'a, C, A> VpnTunnelMethods<'a, C, A> { } } + /// Create a builder to help you perform the following task: + /// + /// Deletes the specified VpnTunnel resource. + /// + /// # Arguments + /// + /// * `project` - Project ID for this request. + /// * `region` - The name of the region for this request. + /// * `vpnTunnel` - Name of the VpnTunnel resource to delete. + pub fn delete(&self, project: &str, region: &str, vpn_tunnel: &str) -> VpnTunnelDeleteCall<'a, C, A> { + VpnTunnelDeleteCall { + hub: self.hub, + _project: project.to_string(), + _region: region.to_string(), + _vpn_tunnel: vpn_tunnel.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 VpnTunnel resource. @@ -10505,14 +11196,11 @@ impl<'a, C, A> DiskAggregatedListCall<'a, C, A> where C: BorrowMut DiskAggregatedListCall<'a, C, A> { @@ -11056,14 +11744,11 @@ impl<'a, C, A> DiskListCall<'a, C, A> where C: BorrowMut, A: oaut self._max_results = Some(new_value); self } - /// Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must contain the following: - /// FIELD_NAME COMPARISON_STRING LITERAL_STRING - /// - /// - FIELD_NAME: The name of the field you want to compare. The field name must be valid for the type of resource being filtered. Only atomic field types are supported (string, number, boolean). Array and object fields are not currently supported. - /// - COMPARISON_STRING: The comparison string, either eq (equals) or ne (not equals). - /// - LITERAL_STRING: The literal string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field. For example, you can filter by the name of a resource: - /// filter=name ne example-instance - /// The above filter returns only results whose name field does not equal example-instance. You can also enclose your literal string in single, double, or no quotes. + /// Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must be in the format: FIELD_NAME COMPARISON_STRING LITERAL_STRING. + /// + /// The FIELD_NAME is the name of the field you want to compare. Only atomic field types are supported (string, number, boolean). The COMPARISON_STRING must be either eq (equals) or ne (not equals). The LITERAL_STRING is the string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field. + /// + /// For example, filter=name ne example-instance. /// /// Sets the *filter* query property to the given value. pub fn filter(mut self, new_value: &str) -> DiskListCall<'a, C, A> { @@ -11929,14 +12614,11 @@ impl<'a, C, A> AddresseListCall<'a, C, A> where C: BorrowMut, A: self._max_results = Some(new_value); self } - /// Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must contain the following: - /// FIELD_NAME COMPARISON_STRING LITERAL_STRING - /// - /// - FIELD_NAME: The name of the field you want to compare. The field name must be valid for the type of resource being filtered. Only atomic field types are supported (string, number, boolean). Array and object fields are not currently supported. - /// - COMPARISON_STRING: The comparison string, either eq (equals) or ne (not equals). - /// - LITERAL_STRING: The literal string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field. For example, you can filter by the name of a resource: - /// filter=name ne example-instance - /// The above filter returns only results whose name field does not equal example-instance. You can also enclose your literal string in single, double, or no quotes. + /// Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must be in the format: FIELD_NAME COMPARISON_STRING LITERAL_STRING. + /// + /// The FIELD_NAME is the name of the field you want to compare. Only atomic field types are supported (string, number, boolean). The COMPARISON_STRING must be either eq (equals) or ne (not equals). The LITERAL_STRING is the string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field. + /// + /// For example, filter=name ne example-instance. /// /// Sets the *filter* query property to the given value. pub fn filter(mut self, new_value: &str) -> AddresseListCall<'a, C, A> { @@ -12208,14 +12890,11 @@ impl<'a, C, A> AddresseAggregatedListCall<'a, C, A> where C: BorrowMut AddresseAggregatedListCall<'a, C, A> { @@ -14080,14 +14759,11 @@ impl<'a, C, A> UrlMapListCall<'a, C, A> where C: BorrowMut, A: oa self._max_results = Some(new_value); self } - /// Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must contain the following: - /// FIELD_NAME COMPARISON_STRING LITERAL_STRING - /// - /// - FIELD_NAME: The name of the field you want to compare. The field name must be valid for the type of resource being filtered. Only atomic field types are supported (string, number, boolean). Array and object fields are not currently supported. - /// - COMPARISON_STRING: The comparison string, either eq (equals) or ne (not equals). - /// - LITERAL_STRING: The literal string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field. For example, you can filter by the name of a resource: - /// filter=name ne example-instance - /// The above filter returns only results whose name field does not equal example-instance. You can also enclose your literal string in single, double, or no quotes. + /// Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must be in the format: FIELD_NAME COMPARISON_STRING LITERAL_STRING. + /// + /// The FIELD_NAME is the name of the field you want to compare. Only atomic field types are supported (string, number, boolean). The COMPARISON_STRING must be either eq (equals) or ne (not equals). The LITERAL_STRING is the string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field. + /// + /// For example, filter=name ne example-instance. /// /// Sets the *filter* query property to the given value. pub fn filter(mut self, new_value: &str) -> UrlMapListCall<'a, C, A> { @@ -15432,14 +16108,11 @@ impl<'a, C, A> GlobalAddresseListCall<'a, C, A> where C: BorrowMut GlobalAddresseListCall<'a, C, A> { @@ -16455,14 +17128,11 @@ impl<'a, C, A> SnapshotListCall<'a, C, A> where C: BorrowMut, A: self._max_results = Some(new_value); self } - /// Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must contain the following: - /// FIELD_NAME COMPARISON_STRING LITERAL_STRING - /// - /// - FIELD_NAME: The name of the field you want to compare. The field name must be valid for the type of resource being filtered. Only atomic field types are supported (string, number, boolean). Array and object fields are not currently supported. - /// - COMPARISON_STRING: The comparison string, either eq (equals) or ne (not equals). - /// - LITERAL_STRING: The literal string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field. For example, you can filter by the name of a resource: - /// filter=name ne example-instance - /// The above filter returns only results whose name field does not equal example-instance. You can also enclose your literal string in single, double, or no quotes. + /// Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must be in the format: FIELD_NAME COMPARISON_STRING LITERAL_STRING. + /// + /// The FIELD_NAME is the name of the field you want to compare. Only atomic field types are supported (string, number, boolean). The COMPARISON_STRING must be either eq (equals) or ne (not equals). The LITERAL_STRING is the string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field. + /// + /// For example, filter=name ne example-instance. /// /// Sets the *filter* query property to the given value. pub fn filter(mut self, new_value: &str) -> SnapshotListCall<'a, C, A> { @@ -16771,10 +17441,10 @@ impl<'a, C, A> SnapshotDeleteCall<'a, C, A> where C: BorrowMut, A } -/// Resizes the managed instance group. If you increase the size, the group creates new instances using the current instance template. If you decrease the size, the group removes instances in the order that is outlined in Resizing a managed instance group. +/// Returns the specified disk type resource. /// -/// A builder for the *resize* method supported by a *instanceGroupManager* resource. -/// It is not used directly, but through a `InstanceGroupManagerMethods` instance. +/// A builder for the *get* method supported by a *diskType* resource. +/// It is not used directly, but through a `DiskTypeMethods` instance. /// /// # Example /// @@ -16797,30 +17467,29 @@ impl<'a, C, A> SnapshotDeleteCall<'a, C, A> where C: BorrowMut, A /// // You can configure optional parameters by calling 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_group_managers().resize("project", "zone", "instanceGroupManager", -82) +/// let result = hub.disk_types().get("project", "zone", "diskType") /// .doit(); /// # } /// ``` -pub struct InstanceGroupManagerResizeCall<'a, C, A> +pub struct DiskTypeGetCall<'a, C, A> where C: 'a, A: 'a { hub: &'a Compute, _project: String, _zone: String, - _instance_group_manager: String, - _size: i32, + _disk_type: String, _delegate: Option<&'a mut Delegate>, _additional_params: HashMap, _scopes: BTreeMap } -impl<'a, C, A> CallBuilder for InstanceGroupManagerResizeCall<'a, C, A> {} +impl<'a, C, A> CallBuilder for DiskTypeGetCall<'a, C, A> {} -impl<'a, C, A> InstanceGroupManagerResizeCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { +impl<'a, C, A> DiskTypeGetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { /// Perform the operation you have build so far. - pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + 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; @@ -16828,14 +17497,13 @@ impl<'a, C, A> InstanceGroupManagerResizeCall<'a, C, A> where C: BorrowMut d, None => &mut dd }; - dlg.begin(MethodInfo { id: "compute.instanceGroupManagers.resize", - http_method: hyper::method::Method::Post }); - let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + 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(("instanceGroupManager", self._instance_group_manager.to_string())); - params.push(("size", self._size.to_string())); - for &field in ["alt", "project", "zone", "instanceGroupManager", "size"].iter() { + 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 Err(Error::FieldClash(field)); @@ -16847,12 +17515,12 @@ impl<'a, C, A> InstanceGroupManagerResizeCall<'a, C, A> where C: BorrowMut = None; for &(name, ref value) in params.iter() { if name == param_name { @@ -16864,290 +17532,7 @@ impl<'a, C, A> InstanceGroupManagerResizeCall<'a, C, A> where C: BorrowMut = Vec::with_capacity(3); - for param_name in ["instanceGroupManager", "zone", "project"].iter() { - if let Some(index) = params.iter().position(|t| &t.0 == param_name) { - indices_for_removal.push(index); - } - } - for &index in indices_for_removal.iter() { - params.remove(index); - } - } - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_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) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = { - let mut json_response = String::new(); - res.read_to_string(&mut json_response).unwrap(); - match json::from_str(&json_response) { - Ok(decoded) => (res, decoded), - Err(err) => { - dlg.response_json_decode_error(&json_response, &err); - return Err(Error::JsonDecodeError(json_response, err)); - } - } - }; - - dlg.finished(true); - return Ok(result_value) - } - } - } - } - - - /// The project ID for this request. - /// - /// 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) -> InstanceGroupManagerResizeCall<'a, C, A> { - self._project = new_value.to_string(); - self - } - /// The URL of the zone where the managed instance group is located. - /// - /// 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) -> InstanceGroupManagerResizeCall<'a, C, A> { - self._zone = new_value.to_string(); - self - } - /// The name of the instance group manager. - /// - /// Sets the *instance group manager* path property to the given value. - /// - /// Even though the property as already been set when instantiating this call, - /// we provide this method for API completeness. - pub fn instance_group_manager(mut self, new_value: &str) -> InstanceGroupManagerResizeCall<'a, C, A> { - self._instance_group_manager = new_value.to_string(); - self - } - /// The number of running instances that the managed instance group should maintain at any given time. The group automatically adds or removes instances to maintain the number of instances specified by this parameter. - /// - /// Sets the *size* 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. - pub fn size(mut self, new_value: i32) -> InstanceGroupManagerResizeCall<'a, C, A> { - self._size = new_value; - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> InstanceGroupManagerResizeCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. - /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. - /// * *alt* (query-string) - Data format for the response. - pub fn param(mut self, name: T, value: T) -> InstanceGroupManagerResizeCall<'a, C, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::CloudPlatform`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be - /// sufficient, a read-write scope will do as well. - pub fn add_scope(mut self, scope: T) -> InstanceGroupManagerResizeCall<'a, C, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().to_string(), ()); - self - } -} - - -/// Retrieves a list of managed instance groups that are contained within the specified project and zone. -/// -/// A builder for the *list* method supported by a *instanceGroupManager* resource. -/// It is not used directly, but through a `InstanceGroupManagerMethods` instance. -/// -/// # 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_group_managers().list("project", "zone") -/// .page_token("clita") -/// .max_results(56) -/// .filter("takimata") -/// .doit(); -/// # } -/// ``` -pub struct InstanceGroupManagerListCall<'a, C, A> - where C: '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, A> CallBuilder for InstanceGroupManagerListCall<'a, C, A> {} - -impl<'a, C, A> InstanceGroupManagerListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { - - - /// Perform the operation you have build so far. - pub fn doit(mut self) -> Result<(hyper::client::Response, InstanceGroupManagerList)> { - use std::io::{Read, Seek}; - use hyper::header::{ContentType, ContentLength, Authorization, 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.instanceGroupManagers.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 Err(Error::FieldClash(field)); - } - } - for (name, 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}/instanceGroupManagers".to_string(); - if self._scopes.len() == 0 { - self._scopes.insert(Scope::Readonly.as_ref().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 ["zone", "project"].iter() { + for param_name in ["diskType", "zone", "project"].iter() { if let Some(index) = params.iter().position(|t| &t.0 == param_name) { indices_for_removal.push(index); } @@ -17234,52 +17619,34 @@ impl<'a, C, A> InstanceGroupManagerListCall<'a, C, A> where C: BorrowMut InstanceGroupManagerListCall<'a, C, A> { + pub fn project(mut self, new_value: &str) -> DiskTypeGetCall<'a, C, A> { self._project = new_value.to_string(); self } - /// The URL of the zone where the managed instance group is located. + /// The name of the zone for this request. /// /// 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) -> InstanceGroupManagerListCall<'a, C, A> { + pub fn zone(mut self, new_value: &str) -> DiskTypeGetCall<'a, C, A> { self._zone = new_value.to_string(); self } - /// Specifies a page token to use. Use this parameter if you want to list the next page of results. Set pageToken to the nextPageToken returned by a previous list request. + /// Name of the disk type resource to return. /// - /// Sets the *page token* query property to the given value. - pub fn page_token(mut self, new_value: &str) -> InstanceGroupManagerListCall<'a, C, A> { - self._page_token = Some(new_value.to_string()); - self - } - /// Maximum count of results to be returned. + /// Sets the *disk type* path property to the given value. /// - /// Sets the *max results* query property to the given value. - pub fn max_results(mut self, new_value: u32) -> InstanceGroupManagerListCall<'a, C, A> { - self._max_results = Some(new_value); - self - } - /// Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must contain the following: - /// FIELD_NAME COMPARISON_STRING LITERAL_STRING - /// - /// - FIELD_NAME: The name of the field you want to compare. The field name must be valid for the type of resource being filtered. Only atomic field types are supported (string, number, boolean). Array and object fields are not currently supported. - /// - COMPARISON_STRING: The comparison string, either eq (equals) or ne (not equals). - /// - LITERAL_STRING: The literal string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field. For example, you can filter by the name of a resource: - /// filter=name ne example-instance - /// The above filter returns only results whose name field does not equal example-instance. You can also enclose your literal string in single, double, or no quotes. - /// - /// Sets the *filter* query property to the given value. - pub fn filter(mut self, new_value: &str) -> InstanceGroupManagerListCall<'a, C, A> { - self._filter = Some(new_value.to_string()); + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn disk_type(mut self, new_value: &str) -> DiskTypeGetCall<'a, C, A> { + self._disk_type = new_value.to_string(); self } /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong @@ -17288,7 +17655,7 @@ impl<'a, C, A> InstanceGroupManagerListCall<'a, C, A> where C: BorrowMut InstanceGroupManagerListCall<'a, C, A> { + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DiskTypeGetCall<'a, C, A> { self._delegate = Some(new_value); self } @@ -17309,7 +17676,7 @@ impl<'a, C, A> InstanceGroupManagerListCall<'a, C, A> where C: BorrowMut(mut self, name: T, value: T) -> InstanceGroupManagerListCall<'a, C, A> + pub fn param(mut self, name: T, value: T) -> DiskTypeGetCall<'a, C, A> where T: AsRef { self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); self @@ -17326,7 +17693,7 @@ impl<'a, C, A> InstanceGroupManagerListCall<'a, C, A> where C: BorrowMut(mut self, scope: T) -> InstanceGroupManagerListCall<'a, C, A> + pub fn add_scope(mut self, scope: T) -> DiskTypeGetCall<'a, C, A> where T: AsRef { self._scopes.insert(scope.as_ref().to_string(), ()); self @@ -17334,10 +17701,10 @@ impl<'a, C, A> InstanceGroupManagerListCall<'a, C, A> where C: BorrowMut InstanceGroupManagerListCall<'a, C, A> where C: BorrowMut - where C: 'a, A: 'a { - - hub: &'a Compute, - _project: String, - _zone: String, - _instance_group_manager: String, - _delegate: Option<&'a mut Delegate>, - _additional_params: HashMap, - _scopes: BTreeMap -} - -impl<'a, C, A> CallBuilder for InstanceGroupManagerListManagedInstanceCall<'a, C, A> {} - -impl<'a, C, A> InstanceGroupManagerListManagedInstanceCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { - - - /// Perform the operation you have build so far. - pub fn doit(mut self) -> Result<(hyper::client::Response, InstanceGroupManagersListManagedInstancesResponse)> { - use std::io::{Read, Seek}; - use hyper::header::{ContentType, ContentLength, Authorization, 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.instanceGroupManagers.listManagedInstances", - 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(("instanceGroupManager", self._instance_group_manager.to_string())); - for &field in ["alt", "project", "zone", "instanceGroupManager"].iter() { - if self._additional_params.contains_key(field) { - dlg.finished(false); - return Err(Error::FieldClash(field)); - } - } - for (name, 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}/instanceGroupManagers/{instanceGroupManager}/listManagedInstances".to_string(); - if self._scopes.len() == 0 { - self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); - } - - for &(find_this, param_name) in [("{project}", "project"), ("{zone}", "zone"), ("{instanceGroupManager}", "instanceGroupManager")].iter() { - let mut replace_with: Option<&str> = None; - for &(name, ref value) in params.iter() { - if name == param_name { - replace_with = Some(value); - 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 ["instanceGroupManager", "zone", "project"].iter() { - if let Some(index) = params.iter().position(|t| &t.0 == param_name) { - indices_for_removal.push(index); - } - } - for &index in indices_for_removal.iter() { - params.remove(index); - } - } - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_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) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = { - let mut json_response = String::new(); - res.read_to_string(&mut json_response).unwrap(); - match json::from_str(&json_response) { - Ok(decoded) => (res, decoded), - Err(err) => { - dlg.response_json_decode_error(&json_response, &err); - return Err(Error::JsonDecodeError(json_response, err)); - } - } - }; - - dlg.finished(true); - return Ok(result_value) - } - } - } - } - - - /// The project ID for this request. - /// - /// 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) -> InstanceGroupManagerListManagedInstanceCall<'a, C, A> { - self._project = new_value.to_string(); - self - } - /// The URL of the zone where the managed instance group is located. - /// - /// 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) -> InstanceGroupManagerListManagedInstanceCall<'a, C, A> { - self._zone = new_value.to_string(); - self - } - /// The name of the managed instance group. - /// - /// Sets the *instance group manager* path property to the given value. - /// - /// Even though the property as already been set when instantiating this call, - /// we provide this method for API completeness. - pub fn instance_group_manager(mut self, new_value: &str) -> InstanceGroupManagerListManagedInstanceCall<'a, C, A> { - self._instance_group_manager = new_value.to_string(); - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> InstanceGroupManagerListManagedInstanceCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. - /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. - /// * *alt* (query-string) - Data format for the response. - pub fn param(mut self, name: T, value: T) -> InstanceGroupManagerListManagedInstanceCall<'a, C, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::CloudPlatform`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be - /// sufficient, a read-write scope will do as well. - pub fn add_scope(mut self, scope: T) -> InstanceGroupManagerListManagedInstanceCall<'a, C, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().to_string(), ()); - self - } -} - - -/// Creates a managed instance group resource in the specified project using the data that is included in the request. -/// -/// A builder for the *insert* method supported by a *instanceGroupManager* resource. -/// It is not used directly, but through a `InstanceGroupManagerMethods` instance. -/// -/// # 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::InstanceGroupManager; -/// # #[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 = InstanceGroupManager::default(); -/// -/// // You can configure optional parameters by calling 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_group_managers().insert(req, "project", "zone") -/// .doit(); -/// # } -/// ``` -pub struct InstanceGroupManagerInsertCall<'a, C, A> - where C: 'a, A: 'a { - - hub: &'a Compute, - _request: InstanceGroupManager, - _project: String, - _zone: String, - _delegate: Option<&'a mut Delegate>, - _additional_params: HashMap, - _scopes: BTreeMap -} - -impl<'a, C, A> CallBuilder for InstanceGroupManagerInsertCall<'a, C, A> {} - -impl<'a, C, A> InstanceGroupManagerInsertCall<'a, C, A> where 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.instanceGroupManagers.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 Err(Error::FieldClash(field)); - } - } - for (name, 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}/instanceGroupManagers".to_string(); - if self._scopes.len() == 0 { - self._scopes.insert(Scope::CloudPlatform.as_ref().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 ["zone", "project"].iter() { - if let Some(index) = params.iter().position(|t| &t.0 == param_name) { - indices_for_removal.push(index); - } - } - for &index in indices_for_removal.iter() { - params.remove(index); - } - } - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); - let mut request_value_reader = - { - let mut value = json::value::to_value(&self._request); - remove_json_null_values(&mut value); - let mut dst = io::Cursor::new(Vec::with_capacity(128)); - json::to_writer(&mut dst, &value).unwrap(); - dst - }; - let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); - request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_token }); - request_value_reader.seek(io::SeekFrom::Start(0)).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) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()) - .header(ContentType(json_mime_type.clone())) - .header(ContentLength(request_size as u64)) - .body(&mut request_value_reader); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = { - let mut json_response = String::new(); - res.read_to_string(&mut json_response).unwrap(); - match json::from_str(&json_response) { - Ok(decoded) => (res, decoded), - Err(err) => { - dlg.response_json_decode_error(&json_response, &err); - return Err(Error::JsonDecodeError(json_response, err)); - } - } - }; - - dlg.finished(true); - return Ok(result_value) - } - } - } - } - - - /// - /// Sets the *request* property to the given value. - /// - /// Even though the property as already been set when instantiating this call, - /// we provide this method for API completeness. - pub fn request(mut self, new_value: InstanceGroupManager) -> InstanceGroupManagerInsertCall<'a, C, A> { - self._request = new_value; - self - } - /// The project ID for this request. - /// - /// 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) -> InstanceGroupManagerInsertCall<'a, C, A> { - self._project = new_value.to_string(); - self - } - /// The URL of the zone where the managed instance group is located. - /// - /// 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) -> InstanceGroupManagerInsertCall<'a, C, A> { - self._zone = new_value.to_string(); - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> InstanceGroupManagerInsertCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. - /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. - /// * *alt* (query-string) - Data format for the response. - pub fn param(mut self, name: T, value: T) -> InstanceGroupManagerInsertCall<'a, C, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::CloudPlatform`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be - /// sufficient, a read-write scope will do as well. - pub fn add_scope(mut self, scope: T) -> InstanceGroupManagerInsertCall<'a, C, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().to_string(), ()); - self - } -} - - -/// Retrieves the list of managed instance groups, and groups them by project and zone. -/// -/// A builder for the *aggregatedList* method supported by a *instanceGroupManager* resource. -/// It is not used directly, but through a `InstanceGroupManagerMethods` instance. -/// -/// # 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_group_managers().aggregated_list("project") -/// .page_token("invidunt") -/// .max_results(35) -/// .filter("sadipscing") -/// .doit(); -/// # } -/// ``` -pub struct InstanceGroupManagerAggregatedListCall<'a, C, A> +pub struct DiskTypeAggregatedListCall<'a, C, A> where C: 'a, A: 'a { hub: &'a Compute, @@ -17919,13 +17747,13 @@ pub struct InstanceGroupManagerAggregatedListCall<'a, C, A> _scopes: BTreeMap } -impl<'a, C, A> CallBuilder for InstanceGroupManagerAggregatedListCall<'a, C, A> {} +impl<'a, C, A> CallBuilder for DiskTypeAggregatedListCall<'a, C, A> {} -impl<'a, C, A> InstanceGroupManagerAggregatedListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { +impl<'a, C, A> DiskTypeAggregatedListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { /// Perform the operation you have build so far. - pub fn doit(mut self) -> Result<(hyper::client::Response, InstanceGroupManagerAggregatedList)> { + 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; @@ -17933,7 +17761,7 @@ impl<'a, C, A> InstanceGroupManagerAggregatedListCall<'a, C, A> where C: BorrowM Some(d) => d, None => &mut dd }; - dlg.begin(MethodInfo { id: "compute.instanceGroupManagers.aggregatedList", + 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())); @@ -17958,7 +17786,7 @@ impl<'a, C, A> InstanceGroupManagerAggregatedListCall<'a, C, A> where C: BorrowM params.push(("alt", "json".to_string())); - let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/aggregated/instanceGroupManagers".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_ref().to_string(), ()); } @@ -18062,41 +17890,38 @@ impl<'a, C, A> InstanceGroupManagerAggregatedListCall<'a, C, A> where C: BorrowM } - /// The project ID for this request. + /// Project ID for this request. /// /// 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) -> InstanceGroupManagerAggregatedListCall<'a, C, A> { + pub fn project(mut self, new_value: &str) -> DiskTypeAggregatedListCall<'a, C, A> { self._project = new_value.to_string(); self } /// Specifies a page token to use. Use this parameter if you want to list the next page of results. Set pageToken to the nextPageToken returned by a previous list request. /// /// Sets the *page token* query property to the given value. - pub fn page_token(mut self, new_value: &str) -> InstanceGroupManagerAggregatedListCall<'a, C, A> { + pub fn page_token(mut self, new_value: &str) -> DiskTypeAggregatedListCall<'a, C, A> { self._page_token = Some(new_value.to_string()); self } /// Maximum count of results to be returned. /// /// Sets the *max results* query property to the given value. - pub fn max_results(mut self, new_value: u32) -> InstanceGroupManagerAggregatedListCall<'a, C, A> { + pub fn max_results(mut self, new_value: u32) -> DiskTypeAggregatedListCall<'a, C, A> { self._max_results = Some(new_value); self } - /// Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must contain the following: - /// FIELD_NAME COMPARISON_STRING LITERAL_STRING - /// - /// - FIELD_NAME: The name of the field you want to compare. The field name must be valid for the type of resource being filtered. Only atomic field types are supported (string, number, boolean). Array and object fields are not currently supported. - /// - COMPARISON_STRING: The comparison string, either eq (equals) or ne (not equals). - /// - LITERAL_STRING: The literal string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field. For example, you can filter by the name of a resource: - /// filter=name ne example-instance - /// The above filter returns only results whose name field does not equal example-instance. You can also enclose your literal string in single, double, or no quotes. + /// Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must be in the format: FIELD_NAME COMPARISON_STRING LITERAL_STRING. + /// + /// The FIELD_NAME is the name of the field you want to compare. Only atomic field types are supported (string, number, boolean). The COMPARISON_STRING must be either eq (equals) or ne (not equals). The LITERAL_STRING is the string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field. + /// + /// For example, filter=name ne example-instance. /// /// Sets the *filter* query property to the given value. - pub fn filter(mut self, new_value: &str) -> InstanceGroupManagerAggregatedListCall<'a, C, A> { + pub fn filter(mut self, new_value: &str) -> DiskTypeAggregatedListCall<'a, C, A> { self._filter = Some(new_value.to_string()); self } @@ -18106,7 +17931,7 @@ impl<'a, C, A> InstanceGroupManagerAggregatedListCall<'a, C, A> where C: BorrowM /// It should be used to handle progress information, and to implement a certain level of resilience. /// /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> InstanceGroupManagerAggregatedListCall<'a, C, A> { + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DiskTypeAggregatedListCall<'a, C, A> { self._delegate = Some(new_value); self } @@ -18127,7 +17952,7 @@ impl<'a, C, A> InstanceGroupManagerAggregatedListCall<'a, C, A> where C: BorrowM /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. /// * *alt* (query-string) - Data format for the response. - pub fn param(mut self, name: T, value: T) -> InstanceGroupManagerAggregatedListCall<'a, C, A> + pub fn param(mut self, name: T, value: T) -> DiskTypeAggregatedListCall<'a, C, A> where T: AsRef { self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); self @@ -18144,7 +17969,7 @@ impl<'a, C, A> InstanceGroupManagerAggregatedListCall<'a, C, A> where C: BorrowM /// Usually there is more than one suitable scope to authorize an operation, some of which may /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be /// sufficient, a read-write scope will do as well. - pub fn add_scope(mut self, scope: T) -> InstanceGroupManagerAggregatedListCall<'a, C, A> + pub fn add_scope(mut self, scope: T) -> DiskTypeAggregatedListCall<'a, C, A> where T: AsRef { self._scopes.insert(scope.as_ref().to_string(), ()); self @@ -18152,883 +17977,10 @@ impl<'a, C, A> InstanceGroupManagerAggregatedListCall<'a, C, A> where C: BorrowM } -/// Deletes the specified instances. The instances are deleted and removed from the instance group and any target pools where they are a member. The managed instance group automatically reduces its targetSize value by the number of instances that you delete. +/// Retrieves the list of disk type resources available to the specified project. /// -/// A builder for the *deleteInstances* method supported by a *instanceGroupManager* resource. -/// It is not used directly, but through a `InstanceGroupManagerMethods` instance. -/// -/// # 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::InstanceGroupManagersDeleteInstancesRequest; -/// # #[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 = InstanceGroupManagersDeleteInstancesRequest::default(); -/// -/// // You can configure optional parameters by calling 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_group_managers().delete_instances(req, "project", "zone", "instanceGroupManager") -/// .doit(); -/// # } -/// ``` -pub struct InstanceGroupManagerDeleteInstanceCall<'a, C, A> - where C: 'a, A: 'a { - - hub: &'a Compute, - _request: InstanceGroupManagersDeleteInstancesRequest, - _project: String, - _zone: String, - _instance_group_manager: String, - _delegate: Option<&'a mut Delegate>, - _additional_params: HashMap, - _scopes: BTreeMap -} - -impl<'a, C, A> CallBuilder for InstanceGroupManagerDeleteInstanceCall<'a, C, A> {} - -impl<'a, C, A> InstanceGroupManagerDeleteInstanceCall<'a, C, A> where 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.instanceGroupManagers.deleteInstances", - 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(("instanceGroupManager", self._instance_group_manager.to_string())); - for &field in ["alt", "project", "zone", "instanceGroupManager"].iter() { - if self._additional_params.contains_key(field) { - dlg.finished(false); - return Err(Error::FieldClash(field)); - } - } - for (name, 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}/instanceGroupManagers/{instanceGroupManager}/deleteInstances".to_string(); - if self._scopes.len() == 0 { - self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); - } - - for &(find_this, param_name) in [("{project}", "project"), ("{zone}", "zone"), ("{instanceGroupManager}", "instanceGroupManager")].iter() { - let mut replace_with: Option<&str> = None; - for &(name, ref value) in params.iter() { - if name == param_name { - replace_with = Some(value); - 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 ["instanceGroupManager", "zone", "project"].iter() { - if let Some(index) = params.iter().position(|t| &t.0 == param_name) { - indices_for_removal.push(index); - } - } - for &index in indices_for_removal.iter() { - params.remove(index); - } - } - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); - let mut request_value_reader = - { - let mut value = json::value::to_value(&self._request); - remove_json_null_values(&mut value); - let mut dst = io::Cursor::new(Vec::with_capacity(128)); - json::to_writer(&mut dst, &value).unwrap(); - dst - }; - let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); - request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_token }); - request_value_reader.seek(io::SeekFrom::Start(0)).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) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()) - .header(ContentType(json_mime_type.clone())) - .header(ContentLength(request_size as u64)) - .body(&mut request_value_reader); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = { - let mut json_response = String::new(); - res.read_to_string(&mut json_response).unwrap(); - match json::from_str(&json_response) { - Ok(decoded) => (res, decoded), - Err(err) => { - dlg.response_json_decode_error(&json_response, &err); - return Err(Error::JsonDecodeError(json_response, err)); - } - } - }; - - dlg.finished(true); - return Ok(result_value) - } - } - } - } - - - /// - /// Sets the *request* property to the given value. - /// - /// Even though the property as already been set when instantiating this call, - /// we provide this method for API completeness. - pub fn request(mut self, new_value: InstanceGroupManagersDeleteInstancesRequest) -> InstanceGroupManagerDeleteInstanceCall<'a, C, A> { - self._request = new_value; - self - } - /// The project ID for this request. - /// - /// 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) -> InstanceGroupManagerDeleteInstanceCall<'a, C, A> { - self._project = new_value.to_string(); - self - } - /// The URL of the zone where the managed instance group is located. - /// - /// 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) -> InstanceGroupManagerDeleteInstanceCall<'a, C, A> { - self._zone = new_value.to_string(); - self - } - /// The name of the instance group manager. - /// - /// Sets the *instance group manager* path property to the given value. - /// - /// Even though the property as already been set when instantiating this call, - /// we provide this method for API completeness. - pub fn instance_group_manager(mut self, new_value: &str) -> InstanceGroupManagerDeleteInstanceCall<'a, C, A> { - self._instance_group_manager = new_value.to_string(); - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> InstanceGroupManagerDeleteInstanceCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. - /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. - /// * *alt* (query-string) - Data format for the response. - pub fn param(mut self, name: T, value: T) -> InstanceGroupManagerDeleteInstanceCall<'a, C, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::CloudPlatform`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be - /// sufficient, a read-write scope will do as well. - pub fn add_scope(mut self, scope: T) -> InstanceGroupManagerDeleteInstanceCall<'a, C, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().to_string(), ()); - self - } -} - - -/// Specifies the instance template to use when creating new instances in this group. The templates for existing instances in the group do not change unless you recreate them. -/// -/// A builder for the *setInstanceTemplate* method supported by a *instanceGroupManager* resource. -/// It is not used directly, but through a `InstanceGroupManagerMethods` instance. -/// -/// # 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::InstanceGroupManagersSetInstanceTemplateRequest; -/// # #[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 = InstanceGroupManagersSetInstanceTemplateRequest::default(); -/// -/// // You can configure optional parameters by calling 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_group_managers().set_instance_template(req, "project", "zone", "instanceGroupManager") -/// .doit(); -/// # } -/// ``` -pub struct InstanceGroupManagerSetInstanceTemplateCall<'a, C, A> - where C: 'a, A: 'a { - - hub: &'a Compute, - _request: InstanceGroupManagersSetInstanceTemplateRequest, - _project: String, - _zone: String, - _instance_group_manager: String, - _delegate: Option<&'a mut Delegate>, - _additional_params: HashMap, - _scopes: BTreeMap -} - -impl<'a, C, A> CallBuilder for InstanceGroupManagerSetInstanceTemplateCall<'a, C, A> {} - -impl<'a, C, A> InstanceGroupManagerSetInstanceTemplateCall<'a, C, A> where 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.instanceGroupManagers.setInstanceTemplate", - 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(("instanceGroupManager", self._instance_group_manager.to_string())); - for &field in ["alt", "project", "zone", "instanceGroupManager"].iter() { - if self._additional_params.contains_key(field) { - dlg.finished(false); - return Err(Error::FieldClash(field)); - } - } - for (name, 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}/instanceGroupManagers/{instanceGroupManager}/setInstanceTemplate".to_string(); - if self._scopes.len() == 0 { - self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); - } - - for &(find_this, param_name) in [("{project}", "project"), ("{zone}", "zone"), ("{instanceGroupManager}", "instanceGroupManager")].iter() { - let mut replace_with: Option<&str> = None; - for &(name, ref value) in params.iter() { - if name == param_name { - replace_with = Some(value); - 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 ["instanceGroupManager", "zone", "project"].iter() { - if let Some(index) = params.iter().position(|t| &t.0 == param_name) { - indices_for_removal.push(index); - } - } - for &index in indices_for_removal.iter() { - params.remove(index); - } - } - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); - let mut request_value_reader = - { - let mut value = json::value::to_value(&self._request); - remove_json_null_values(&mut value); - let mut dst = io::Cursor::new(Vec::with_capacity(128)); - json::to_writer(&mut dst, &value).unwrap(); - dst - }; - let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); - request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_token }); - request_value_reader.seek(io::SeekFrom::Start(0)).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) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()) - .header(ContentType(json_mime_type.clone())) - .header(ContentLength(request_size as u64)) - .body(&mut request_value_reader); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = { - let mut json_response = String::new(); - res.read_to_string(&mut json_response).unwrap(); - match json::from_str(&json_response) { - Ok(decoded) => (res, decoded), - Err(err) => { - dlg.response_json_decode_error(&json_response, &err); - return Err(Error::JsonDecodeError(json_response, err)); - } - } - }; - - dlg.finished(true); - return Ok(result_value) - } - } - } - } - - - /// - /// Sets the *request* property to the given value. - /// - /// Even though the property as already been set when instantiating this call, - /// we provide this method for API completeness. - pub fn request(mut self, new_value: InstanceGroupManagersSetInstanceTemplateRequest) -> InstanceGroupManagerSetInstanceTemplateCall<'a, C, A> { - self._request = new_value; - self - } - /// The project ID for this request. - /// - /// 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) -> InstanceGroupManagerSetInstanceTemplateCall<'a, C, A> { - self._project = new_value.to_string(); - self - } - /// The URL of the zone where the managed instance group is located. - /// - /// 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) -> InstanceGroupManagerSetInstanceTemplateCall<'a, C, A> { - self._zone = new_value.to_string(); - self - } - /// The name of the instance group manager. - /// - /// Sets the *instance group manager* path property to the given value. - /// - /// Even though the property as already been set when instantiating this call, - /// we provide this method for API completeness. - pub fn instance_group_manager(mut self, new_value: &str) -> InstanceGroupManagerSetInstanceTemplateCall<'a, C, A> { - self._instance_group_manager = new_value.to_string(); - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> InstanceGroupManagerSetInstanceTemplateCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. - /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. - /// * *alt* (query-string) - Data format for the response. - pub fn param(mut self, name: T, value: T) -> InstanceGroupManagerSetInstanceTemplateCall<'a, C, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::CloudPlatform`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be - /// sufficient, a read-write scope will do as well. - pub fn add_scope(mut self, scope: T) -> InstanceGroupManagerSetInstanceTemplateCall<'a, C, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().to_string(), ()); - self - } -} - - -/// Modifies the target pools to which all new instances in this group are assigned. The target pools for existing instances in the group do not change unless you recreate them. -/// -/// A builder for the *setTargetPools* method supported by a *instanceGroupManager* resource. -/// It is not used directly, but through a `InstanceGroupManagerMethods` instance. -/// -/// # 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::InstanceGroupManagersSetTargetPoolsRequest; -/// # #[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 = InstanceGroupManagersSetTargetPoolsRequest::default(); -/// -/// // You can configure optional parameters by calling 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_group_managers().set_target_pools(req, "project", "zone", "instanceGroupManager") -/// .doit(); -/// # } -/// ``` -pub struct InstanceGroupManagerSetTargetPoolCall<'a, C, A> - where C: 'a, A: 'a { - - hub: &'a Compute, - _request: InstanceGroupManagersSetTargetPoolsRequest, - _project: String, - _zone: String, - _instance_group_manager: String, - _delegate: Option<&'a mut Delegate>, - _additional_params: HashMap, - _scopes: BTreeMap -} - -impl<'a, C, A> CallBuilder for InstanceGroupManagerSetTargetPoolCall<'a, C, A> {} - -impl<'a, C, A> InstanceGroupManagerSetTargetPoolCall<'a, C, A> where 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.instanceGroupManagers.setTargetPools", - 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(("instanceGroupManager", self._instance_group_manager.to_string())); - for &field in ["alt", "project", "zone", "instanceGroupManager"].iter() { - if self._additional_params.contains_key(field) { - dlg.finished(false); - return Err(Error::FieldClash(field)); - } - } - for (name, 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}/instanceGroupManagers/{instanceGroupManager}/setTargetPools".to_string(); - if self._scopes.len() == 0 { - self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); - } - - for &(find_this, param_name) in [("{project}", "project"), ("{zone}", "zone"), ("{instanceGroupManager}", "instanceGroupManager")].iter() { - let mut replace_with: Option<&str> = None; - for &(name, ref value) in params.iter() { - if name == param_name { - replace_with = Some(value); - 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 ["instanceGroupManager", "zone", "project"].iter() { - if let Some(index) = params.iter().position(|t| &t.0 == param_name) { - indices_for_removal.push(index); - } - } - for &index in indices_for_removal.iter() { - params.remove(index); - } - } - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); - let mut request_value_reader = - { - let mut value = json::value::to_value(&self._request); - remove_json_null_values(&mut value); - let mut dst = io::Cursor::new(Vec::with_capacity(128)); - json::to_writer(&mut dst, &value).unwrap(); - dst - }; - let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); - request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_token }); - request_value_reader.seek(io::SeekFrom::Start(0)).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) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()) - .header(ContentType(json_mime_type.clone())) - .header(ContentLength(request_size as u64)) - .body(&mut request_value_reader); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = { - let mut json_response = String::new(); - res.read_to_string(&mut json_response).unwrap(); - match json::from_str(&json_response) { - Ok(decoded) => (res, decoded), - Err(err) => { - dlg.response_json_decode_error(&json_response, &err); - return Err(Error::JsonDecodeError(json_response, err)); - } - } - }; - - dlg.finished(true); - return Ok(result_value) - } - } - } - } - - - /// - /// Sets the *request* property to the given value. - /// - /// Even though the property as already been set when instantiating this call, - /// we provide this method for API completeness. - pub fn request(mut self, new_value: InstanceGroupManagersSetTargetPoolsRequest) -> InstanceGroupManagerSetTargetPoolCall<'a, C, A> { - self._request = new_value; - self - } - /// The project ID for this request. - /// - /// 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) -> InstanceGroupManagerSetTargetPoolCall<'a, C, A> { - self._project = new_value.to_string(); - self - } - /// The URL of the zone where the managed instance group is located. - /// - /// 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) -> InstanceGroupManagerSetTargetPoolCall<'a, C, A> { - self._zone = new_value.to_string(); - self - } - /// The name of the instance group manager. - /// - /// Sets the *instance group manager* path property to the given value. - /// - /// Even though the property as already been set when instantiating this call, - /// we provide this method for API completeness. - pub fn instance_group_manager(mut self, new_value: &str) -> InstanceGroupManagerSetTargetPoolCall<'a, C, A> { - self._instance_group_manager = new_value.to_string(); - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> InstanceGroupManagerSetTargetPoolCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. - /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. - /// * *alt* (query-string) - Data format for the response. - pub fn param(mut self, name: T, value: T) -> InstanceGroupManagerSetTargetPoolCall<'a, C, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::CloudPlatform`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be - /// sufficient, a read-write scope will do as well. - pub fn add_scope(mut self, scope: T) -> InstanceGroupManagerSetTargetPoolCall<'a, C, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().to_string(), ()); - self - } -} - - -/// Deletes the specified managed instance group resource. -/// -/// A builder for the *delete* method supported by a *instanceGroupManager* resource. -/// It is not used directly, but through a `InstanceGroupManagerMethods` instance. +/// A builder for the *list* method supported by a *diskType* resource. +/// It is not used directly, but through a `DiskTypeMethods` instance. /// /// # Example /// @@ -19051,29 +18003,34 @@ impl<'a, C, A> InstanceGroupManagerSetTargetPoolCall<'a, C, A> where C: BorrowMu /// // You can configure optional parameters by calling 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_group_managers().delete("project", "zone", "instanceGroupManager") +/// let result = hub.disk_types().list("project", "zone") +/// .page_token("nonumy") +/// .max_results(88) +/// .filter("sanctus") /// .doit(); /// # } /// ``` -pub struct InstanceGroupManagerDeleteCall<'a, C, A> +pub struct DiskTypeListCall<'a, C, A> where C: 'a, A: 'a { hub: &'a Compute, _project: String, _zone: String, - _instance_group_manager: String, + _page_token: Option, + _max_results: Option, + _filter: Option, _delegate: Option<&'a mut Delegate>, _additional_params: HashMap, _scopes: BTreeMap } -impl<'a, C, A> CallBuilder for InstanceGroupManagerDeleteCall<'a, C, A> {} +impl<'a, C, A> CallBuilder for DiskTypeListCall<'a, C, A> {} -impl<'a, C, A> InstanceGroupManagerDeleteCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { +impl<'a, C, A> DiskTypeListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { /// Perform the operation you have build so far. - pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + 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; @@ -19081,273 +18038,21 @@ impl<'a, C, A> InstanceGroupManagerDeleteCall<'a, C, A> where C: BorrowMut d, None => &mut dd }; - dlg.begin(MethodInfo { id: "compute.instanceGroupManagers.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(("instanceGroupManager", self._instance_group_manager.to_string())); - for &field in ["alt", "project", "zone", "instanceGroupManager"].iter() { - if self._additional_params.contains_key(field) { - dlg.finished(false); - return Err(Error::FieldClash(field)); - } - } - for (name, 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}/instanceGroupManagers/{instanceGroupManager}".to_string(); - if self._scopes.len() == 0 { - self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); - } - - for &(find_this, param_name) in [("{project}", "project"), ("{zone}", "zone"), ("{instanceGroupManager}", "instanceGroupManager")].iter() { - let mut replace_with: Option<&str> = None; - for &(name, ref value) in params.iter() { - if name == param_name { - replace_with = Some(value); - 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 ["instanceGroupManager", "zone", "project"].iter() { - if let Some(index) = params.iter().position(|t| &t.0 == param_name) { - indices_for_removal.push(index); - } - } - for &index in indices_for_removal.iter() { - params.remove(index); - } - } - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_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) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = { - let mut json_response = String::new(); - res.read_to_string(&mut json_response).unwrap(); - match json::from_str(&json_response) { - Ok(decoded) => (res, decoded), - Err(err) => { - dlg.response_json_decode_error(&json_response, &err); - return Err(Error::JsonDecodeError(json_response, err)); - } - } - }; - - dlg.finished(true); - return Ok(result_value) - } - } - } - } - - - /// The project ID for this request. - /// - /// 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) -> InstanceGroupManagerDeleteCall<'a, C, A> { - self._project = new_value.to_string(); - self - } - /// The URL of the zone where the managed instance group is located. - /// - /// 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) -> InstanceGroupManagerDeleteCall<'a, C, A> { - self._zone = new_value.to_string(); - self - } - /// The name of the instance group manager to delete. - /// - /// Sets the *instance group manager* path property to the given value. - /// - /// Even though the property as already been set when instantiating this call, - /// we provide this method for API completeness. - pub fn instance_group_manager(mut self, new_value: &str) -> InstanceGroupManagerDeleteCall<'a, C, A> { - self._instance_group_manager = new_value.to_string(); - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> InstanceGroupManagerDeleteCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. - /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. - /// * *alt* (query-string) - Data format for the response. - pub fn param(mut self, name: T, value: T) -> InstanceGroupManagerDeleteCall<'a, C, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::CloudPlatform`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be - /// sufficient, a read-write scope will do as well. - pub fn add_scope(mut self, scope: T) -> InstanceGroupManagerDeleteCall<'a, C, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().to_string(), ()); - self - } -} - - -/// Returns the specified managed instance group resource. -/// -/// A builder for the *get* method supported by a *instanceGroupManager* resource. -/// It is not used directly, but through a `InstanceGroupManagerMethods` instance. -/// -/// # 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_group_managers().get("project", "zone", "instanceGroupManager") -/// .doit(); -/// # } -/// ``` -pub struct InstanceGroupManagerGetCall<'a, C, A> - where C: 'a, A: 'a { - - hub: &'a Compute, - _project: String, - _zone: String, - _instance_group_manager: String, - _delegate: Option<&'a mut Delegate>, - _additional_params: HashMap, - _scopes: BTreeMap -} - -impl<'a, C, A> CallBuilder for InstanceGroupManagerGetCall<'a, C, A> {} - -impl<'a, C, A> InstanceGroupManagerGetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { - - - /// Perform the operation you have build so far. - pub fn doit(mut self) -> Result<(hyper::client::Response, InstanceGroupManager)> { - use std::io::{Read, Seek}; - use hyper::header::{ContentType, ContentLength, Authorization, 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.instanceGroupManagers.get", + dlg.begin(MethodInfo { id: "compute.diskTypes.list", http_method: hyper::method::Method::Get }); - let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + 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(("instanceGroupManager", self._instance_group_manager.to_string())); - for &field in ["alt", "project", "zone", "instanceGroupManager"].iter() { + 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 Err(Error::FieldClash(field)); @@ -19359,12 +18064,12 @@ impl<'a, C, A> InstanceGroupManagerGetCall<'a, C, A> where C: BorrowMut = None; for &(name, ref value) in params.iter() { if name == param_name { @@ -19375,8 +18080,8 @@ impl<'a, C, A> InstanceGroupManagerGetCall<'a, C, A> where C: BorrowMut = Vec::with_capacity(3); - for param_name in ["instanceGroupManager", "zone", "project"].iter() { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["zone", "project"].iter() { if let Some(index) = params.iter().position(|t| &t.0 == param_name) { indices_for_removal.push(index); } @@ -19463,34 +18168,49 @@ impl<'a, C, A> InstanceGroupManagerGetCall<'a, C, A> where C: BorrowMut InstanceGroupManagerGetCall<'a, C, A> { + pub fn project(mut self, new_value: &str) -> DiskTypeListCall<'a, C, A> { self._project = new_value.to_string(); self } - /// The URL of the zone where the managed instance group is located. + /// The name of the zone for this request. /// /// 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) -> InstanceGroupManagerGetCall<'a, C, A> { + pub fn zone(mut self, new_value: &str) -> DiskTypeListCall<'a, C, A> { self._zone = new_value.to_string(); self } - /// The name of the instance group manager resource. + /// Specifies a page token to use. Use this parameter if you want to list the next page of results. Set pageToken to the nextPageToken returned by a previous list request. /// - /// Sets the *instance group manager* path property to the given value. + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> DiskTypeListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Maximum count of results to be returned. /// - /// Even though the property as already been set when instantiating this call, - /// we provide this method for API completeness. - pub fn instance_group_manager(mut self, new_value: &str) -> InstanceGroupManagerGetCall<'a, C, A> { - self._instance_group_manager = new_value.to_string(); + /// Sets the *max results* query property to the given value. + pub fn max_results(mut self, new_value: u32) -> DiskTypeListCall<'a, C, A> { + self._max_results = Some(new_value); + self + } + /// Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must be in the format: FIELD_NAME COMPARISON_STRING LITERAL_STRING. + /// + /// The FIELD_NAME is the name of the field you want to compare. Only atomic field types are supported (string, number, boolean). The COMPARISON_STRING must be either eq (equals) or ne (not equals). The LITERAL_STRING is the string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field. + /// + /// For example, filter=name ne example-instance. + /// + /// Sets the *filter* query property to the given value. + pub fn filter(mut self, new_value: &str) -> DiskTypeListCall<'a, C, A> { + self._filter = Some(new_value.to_string()); self } /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong @@ -19499,7 +18219,7 @@ impl<'a, C, A> InstanceGroupManagerGetCall<'a, C, A> where C: BorrowMut InstanceGroupManagerGetCall<'a, C, A> { + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DiskTypeListCall<'a, C, A> { self._delegate = Some(new_value); self } @@ -19520,7 +18240,7 @@ impl<'a, C, A> InstanceGroupManagerGetCall<'a, C, A> where C: BorrowMut(mut self, name: T, value: T) -> InstanceGroupManagerGetCall<'a, C, A> + pub fn param(mut self, name: T, value: T) -> DiskTypeListCall<'a, C, A> where T: AsRef { self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); self @@ -19537,589 +18257,7 @@ impl<'a, C, A> InstanceGroupManagerGetCall<'a, C, A> where C: BorrowMut(mut self, scope: T) -> InstanceGroupManagerGetCall<'a, C, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().to_string(), ()); - self - } -} - - -/// Removes the specified instances from the managed instance group, and from any target pools where they are a member. The instances are not deleted. The managed instance group automatically reduces its targetSize value by the number of instances that you abandon from the group. -/// -/// A builder for the *abandonInstances* method supported by a *instanceGroupManager* resource. -/// It is not used directly, but through a `InstanceGroupManagerMethods` instance. -/// -/// # 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::InstanceGroupManagersAbandonInstancesRequest; -/// # #[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 = InstanceGroupManagersAbandonInstancesRequest::default(); -/// -/// // You can configure optional parameters by calling 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_group_managers().abandon_instances(req, "project", "zone", "instanceGroupManager") -/// .doit(); -/// # } -/// ``` -pub struct InstanceGroupManagerAbandonInstanceCall<'a, C, A> - where C: 'a, A: 'a { - - hub: &'a Compute, - _request: InstanceGroupManagersAbandonInstancesRequest, - _project: String, - _zone: String, - _instance_group_manager: String, - _delegate: Option<&'a mut Delegate>, - _additional_params: HashMap, - _scopes: BTreeMap -} - -impl<'a, C, A> CallBuilder for InstanceGroupManagerAbandonInstanceCall<'a, C, A> {} - -impl<'a, C, A> InstanceGroupManagerAbandonInstanceCall<'a, C, A> where 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.instanceGroupManagers.abandonInstances", - 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(("instanceGroupManager", self._instance_group_manager.to_string())); - for &field in ["alt", "project", "zone", "instanceGroupManager"].iter() { - if self._additional_params.contains_key(field) { - dlg.finished(false); - return Err(Error::FieldClash(field)); - } - } - for (name, 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}/instanceGroupManagers/{instanceGroupManager}/abandonInstances".to_string(); - if self._scopes.len() == 0 { - self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); - } - - for &(find_this, param_name) in [("{project}", "project"), ("{zone}", "zone"), ("{instanceGroupManager}", "instanceGroupManager")].iter() { - let mut replace_with: Option<&str> = None; - for &(name, ref value) in params.iter() { - if name == param_name { - replace_with = Some(value); - 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 ["instanceGroupManager", "zone", "project"].iter() { - if let Some(index) = params.iter().position(|t| &t.0 == param_name) { - indices_for_removal.push(index); - } - } - for &index in indices_for_removal.iter() { - params.remove(index); - } - } - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); - let mut request_value_reader = - { - let mut value = json::value::to_value(&self._request); - remove_json_null_values(&mut value); - let mut dst = io::Cursor::new(Vec::with_capacity(128)); - json::to_writer(&mut dst, &value).unwrap(); - dst - }; - let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); - request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_token }); - request_value_reader.seek(io::SeekFrom::Start(0)).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) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()) - .header(ContentType(json_mime_type.clone())) - .header(ContentLength(request_size as u64)) - .body(&mut request_value_reader); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = { - let mut json_response = String::new(); - res.read_to_string(&mut json_response).unwrap(); - match json::from_str(&json_response) { - Ok(decoded) => (res, decoded), - Err(err) => { - dlg.response_json_decode_error(&json_response, &err); - return Err(Error::JsonDecodeError(json_response, err)); - } - } - }; - - dlg.finished(true); - return Ok(result_value) - } - } - } - } - - - /// - /// Sets the *request* property to the given value. - /// - /// Even though the property as already been set when instantiating this call, - /// we provide this method for API completeness. - pub fn request(mut self, new_value: InstanceGroupManagersAbandonInstancesRequest) -> InstanceGroupManagerAbandonInstanceCall<'a, C, A> { - self._request = new_value; - self - } - /// The project ID for this request. - /// - /// 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) -> InstanceGroupManagerAbandonInstanceCall<'a, C, A> { - self._project = new_value.to_string(); - self - } - /// The URL of the zone where the managed instance group is located. - /// - /// 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) -> InstanceGroupManagerAbandonInstanceCall<'a, C, A> { - self._zone = new_value.to_string(); - self - } - /// The name of the instance group manager. - /// - /// Sets the *instance group manager* path property to the given value. - /// - /// Even though the property as already been set when instantiating this call, - /// we provide this method for API completeness. - pub fn instance_group_manager(mut self, new_value: &str) -> InstanceGroupManagerAbandonInstanceCall<'a, C, A> { - self._instance_group_manager = new_value.to_string(); - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> InstanceGroupManagerAbandonInstanceCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. - /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. - /// * *alt* (query-string) - Data format for the response. - pub fn param(mut self, name: T, value: T) -> InstanceGroupManagerAbandonInstanceCall<'a, C, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::CloudPlatform`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be - /// sufficient, a read-write scope will do as well. - pub fn add_scope(mut self, scope: T) -> InstanceGroupManagerAbandonInstanceCall<'a, C, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().to_string(), ()); - self - } -} - - -/// Recreates the specified instances. The instances are deleted, then recreated using the managed instance group's current instance template. -/// -/// A builder for the *recreateInstances* method supported by a *instanceGroupManager* resource. -/// It is not used directly, but through a `InstanceGroupManagerMethods` instance. -/// -/// # 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::InstanceGroupManagersRecreateInstancesRequest; -/// # #[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 = InstanceGroupManagersRecreateInstancesRequest::default(); -/// -/// // You can configure optional parameters by calling 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_group_managers().recreate_instances(req, "project", "zone", "instanceGroupManager") -/// .doit(); -/// # } -/// ``` -pub struct InstanceGroupManagerRecreateInstanceCall<'a, C, A> - where C: 'a, A: 'a { - - hub: &'a Compute, - _request: InstanceGroupManagersRecreateInstancesRequest, - _project: String, - _zone: String, - _instance_group_manager: String, - _delegate: Option<&'a mut Delegate>, - _additional_params: HashMap, - _scopes: BTreeMap -} - -impl<'a, C, A> CallBuilder for InstanceGroupManagerRecreateInstanceCall<'a, C, A> {} - -impl<'a, C, A> InstanceGroupManagerRecreateInstanceCall<'a, C, A> where 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.instanceGroupManagers.recreateInstances", - 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(("instanceGroupManager", self._instance_group_manager.to_string())); - for &field in ["alt", "project", "zone", "instanceGroupManager"].iter() { - if self._additional_params.contains_key(field) { - dlg.finished(false); - return Err(Error::FieldClash(field)); - } - } - for (name, 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}/instanceGroupManagers/{instanceGroupManager}/recreateInstances".to_string(); - if self._scopes.len() == 0 { - self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); - } - - for &(find_this, param_name) in [("{project}", "project"), ("{zone}", "zone"), ("{instanceGroupManager}", "instanceGroupManager")].iter() { - let mut replace_with: Option<&str> = None; - for &(name, ref value) in params.iter() { - if name == param_name { - replace_with = Some(value); - 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 ["instanceGroupManager", "zone", "project"].iter() { - if let Some(index) = params.iter().position(|t| &t.0 == param_name) { - indices_for_removal.push(index); - } - } - for &index in indices_for_removal.iter() { - params.remove(index); - } - } - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); - let mut request_value_reader = - { - let mut value = json::value::to_value(&self._request); - remove_json_null_values(&mut value); - let mut dst = io::Cursor::new(Vec::with_capacity(128)); - json::to_writer(&mut dst, &value).unwrap(); - dst - }; - let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); - request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_token }); - request_value_reader.seek(io::SeekFrom::Start(0)).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) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()) - .header(ContentType(json_mime_type.clone())) - .header(ContentLength(request_size as u64)) - .body(&mut request_value_reader); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = { - let mut json_response = String::new(); - res.read_to_string(&mut json_response).unwrap(); - match json::from_str(&json_response) { - Ok(decoded) => (res, decoded), - Err(err) => { - dlg.response_json_decode_error(&json_response, &err); - return Err(Error::JsonDecodeError(json_response, err)); - } - } - }; - - dlg.finished(true); - return Ok(result_value) - } - } - } - } - - - /// - /// Sets the *request* property to the given value. - /// - /// Even though the property as already been set when instantiating this call, - /// we provide this method for API completeness. - pub fn request(mut self, new_value: InstanceGroupManagersRecreateInstancesRequest) -> InstanceGroupManagerRecreateInstanceCall<'a, C, A> { - self._request = new_value; - self - } - /// The project ID for this request. - /// - /// 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) -> InstanceGroupManagerRecreateInstanceCall<'a, C, A> { - self._project = new_value.to_string(); - self - } - /// The URL of the zone where the managed instance group is located. - /// - /// 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) -> InstanceGroupManagerRecreateInstanceCall<'a, C, A> { - self._zone = new_value.to_string(); - self - } - /// The name of the instance group manager. - /// - /// Sets the *instance group manager* path property to the given value. - /// - /// Even though the property as already been set when instantiating this call, - /// we provide this method for API completeness. - pub fn instance_group_manager(mut self, new_value: &str) -> InstanceGroupManagerRecreateInstanceCall<'a, C, A> { - self._instance_group_manager = new_value.to_string(); - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> InstanceGroupManagerRecreateInstanceCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. - /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. - /// * *alt* (query-string) - Data format for the response. - pub fn param(mut self, name: T, value: T) -> InstanceGroupManagerRecreateInstanceCall<'a, C, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::CloudPlatform`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be - /// sufficient, a read-write scope will do as well. - pub fn add_scope(mut self, scope: T) -> InstanceGroupManagerRecreateInstanceCall<'a, C, A> + pub fn add_scope(mut self, scope: T) -> DiskTypeListCall<'a, C, A> where T: AsRef { self._scopes.insert(scope.as_ref().to_string(), ()); self @@ -20402,9 +18540,9 @@ impl<'a, C, A> ZoneGetCall<'a, C, A> where C: BorrowMut, A: oauth /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.zones().list("project") -/// .page_token("est") -/// .max_results(55) -/// .filter("accusam") +/// .page_token("invidunt") +/// .max_results(35) +/// .filter("sadipscing") /// .doit(); /// # } /// ``` @@ -20588,14 +18726,11 @@ impl<'a, C, A> ZoneListCall<'a, C, A> where C: BorrowMut, A: oaut self._max_results = Some(new_value); self } - /// Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must contain the following: - /// FIELD_NAME COMPARISON_STRING LITERAL_STRING - /// - /// - FIELD_NAME: The name of the field you want to compare. The field name must be valid for the type of resource being filtered. Only atomic field types are supported (string, number, boolean). Array and object fields are not currently supported. - /// - COMPARISON_STRING: The comparison string, either eq (equals) or ne (not equals). - /// - LITERAL_STRING: The literal string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field. For example, you can filter by the name of a resource: - /// filter=name ne example-instance - /// The above filter returns only results whose name field does not equal example-instance. You can also enclose your literal string in single, double, or no quotes. + /// Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must be in the format: FIELD_NAME COMPARISON_STRING LITERAL_STRING. + /// + /// The FIELD_NAME is the name of the field you want to compare. Only atomic field types are supported (string, number, boolean). The COMPARISON_STRING must be either eq (equals) or ne (not equals). The LITERAL_STRING is the string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field. + /// + /// For example, filter=name ne example-instance. /// /// Sets the *filter* query property to the given value. pub fn filter(mut self, new_value: &str) -> ZoneListCall<'a, C, A> { @@ -21232,7 +19367,7 @@ impl<'a, C, A> InstanceDeleteCall<'a, C, A> where C: BorrowMut, A /// // 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") -/// .port(-78) +/// .port(-30) /// .doit(); /// # } /// ``` @@ -21503,7 +19638,7 @@ impl<'a, C, A> InstanceGetSerialPortOutputCall<'a, C, A> where C: BorrowMut InstanceGetCall<'a, C, A> where C: BorrowMut, A: o self._project = new_value.to_string(); self } - /// The name of the The name of the zone for this request.. + /// The name of the zone for this request. /// /// Sets the *zone* path property to the given value. /// @@ -24295,9 +22430,9 @@ impl<'a, C, A> InstanceInsertCall<'a, C, A> where C: BorrowMut, A /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.instances().list("project", "zone") -/// .page_token("eirmod") -/// .max_results(93) -/// .filter("voluptua.") +/// .page_token("kasd") +/// .max_results(14) +/// .filter("rebum.") /// .doit(); /// # } /// ``` @@ -24493,14 +22628,11 @@ impl<'a, C, A> InstanceListCall<'a, C, A> where C: BorrowMut, A: self._max_results = Some(new_value); self } - /// Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must contain the following: - /// FIELD_NAME COMPARISON_STRING LITERAL_STRING - /// - /// - FIELD_NAME: The name of the field you want to compare. The field name must be valid for the type of resource being filtered. Only atomic field types are supported (string, number, boolean). Array and object fields are not currently supported. - /// - COMPARISON_STRING: The comparison string, either eq (equals) or ne (not equals). - /// - LITERAL_STRING: The literal string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field. For example, you can filter by the name of a resource: - /// filter=name ne example-instance - /// The above filter returns only results whose name field does not equal example-instance. You can also enclose your literal string in single, double, or no quotes. + /// Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must be in the format: FIELD_NAME COMPARISON_STRING LITERAL_STRING. + /// + /// The FIELD_NAME is the name of the field you want to compare. Only atomic field types are supported (string, number, boolean). The COMPARISON_STRING must be either eq (equals) or ne (not equals). The LITERAL_STRING is the string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field. + /// + /// For example, filter=name ne example-instance. /// /// Sets the *filter* query property to the given value. pub fn filter(mut self, new_value: &str) -> InstanceListCall<'a, C, A> { @@ -25103,6 +23235,8 @@ impl<'a, C, A> InstanceDeleteAccessConfigCall<'a, C, A> where C: BorrowMut InstanceDeleteAccessConfigCall<'a, C, A> where C: BorrowMut InstanceAggregatedListCall<'a, C, A> where C: BorrowMut InstanceAggregatedListCall<'a, C, A> { @@ -26460,9 +24591,9 @@ impl<'a, C, A> BackendServiceUpdateCall<'a, C, A> where C: BorrowMut BackendServiceListCall<'a, C, A> where C: BorrowMut BackendServiceListCall<'a, C, A> { @@ -27258,7 +25386,9 @@ impl<'a, C, A> BackendServiceInsertCall<'a, C, A> where C: BorrowMut BackendServiceInsertCall<'a, C, A> where C: BorrowMut ImageListCall<'a, C, A> where C: BorrowMut, A: oau self._max_results = Some(new_value); self } - /// Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must contain the following: - /// FIELD_NAME COMPARISON_STRING LITERAL_STRING - /// - /// - FIELD_NAME: The name of the field you want to compare. The field name must be valid for the type of resource being filtered. Only atomic field types are supported (string, number, boolean). Array and object fields are not currently supported. - /// - COMPARISON_STRING: The comparison string, either eq (equals) or ne (not equals). - /// - LITERAL_STRING: The literal string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field. For example, you can filter by the name of a resource: - /// filter=name ne example-instance - /// The above filter returns only results whose name field does not equal example-instance. You can also enclose your literal string in single, double, or no quotes. + /// Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must be in the format: FIELD_NAME COMPARISON_STRING LITERAL_STRING. + /// + /// The FIELD_NAME is the name of the field you want to compare. Only atomic field types are supported (string, number, boolean). The COMPARISON_STRING must be either eq (equals) or ne (not equals). The LITERAL_STRING is the string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field. + /// + /// For example, filter=name ne example-instance. /// /// Sets the *filter* query property to the given value. pub fn filter(mut self, new_value: &str) -> ImageListCall<'a, C, A> { @@ -28829,6 +26956,1603 @@ impl<'a, C, A> LicenseGetCall<'a, C, A> where C: BorrowMut, A: oa } +/// Deletes the specified TargetHttpsProxy resource. +/// +/// A builder for the *delete* method supported by a *targetHttpsProxy* resource. +/// It is not used directly, but through a `TargetHttpsProxyMethods` instance. +/// +/// # 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_https_proxies().delete("project", "targetHttpsProxy") +/// .doit(); +/// # } +/// ``` +pub struct TargetHttpsProxyDeleteCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _target_https_proxy: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for TargetHttpsProxyDeleteCall<'a, C, A> {} + +impl<'a, C, A> TargetHttpsProxyDeleteCall<'a, C, A> where 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.targetHttpsProxies.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(("targetHttpsProxy", self._target_https_proxy.to_string())); + for &field in ["alt", "project", "targetHttpsProxy"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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/targetHttpsProxies/{targetHttpsProxy}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{targetHttpsProxy}", "targetHttpsProxy")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["targetHttpsProxy", "project"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Name of the project scoping this request. + /// + /// 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) -> TargetHttpsProxyDeleteCall<'a, C, A> { + self._project = new_value.to_string(); + self + } + /// Name of the TargetHttpsProxy resource to delete. + /// + /// Sets the *target https 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. + pub fn target_https_proxy(mut self, new_value: &str) -> TargetHttpsProxyDeleteCall<'a, C, A> { + self._target_https_proxy = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> TargetHttpsProxyDeleteCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> TargetHttpsProxyDeleteCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> TargetHttpsProxyDeleteCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Returns the specified TargetHttpsProxy resource. +/// +/// A builder for the *get* method supported by a *targetHttpsProxy* resource. +/// It is not used directly, but through a `TargetHttpsProxyMethods` instance. +/// +/// # 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_https_proxies().get("project", "targetHttpsProxy") +/// .doit(); +/// # } +/// ``` +pub struct TargetHttpsProxyGetCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _target_https_proxy: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for TargetHttpsProxyGetCall<'a, C, A> {} + +impl<'a, C, A> TargetHttpsProxyGetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, TargetHttpsProxy)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.targetHttpsProxies.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(("targetHttpsProxy", self._target_https_proxy.to_string())); + for &field in ["alt", "project", "targetHttpsProxy"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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/targetHttpsProxies/{targetHttpsProxy}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{targetHttpsProxy}", "targetHttpsProxy")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["targetHttpsProxy", "project"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Name of the project scoping this request. + /// + /// 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) -> TargetHttpsProxyGetCall<'a, C, A> { + self._project = new_value.to_string(); + self + } + /// Name of the TargetHttpsProxy resource to return. + /// + /// Sets the *target https 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. + pub fn target_https_proxy(mut self, new_value: &str) -> TargetHttpsProxyGetCall<'a, C, A> { + self._target_https_proxy = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> TargetHttpsProxyGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> TargetHttpsProxyGetCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Readonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> TargetHttpsProxyGetCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Changes the URL map for TargetHttpsProxy. +/// +/// A builder for the *setUrlMap* method supported by a *targetHttpsProxy* resource. +/// It is not used directly, but through a `TargetHttpsProxyMethods` instance. +/// +/// # 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(); +/// +/// // You can configure optional parameters by calling 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_https_proxies().set_url_map(req, "project", "targetHttpsProxy") +/// .doit(); +/// # } +/// ``` +pub struct TargetHttpsProxySetUrlMapCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Compute, + _request: UrlMapReference, + _project: String, + _target_https_proxy: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for TargetHttpsProxySetUrlMapCall<'a, C, A> {} + +impl<'a, C, A> TargetHttpsProxySetUrlMapCall<'a, C, A> where 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.targetHttpsProxies.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(("targetHttpsProxy", self._target_https_proxy.to_string())); + for &field in ["alt", "project", "targetHttpsProxy"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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}/targetHttpsProxies/{targetHttpsProxy}/setUrlMap".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{targetHttpsProxy}", "targetHttpsProxy")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["targetHttpsProxy", "project"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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) -> TargetHttpsProxySetUrlMapCall<'a, C, A> { + self._request = new_value; + self + } + /// Name of the project scoping this request. + /// + /// 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) -> TargetHttpsProxySetUrlMapCall<'a, C, A> { + self._project = new_value.to_string(); + self + } + /// Name of the TargetHttpsProxy resource whose URL map is to be set. + /// + /// Sets the *target https 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. + pub fn target_https_proxy(mut self, new_value: &str) -> TargetHttpsProxySetUrlMapCall<'a, C, A> { + self._target_https_proxy = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> TargetHttpsProxySetUrlMapCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> TargetHttpsProxySetUrlMapCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> TargetHttpsProxySetUrlMapCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Creates a TargetHttpsProxy resource in the specified project using the data included in the request. +/// +/// A builder for the *insert* method supported by a *targetHttpsProxy* resource. +/// It is not used directly, but through a `TargetHttpsProxyMethods` instance. +/// +/// # 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::TargetHttpsProxy; +/// # #[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 = TargetHttpsProxy::default(); +/// +/// // You can configure optional parameters by calling 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_https_proxies().insert(req, "project") +/// .doit(); +/// # } +/// ``` +pub struct TargetHttpsProxyInsertCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Compute, + _request: TargetHttpsProxy, + _project: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for TargetHttpsProxyInsertCall<'a, C, A> {} + +impl<'a, C, A> TargetHttpsProxyInsertCall<'a, C, A> where 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.targetHttpsProxies.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 Err(Error::FieldClash(field)); + } + } + for (name, 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/targetHttpsProxies".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: TargetHttpsProxy) -> TargetHttpsProxyInsertCall<'a, C, A> { + self._request = new_value; + self + } + /// Name of the project scoping this request. + /// + /// 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) -> TargetHttpsProxyInsertCall<'a, C, A> { + self._project = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> TargetHttpsProxyInsertCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> TargetHttpsProxyInsertCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> TargetHttpsProxyInsertCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Replaces SslCertificates for TargetHttpsProxy. +/// +/// A builder for the *setSslCertificates* method supported by a *targetHttpsProxy* resource. +/// It is not used directly, but through a `TargetHttpsProxyMethods` instance. +/// +/// # 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::TargetHttpsProxiesSetSslCertificatesRequest; +/// # #[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 = TargetHttpsProxiesSetSslCertificatesRequest::default(); +/// +/// // You can configure optional parameters by calling 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_https_proxies().set_ssl_certificates(req, "project", "targetHttpsProxy") +/// .doit(); +/// # } +/// ``` +pub struct TargetHttpsProxySetSslCertificateCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Compute, + _request: TargetHttpsProxiesSetSslCertificatesRequest, + _project: String, + _target_https_proxy: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for TargetHttpsProxySetSslCertificateCall<'a, C, A> {} + +impl<'a, C, A> TargetHttpsProxySetSslCertificateCall<'a, C, A> where 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.targetHttpsProxies.setSslCertificates", + 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(("targetHttpsProxy", self._target_https_proxy.to_string())); + for &field in ["alt", "project", "targetHttpsProxy"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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}/targetHttpsProxies/{targetHttpsProxy}/setSslCertificates".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{targetHttpsProxy}", "targetHttpsProxy")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["targetHttpsProxy", "project"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: TargetHttpsProxiesSetSslCertificatesRequest) -> TargetHttpsProxySetSslCertificateCall<'a, C, A> { + self._request = new_value; + self + } + /// Name of the project scoping this request. + /// + /// 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) -> TargetHttpsProxySetSslCertificateCall<'a, C, A> { + self._project = new_value.to_string(); + self + } + /// Name of the TargetHttpsProxy resource whose URL map is to be set. + /// + /// Sets the *target https 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. + pub fn target_https_proxy(mut self, new_value: &str) -> TargetHttpsProxySetSslCertificateCall<'a, C, A> { + self._target_https_proxy = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> TargetHttpsProxySetSslCertificateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> TargetHttpsProxySetSslCertificateCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> TargetHttpsProxySetSslCertificateCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Retrieves the list of TargetHttpsProxy resources available to the specified project. +/// +/// A builder for the *list* method supported by a *targetHttpsProxy* resource. +/// It is not used directly, but through a `TargetHttpsProxyMethods` instance. +/// +/// # 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_https_proxies().list("project") +/// .page_token("consetetur") +/// .max_results(92) +/// .filter("elitr") +/// .doit(); +/// # } +/// ``` +pub struct TargetHttpsProxyListCall<'a, C, A> + where C: '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, A> CallBuilder for TargetHttpsProxyListCall<'a, C, A> {} + +impl<'a, C, A> TargetHttpsProxyListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, TargetHttpsProxyList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.targetHttpsProxies.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 Err(Error::FieldClash(field)); + } + } + for (name, 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/targetHttpsProxies".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Name of the project scoping this request. + /// + /// 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) -> TargetHttpsProxyListCall<'a, C, A> { + self._project = new_value.to_string(); + self + } + /// Specifies a page token to use. Use this parameter if you want to list the next page of results. Set pageToken to the nextPageToken returned by a previous list request. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> TargetHttpsProxyListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Maximum count of results to be returned. + /// + /// Sets the *max results* query property to the given value. + pub fn max_results(mut self, new_value: u32) -> TargetHttpsProxyListCall<'a, C, A> { + self._max_results = Some(new_value); + self + } + /// Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must be in the format: FIELD_NAME COMPARISON_STRING LITERAL_STRING. + /// + /// The FIELD_NAME is the name of the field you want to compare. Only atomic field types are supported (string, number, boolean). The COMPARISON_STRING must be either eq (equals) or ne (not equals). The LITERAL_STRING is the string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field. + /// + /// For example, filter=name ne example-instance. + /// + /// Sets the *filter* query property to the given value. + pub fn filter(mut self, new_value: &str) -> TargetHttpsProxyListCall<'a, C, A> { + self._filter = Some(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> TargetHttpsProxyListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> TargetHttpsProxyListCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Readonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> TargetHttpsProxyListCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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. @@ -29123,9 +28847,9 @@ impl<'a, C, A> NetworkInsertCall<'a, C, A> where C: BorrowMut, A: /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.networks().list("project") -/// .page_token("dolore") -/// .max_results(96) -/// .filter("consetetur") +/// .page_token("consetetur") +/// .max_results(22) +/// .filter("accusam") /// .doit(); /// # } /// ``` @@ -29309,14 +29033,11 @@ impl<'a, C, A> NetworkListCall<'a, C, A> where C: BorrowMut, A: o self._max_results = Some(new_value); self } - /// Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must contain the following: - /// FIELD_NAME COMPARISON_STRING LITERAL_STRING - /// - /// - FIELD_NAME: The name of the field you want to compare. The field name must be valid for the type of resource being filtered. Only atomic field types are supported (string, number, boolean). Array and object fields are not currently supported. - /// - COMPARISON_STRING: The comparison string, either eq (equals) or ne (not equals). - /// - LITERAL_STRING: The literal string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field. For example, you can filter by the name of a resource: - /// filter=name ne example-instance - /// The above filter returns only results whose name field does not equal example-instance. You can also enclose your literal string in single, double, or no quotes. + /// Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must be in the format: FIELD_NAME COMPARISON_STRING LITERAL_STRING. + /// + /// The FIELD_NAME is the name of the field you want to compare. Only atomic field types are supported (string, number, boolean). The COMPARISON_STRING must be either eq (equals) or ne (not equals). The LITERAL_STRING is the string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field. + /// + /// For example, filter=name ne example-instance. /// /// Sets the *filter* query property to the given value. pub fn filter(mut self, new_value: &str) -> NetworkListCall<'a, C, A> { @@ -29898,9 +29619,9 @@ impl<'a, C, A> NetworkGetCall<'a, C, A> where C: BorrowMut, A: oa /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.global_operations().list("project") -/// .page_token("sadipscing") -/// .max_results(28) -/// .filter("magna") +/// .page_token("ea") +/// .max_results(66) +/// .filter("Stet") /// .doit(); /// # } /// ``` @@ -30084,14 +29805,11 @@ impl<'a, C, A> GlobalOperationListCall<'a, C, A> where C: BorrowMut GlobalOperationListCall<'a, C, A> { @@ -30177,9 +29895,9 @@ impl<'a, C, A> GlobalOperationListCall<'a, C, A> where C: BorrowMut GlobalOperationAggregatedListCall<'a, C, A> where C: BorrowMut GlobalOperationAggregatedListCall<'a, C, A> { @@ -31461,9 +31176,9 @@ impl<'a, C, A> AutoscalerGetCall<'a, C, A> where C: BorrowMut, A: /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.autoscalers().list("project", "zone") -/// .page_token("dolore") -/// .max_results(18) -/// .filter("elitr") +/// .page_token("et") +/// .max_results(37) +/// .filter("eos") /// .doit(); /// # } /// ``` @@ -31659,14 +31374,11 @@ impl<'a, C, A> AutoscalerListCall<'a, C, A> where C: BorrowMut, A self._max_results = Some(new_value); self } - /// Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must contain the following: - /// FIELD_NAME COMPARISON_STRING LITERAL_STRING - /// - /// - FIELD_NAME: The name of the field you want to compare. The field name must be valid for the type of resource being filtered. Only atomic field types are supported (string, number, boolean). Array and object fields are not currently supported. - /// - COMPARISON_STRING: The comparison string, either eq (equals) or ne (not equals). - /// - LITERAL_STRING: The literal string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field. For example, you can filter by the name of a resource: - /// filter=name ne example-instance - /// The above filter returns only results whose name field does not equal example-instance. You can also enclose your literal string in single, double, or no quotes. + /// Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must be in the format: FIELD_NAME COMPARISON_STRING LITERAL_STRING. + /// + /// The FIELD_NAME is the name of the field you want to compare. Only atomic field types are supported (string, number, boolean). The COMPARISON_STRING must be either eq (equals) or ne (not equals). The LITERAL_STRING is the string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field. + /// + /// For example, filter=name ne example-instance. /// /// Sets the *filter* query property to the given value. pub fn filter(mut self, new_value: &str) -> AutoscalerListCall<'a, C, A> { @@ -32322,9 +32034,9 @@ impl<'a, C, A> AutoscalerInsertCall<'a, C, A> where C: BorrowMut, /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.autoscalers().aggregated_list("project") -/// .page_token("nonumy") -/// .max_results(8) -/// .filter("diam") +/// .page_token("justo") +/// .max_results(62) +/// .filter("gubergren") /// .doit(); /// # } /// ``` @@ -32508,14 +32220,11 @@ impl<'a, C, A> AutoscalerAggregatedListCall<'a, C, A> where C: BorrowMut AutoscalerAggregatedListCall<'a, C, A> { @@ -32607,7 +32316,7 @@ impl<'a, C, A> AutoscalerAggregatedListCall<'a, C, A> where C: BorrowMut AutoscalerUpdateCall<'a, C, A> where C: BorrowMut, } -/// Deletes the specified instance group. +/// Deletes the specified instance group. The instances in the group are not deleted. /// /// A builder for the *delete* method supported by a *instanceGroup* resource. /// It is not used directly, but through a `InstanceGroupMethods` instance. @@ -33053,7 +32762,7 @@ impl<'a, C, A> InstanceGroupDeleteCall<'a, C, A> where C: BorrowMut InstanceGroupDeleteCall<'a, C, A> where C: BorrowMut InstanceGroupDeleteCall<'a, C, A> where C: BorrowMut InstanceGroupListInstanceCall<'a, C, A> where C: BorrowMut InstanceGroupListInstanceCall<'a, C, A> where C: BorrowMut InstanceGroupListInstanceCall<'a, C, A> { @@ -33676,7 +33382,7 @@ impl<'a, C, A> InstanceGroupInsertCall<'a, C, A> where C: BorrowMut InstanceGroupGetCall<'a, C, A> where C: BorrowMut, self._project = new_value.to_string(); self } - /// The URL of the zone where the instance group is located. + /// The name of the zone where the instance group is located. /// /// Sets the *zone* path property to the given value. /// @@ -33998,7 +33704,7 @@ impl<'a, C, A> InstanceGroupGetCall<'a, C, A> where C: BorrowMut, } -/// Removes a list of instances from an instance group. +/// Removes one or more instances from the specified instance group, but does not delete those instances. /// /// A builder for the *removeInstances* method supported by a *instanceGroup* resource. /// It is not used directly, but through a `InstanceGroupMethods` instance. @@ -34217,7 +33923,7 @@ impl<'a, C, A> InstanceGroupRemoveInstanceCall<'a, C, A> where C: BorrowMut InstanceGroupRemoveInstanceCall<'a, C, A> where C: BorrowMut InstanceGroupAddInstanceCall<'a, C, A> where C: BorrowMut InstanceGroupAddInstanceCall<'a, C, A> where C: BorrowMut InstanceGroupSetNamedPortCall<'a, C, A> where C: BorrowMut InstanceGroupSetNamedPortCall<'a, C, A> where C: BorrowMut InstanceGroupSetNamedPortCall<'a, C, A> where C: BorrowMut InstanceGroupAggregatedListCall<'a, C, A> where C: BorrowMut InstanceGroupAggregatedListCall<'a, C, A> { @@ -35177,9 +34880,9 @@ impl<'a, C, A> InstanceGroupAggregatedListCall<'a, C, A> where C: BorrowMut InstanceGroupListCall<'a, C, A> where C: BorrowMut self._project = new_value.to_string(); self } - /// The URL of the zone where the instance group is located. + /// The name of the zone where the instance group is located. /// /// Sets the *zone* path property to the given value. /// @@ -35375,14 +35078,11 @@ impl<'a, C, A> InstanceGroupListCall<'a, C, A> where C: BorrowMut self._max_results = Some(new_value); self } - /// Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must contain the following: - /// FIELD_NAME COMPARISON_STRING LITERAL_STRING - /// - /// - FIELD_NAME: The name of the field you want to compare. The field name must be valid for the type of resource being filtered. Only atomic field types are supported (string, number, boolean). Array and object fields are not currently supported. - /// - COMPARISON_STRING: The comparison string, either eq (equals) or ne (not equals). - /// - LITERAL_STRING: The literal string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field. For example, you can filter by the name of a resource: - /// filter=name ne example-instance - /// The above filter returns only results whose name field does not equal example-instance. You can also enclose your literal string in single, double, or no quotes. + /// Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must be in the format: FIELD_NAME COMPARISON_STRING LITERAL_STRING. + /// + /// The FIELD_NAME is the name of the field you want to compare. Only atomic field types are supported (string, number, boolean). The COMPARISON_STRING must be either eq (equals) or ne (not equals). The LITERAL_STRING is the string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field. + /// + /// For example, filter=name ne example-instance. /// /// Sets the *filter* query property to the given value. pub fn filter(mut self, new_value: &str) -> InstanceGroupListCall<'a, C, A> { @@ -35468,9 +35168,9 @@ impl<'a, C, A> InstanceGroupListCall<'a, C, A> where C: BorrowMut /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.regions().list("project") -/// .page_token("sit") -/// .max_results(68) -/// .filter("et") +/// .page_token("gubergren") +/// .max_results(3) +/// .filter("gubergren") /// .doit(); /// # } /// ``` @@ -35654,14 +35354,11 @@ impl<'a, C, A> RegionListCall<'a, C, A> where C: BorrowMut, A: oa self._max_results = Some(new_value); self } - /// Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must contain the following: - /// FIELD_NAME COMPARISON_STRING LITERAL_STRING - /// - /// - FIELD_NAME: The name of the field you want to compare. The field name must be valid for the type of resource being filtered. Only atomic field types are supported (string, number, boolean). Array and object fields are not currently supported. - /// - COMPARISON_STRING: The comparison string, either eq (equals) or ne (not equals). - /// - LITERAL_STRING: The literal string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field. For example, you can filter by the name of a resource: - /// filter=name ne example-instance - /// The above filter returns only results whose name field does not equal example-instance. You can also enclose your literal string in single, double, or no quotes. + /// Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must be in the format: FIELD_NAME COMPARISON_STRING LITERAL_STRING. + /// + /// The FIELD_NAME is the name of the field you want to compare. Only atomic field types are supported (string, number, boolean). The COMPARISON_STRING must be either eq (equals) or ne (not equals). The LITERAL_STRING is the string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field. + /// + /// For example, filter=name ne example-instance. /// /// Sets the *filter* query property to the given value. pub fn filter(mut self, new_value: &str) -> RegionListCall<'a, C, A> { @@ -36565,9 +36262,9 @@ impl<'a, C, A> ForwardingRuleSetTargetCall<'a, C, A> where C: BorrowMut ForwardingRuleListCall<'a, C, A> where C: BorrowMut ForwardingRuleListCall<'a, C, A> { @@ -36856,9 +36550,9 @@ impl<'a, C, A> ForwardingRuleListCall<'a, C, A> where C: BorrowMut ForwardingRuleAggregatedListCall<'a, C, A> where C: BorrowMut ForwardingRuleAggregatedListCall<'a, C, A> { @@ -38810,7 +38501,7 @@ impl<'a, C, A> TargetPoolGetHealthCall<'a, C, A> where C: BorrowMut TargetPoolSetBackupCall<'a, C, A> where C: BorrowMut TargetPoolAggregatedListCall<'a, C, A> where C: BorrowMut TargetPoolAggregatedListCall<'a, C, A> { @@ -40486,9 +40174,9 @@ impl<'a, C, A> TargetPoolDeleteCall<'a, C, A> where C: BorrowMut, /// // 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("amet") -/// .max_results(59) -/// .filter("sit") +/// .page_token("est") +/// .max_results(53) +/// .filter("et") /// .doit(); /// # } /// ``` @@ -40684,14 +40372,11 @@ impl<'a, C, A> TargetPoolListCall<'a, C, A> where C: BorrowMut, A self._max_results = Some(new_value); self } - /// Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must contain the following: - /// FIELD_NAME COMPARISON_STRING LITERAL_STRING - /// - /// - FIELD_NAME: The name of the field you want to compare. The field name must be valid for the type of resource being filtered. Only atomic field types are supported (string, number, boolean). Array and object fields are not currently supported. - /// - COMPARISON_STRING: The comparison string, either eq (equals) or ne (not equals). - /// - LITERAL_STRING: The literal string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field. For example, you can filter by the name of a resource: - /// filter=name ne example-instance - /// The above filter returns only results whose name field does not equal example-instance. You can also enclose your literal string in single, double, or no quotes. + /// Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must be in the format: FIELD_NAME COMPARISON_STRING LITERAL_STRING. + /// + /// The FIELD_NAME is the name of the field you want to compare. Only atomic field types are supported (string, number, boolean). The COMPARISON_STRING must be either eq (equals) or ne (not equals). The LITERAL_STRING is the string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field. + /// + /// For example, filter=name ne example-instance. /// /// Sets the *filter* query property to the given value. pub fn filter(mut self, new_value: &str) -> TargetPoolListCall<'a, C, A> { @@ -40777,9 +40462,9 @@ impl<'a, C, A> TargetPoolListCall<'a, C, A> where C: BorrowMut, A /// // 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("et") -/// .max_results(94) -/// .filter("takimata") +/// .page_token("nonumy") +/// .max_results(56) +/// .filter("accusam") /// .doit(); /// # } /// ``` @@ -40975,14 +40660,11 @@ impl<'a, C, A> TargetInstanceListCall<'a, C, A> where C: BorrowMut TargetInstanceListCall<'a, C, A> { @@ -41347,9 +41029,9 @@ impl<'a, C, A> TargetInstanceInsertCall<'a, C, A> where C: BorrowMut TargetInstanceAggregatedListCall<'a, C, A> where C: BorrowMut TargetInstanceAggregatedListCall<'a, C, A> { @@ -42940,9 +42619,9 @@ impl<'a, C, A> GlobalForwardingRuleInsertCall<'a, C, A> where C: BorrowMut GlobalForwardingRuleListCall<'a, C, A> where C: BorrowMut GlobalForwardingRuleListCall<'a, C, A> { @@ -43440,6 +43116,1603 @@ impl<'a, C, A> GlobalForwardingRuleGetCall<'a, C, A> where C: BorrowMut::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.https_health_checks().delete("project", "httpsHealthCheck") +/// .doit(); +/// # } +/// ``` +pub struct HttpsHealthCheckDeleteCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _https_health_check: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for HttpsHealthCheckDeleteCall<'a, C, A> {} + +impl<'a, C, A> HttpsHealthCheckDeleteCall<'a, C, A> where 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.httpsHealthChecks.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(("httpsHealthCheck", self._https_health_check.to_string())); + for &field in ["alt", "project", "httpsHealthCheck"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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/httpsHealthChecks/{httpsHealthCheck}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{httpsHealthCheck}", "httpsHealthCheck")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["httpsHealthCheck", "project"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Name of the project scoping this request. + /// + /// 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) -> HttpsHealthCheckDeleteCall<'a, C, A> { + self._project = new_value.to_string(); + self + } + /// Name of the HttpsHealthCheck resource to delete. + /// + /// Sets the *https 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. + pub fn https_health_check(mut self, new_value: &str) -> HttpsHealthCheckDeleteCall<'a, C, A> { + self._https_health_check = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> HttpsHealthCheckDeleteCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> HttpsHealthCheckDeleteCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> HttpsHealthCheckDeleteCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Retrieves the list of HttpsHealthCheck resources available to the specified project. +/// +/// A builder for the *list* method supported by a *httpsHealthCheck* resource. +/// It is not used directly, but through a `HttpsHealthCheckMethods` instance. +/// +/// # 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.https_health_checks().list("project") +/// .page_token("et") +/// .max_results(49) +/// .filter("eirmod") +/// .doit(); +/// # } +/// ``` +pub struct HttpsHealthCheckListCall<'a, C, A> + where C: '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, A> CallBuilder for HttpsHealthCheckListCall<'a, C, A> {} + +impl<'a, C, A> HttpsHealthCheckListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, HttpsHealthCheckList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.httpsHealthChecks.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 Err(Error::FieldClash(field)); + } + } + for (name, 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/httpsHealthChecks".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Name of the project scoping this request. + /// + /// 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) -> HttpsHealthCheckListCall<'a, C, A> { + self._project = new_value.to_string(); + self + } + /// Specifies a page token to use. Use this parameter if you want to list the next page of results. Set pageToken to the nextPageToken returned by a previous list request. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> HttpsHealthCheckListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Maximum count of results to be returned. + /// + /// Sets the *max results* query property to the given value. + pub fn max_results(mut self, new_value: u32) -> HttpsHealthCheckListCall<'a, C, A> { + self._max_results = Some(new_value); + self + } + /// Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must be in the format: FIELD_NAME COMPARISON_STRING LITERAL_STRING. + /// + /// The FIELD_NAME is the name of the field you want to compare. Only atomic field types are supported (string, number, boolean). The COMPARISON_STRING must be either eq (equals) or ne (not equals). The LITERAL_STRING is the string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field. + /// + /// For example, filter=name ne example-instance. + /// + /// Sets the *filter* query property to the given value. + pub fn filter(mut self, new_value: &str) -> HttpsHealthCheckListCall<'a, C, A> { + self._filter = Some(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> HttpsHealthCheckListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> HttpsHealthCheckListCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Readonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> HttpsHealthCheckListCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Creates a HttpsHealthCheck resource in the specified project using the data included in the request. +/// +/// A builder for the *insert* method supported by a *httpsHealthCheck* resource. +/// It is not used directly, but through a `HttpsHealthCheckMethods` instance. +/// +/// # 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::HttpsHealthCheck; +/// # #[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 = HttpsHealthCheck::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.https_health_checks().insert(req, "project") +/// .doit(); +/// # } +/// ``` +pub struct HttpsHealthCheckInsertCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Compute, + _request: HttpsHealthCheck, + _project: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for HttpsHealthCheckInsertCall<'a, C, A> {} + +impl<'a, C, A> HttpsHealthCheckInsertCall<'a, C, A> where 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.httpsHealthChecks.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 Err(Error::FieldClash(field)); + } + } + for (name, 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/httpsHealthChecks".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: HttpsHealthCheck) -> HttpsHealthCheckInsertCall<'a, C, A> { + self._request = new_value; + self + } + /// Name of the project scoping this request. + /// + /// 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) -> HttpsHealthCheckInsertCall<'a, C, A> { + self._project = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> HttpsHealthCheckInsertCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> HttpsHealthCheckInsertCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> HttpsHealthCheckInsertCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Returns the specified HttpsHealthCheck resource. +/// +/// A builder for the *get* method supported by a *httpsHealthCheck* resource. +/// It is not used directly, but through a `HttpsHealthCheckMethods` instance. +/// +/// # 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.https_health_checks().get("project", "httpsHealthCheck") +/// .doit(); +/// # } +/// ``` +pub struct HttpsHealthCheckGetCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _https_health_check: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for HttpsHealthCheckGetCall<'a, C, A> {} + +impl<'a, C, A> HttpsHealthCheckGetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, HttpsHealthCheck)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.httpsHealthChecks.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(("httpsHealthCheck", self._https_health_check.to_string())); + for &field in ["alt", "project", "httpsHealthCheck"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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/httpsHealthChecks/{httpsHealthCheck}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{httpsHealthCheck}", "httpsHealthCheck")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["httpsHealthCheck", "project"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Name of the project scoping this request. + /// + /// 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) -> HttpsHealthCheckGetCall<'a, C, A> { + self._project = new_value.to_string(); + self + } + /// Name of the HttpsHealthCheck resource to return. + /// + /// Sets the *https 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. + pub fn https_health_check(mut self, new_value: &str) -> HttpsHealthCheckGetCall<'a, C, A> { + self._https_health_check = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> HttpsHealthCheckGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> HttpsHealthCheckGetCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Readonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> HttpsHealthCheckGetCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Updates a HttpsHealthCheck resource in the specified project using the data included in the request. +/// +/// A builder for the *update* method supported by a *httpsHealthCheck* resource. +/// It is not used directly, but through a `HttpsHealthCheckMethods` instance. +/// +/// # 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::HttpsHealthCheck; +/// # #[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 = HttpsHealthCheck::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.https_health_checks().update(req, "project", "httpsHealthCheck") +/// .doit(); +/// # } +/// ``` +pub struct HttpsHealthCheckUpdateCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Compute, + _request: HttpsHealthCheck, + _project: String, + _https_health_check: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for HttpsHealthCheckUpdateCall<'a, C, A> {} + +impl<'a, C, A> HttpsHealthCheckUpdateCall<'a, C, A> where 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.httpsHealthChecks.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(("httpsHealthCheck", self._https_health_check.to_string())); + for &field in ["alt", "project", "httpsHealthCheck"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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/httpsHealthChecks/{httpsHealthCheck}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{httpsHealthCheck}", "httpsHealthCheck")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["httpsHealthCheck", "project"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: HttpsHealthCheck) -> HttpsHealthCheckUpdateCall<'a, C, A> { + self._request = new_value; + self + } + /// Name of the project scoping this request. + /// + /// 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) -> HttpsHealthCheckUpdateCall<'a, C, A> { + self._project = new_value.to_string(); + self + } + /// Name of the HttpsHealthCheck resource to update. + /// + /// Sets the *https 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. + pub fn https_health_check(mut self, new_value: &str) -> HttpsHealthCheckUpdateCall<'a, C, A> { + self._https_health_check = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> HttpsHealthCheckUpdateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> HttpsHealthCheckUpdateCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> HttpsHealthCheckUpdateCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Updates a HttpsHealthCheck 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 *httpsHealthCheck* resource. +/// It is not used directly, but through a `HttpsHealthCheckMethods` instance. +/// +/// # 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::HttpsHealthCheck; +/// # #[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 = HttpsHealthCheck::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.https_health_checks().patch(req, "project", "httpsHealthCheck") +/// .doit(); +/// # } +/// ``` +pub struct HttpsHealthCheckPatchCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Compute, + _request: HttpsHealthCheck, + _project: String, + _https_health_check: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for HttpsHealthCheckPatchCall<'a, C, A> {} + +impl<'a, C, A> HttpsHealthCheckPatchCall<'a, C, A> where 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.httpsHealthChecks.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(("httpsHealthCheck", self._https_health_check.to_string())); + for &field in ["alt", "project", "httpsHealthCheck"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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/httpsHealthChecks/{httpsHealthCheck}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{httpsHealthCheck}", "httpsHealthCheck")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["httpsHealthCheck", "project"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: HttpsHealthCheck) -> HttpsHealthCheckPatchCall<'a, C, A> { + self._request = new_value; + self + } + /// Name of the project scoping this request. + /// + /// 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) -> HttpsHealthCheckPatchCall<'a, C, A> { + self._project = new_value.to_string(); + self + } + /// Name of the HttpsHealthCheck resource to update. + /// + /// Sets the *https 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. + pub fn https_health_check(mut self, new_value: &str) -> HttpsHealthCheckPatchCall<'a, C, A> { + self._https_health_check = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> HttpsHealthCheckPatchCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> HttpsHealthCheckPatchCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> HttpsHealthCheckPatchCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + /// Retrieves the list of machine type resources grouped by scope. /// /// A builder for the *aggregatedList* method supported by a *machineType* resource. @@ -43467,9 +44740,9 @@ impl<'a, C, A> GlobalForwardingRuleGetCall<'a, C, A> where C: BorrowMut MachineTypeAggregatedListCall<'a, C, A> where C: BorrowMut MachineTypeAggregatedListCall<'a, C, A> { @@ -44006,9 +45276,9 @@ impl<'a, C, A> MachineTypeGetCall<'a, C, A> where C: BorrowMut, A /// // 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("labore") -/// .max_results(50) -/// .filter("aliquyam") +/// .page_token("ipsum") +/// .max_results(66) +/// .filter("Lorem") /// .doit(); /// # } /// ``` @@ -44204,14 +45474,11 @@ impl<'a, C, A> MachineTypeListCall<'a, C, A> where C: BorrowMut, self._max_results = Some(new_value); self } - /// Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must contain the following: - /// FIELD_NAME COMPARISON_STRING LITERAL_STRING - /// - /// - FIELD_NAME: The name of the field you want to compare. The field name must be valid for the type of resource being filtered. Only atomic field types are supported (string, number, boolean). Array and object fields are not currently supported. - /// - COMPARISON_STRING: The comparison string, either eq (equals) or ne (not equals). - /// - LITERAL_STRING: The literal string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field. For example, you can filter by the name of a resource: - /// filter=name ne example-instance - /// The above filter returns only results whose name field does not equal example-instance. You can also enclose your literal string in single, double, or no quotes. + /// Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must be in the format: FIELD_NAME COMPARISON_STRING LITERAL_STRING. + /// + /// The FIELD_NAME is the name of the field you want to compare. Only atomic field types are supported (string, number, boolean). The COMPARISON_STRING must be either eq (equals) or ne (not equals). The LITERAL_STRING is the string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field. + /// + /// For example, filter=name ne example-instance. /// /// Sets the *filter* query property to the given value. pub fn filter(mut self, new_value: &str) -> MachineTypeListCall<'a, C, A> { @@ -44297,9 +45564,9 @@ impl<'a, C, A> MachineTypeListCall<'a, C, A> where C: BorrowMut, /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.target_vpn_gateways().aggregated_list("project") -/// .page_token("et") -/// .max_results(55) -/// .filter("et") +/// .page_token("sanctus") +/// .max_results(67) +/// .filter("consetetur") /// .doit(); /// # } /// ``` @@ -44483,14 +45750,11 @@ impl<'a, C, A> TargetVpnGatewayAggregatedListCall<'a, C, A> where C: BorrowMut TargetVpnGatewayAggregatedListCall<'a, C, A> { @@ -44836,9 +46100,9 @@ impl<'a, C, A> TargetVpnGatewayGetCall<'a, C, A> where C: BorrowMut TargetVpnGatewayListCall<'a, C, A> where C: BorrowMut TargetVpnGatewayListCall<'a, C, A> { @@ -45639,10 +46900,10 @@ impl<'a, C, A> TargetVpnGatewayDeleteCall<'a, C, A> where C: BorrowMut TargetVpnGatewayDeleteCall<'a, C, A> where C: BorrowMut +pub struct InstanceGroupManagerResizeCall<'a, C, A> where C: 'a, A: 'a { hub: &'a Compute, _project: String, _zone: String, - _disk_type: String, + _instance_group_manager: String, + _size: i32, _delegate: Option<&'a mut Delegate>, _additional_params: HashMap, _scopes: BTreeMap } -impl<'a, C, A> CallBuilder for DiskTypeGetCall<'a, C, A> {} +impl<'a, C, A> CallBuilder for InstanceGroupManagerResizeCall<'a, C, A> {} -impl<'a, C, A> DiskTypeGetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { +impl<'a, C, A> InstanceGroupManagerResizeCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { /// Perform the operation you have build so far. - pub fn doit(mut self) -> Result<(hyper::client::Response, DiskType)> { + 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; @@ -45695,13 +46957,14 @@ impl<'a, C, A> DiskTypeGetCall<'a, C, A> where C: BorrowMut, A: o 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())); + dlg.begin(MethodInfo { id: "compute.instanceGroupManagers.resize", + 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(("diskType", self._disk_type.to_string())); - for &field in ["alt", "project", "zone", "diskType"].iter() { + params.push(("instanceGroupManager", self._instance_group_manager.to_string())); + params.push(("size", self._size.to_string())); + for &field in ["alt", "project", "zone", "instanceGroupManager", "size"].iter() { if self._additional_params.contains_key(field) { dlg.finished(false); return Err(Error::FieldClash(field)); @@ -45713,12 +46976,12 @@ impl<'a, C, A> DiskTypeGetCall<'a, C, A> where C: BorrowMut, A: o params.push(("alt", "json".to_string())); - let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/zones/{zone}/diskTypes/{diskType}".to_string(); + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/zones/{zone}/instanceGroupManagers/{instanceGroupManager}/resize".to_string(); if self._scopes.len() == 0 { - self._scopes.insert(Scope::Readonly.as_ref().to_string(), ()); + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); } - for &(find_this, param_name) in [("{project}", "project"), ("{zone}", "zone"), ("{diskType}", "diskType")].iter() { + for &(find_this, param_name) in [("{project}", "project"), ("{zone}", "zone"), ("{instanceGroupManager}", "instanceGroupManager")].iter() { let mut replace_with: Option<&str> = None; for &(name, ref value) in params.iter() { if name == param_name { @@ -45730,7 +46993,7 @@ impl<'a, C, A> DiskTypeGetCall<'a, C, A> where C: BorrowMut, A: o } { let mut indices_for_removal: Vec = Vec::with_capacity(3); - for param_name in ["diskType", "zone", "project"].iter() { + for param_name in ["instanceGroupManager", "zone", "project"].iter() { if let Some(index) = params.iter().position(|t| &t.0 == param_name) { indices_for_removal.push(index); } @@ -45764,7 +47027,7 @@ impl<'a, C, A> DiskTypeGetCall<'a, C, A> where C: BorrowMut, A: o access_token: token.access_token }); let mut req_result = { let mut client = &mut *self.hub.client.borrow_mut(); - let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + let mut req = client.borrow_mut().request(hyper::method::Method::Post, &url) .header(UserAgent(self.hub._user_agent.clone())) .header(auth_header.clone()); @@ -45817,34 +47080,44 @@ impl<'a, C, A> DiskTypeGetCall<'a, C, A> where C: BorrowMut, A: o } - /// Project ID for this request. + /// The project ID for this request. /// /// 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) -> DiskTypeGetCall<'a, C, A> { + pub fn project(mut self, new_value: &str) -> InstanceGroupManagerResizeCall<'a, C, A> { self._project = new_value.to_string(); self } - /// The name of the zone for this request. + /// The name of the zone where the managed instance group is located. /// /// 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) -> DiskTypeGetCall<'a, C, A> { + pub fn zone(mut self, new_value: &str) -> InstanceGroupManagerResizeCall<'a, C, A> { self._zone = new_value.to_string(); self } - /// Name of the disk type resource to return. + /// The name of the managed instance group. /// - /// Sets the *disk type* path property to the given value. + /// Sets the *instance group manager* path property to the given value. /// /// Even though the property as already been set when instantiating this call, /// we provide this method for API completeness. - pub fn disk_type(mut self, new_value: &str) -> DiskTypeGetCall<'a, C, A> { - self._disk_type = new_value.to_string(); + pub fn instance_group_manager(mut self, new_value: &str) -> InstanceGroupManagerResizeCall<'a, C, A> { + self._instance_group_manager = new_value.to_string(); + self + } + /// The number of running instances that the managed instance group should maintain at any given time. The group automatically adds or removes instances to maintain the number of instances specified by this parameter. + /// + /// Sets the *size* 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. + pub fn size(mut self, new_value: i32) -> InstanceGroupManagerResizeCall<'a, C, A> { + self._size = new_value; self } /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong @@ -45853,7 +47126,7 @@ impl<'a, C, A> DiskTypeGetCall<'a, C, A> where C: BorrowMut, A: o /// It should be used to handle progress information, and to implement a certain level of resilience. /// /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> DiskTypeGetCall<'a, C, A> { + pub fn delegate(mut self, new_value: &'a mut Delegate) -> InstanceGroupManagerResizeCall<'a, C, A> { self._delegate = Some(new_value); self } @@ -45874,7 +47147,7 @@ impl<'a, C, A> DiskTypeGetCall<'a, C, A> where C: BorrowMut, A: o /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. /// * *fields* (query-string) - Selector specifying which 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, A> + pub fn param(mut self, name: T, value: T) -> InstanceGroupManagerResizeCall<'a, C, A> where T: AsRef { self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); self @@ -45883,7 +47156,7 @@ impl<'a, C, A> DiskTypeGetCall<'a, C, A> where C: BorrowMut, A: o /// Identifies the authorization scope for the method you are building. /// /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::Readonly`. + /// `Scope::CloudPlatform`. /// /// The `scope` will be added to a set of scopes. This is important as one can maintain access /// tokens for more than one scope. @@ -45891,7 +47164,7 @@ impl<'a, C, A> DiskTypeGetCall<'a, C, A> where C: BorrowMut, A: o /// Usually there is more than one suitable scope to authorize an operation, some of which may /// encompass more rights than others. For example, for listing 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, A> + pub fn add_scope(mut self, scope: T) -> InstanceGroupManagerResizeCall<'a, C, A> where T: AsRef { self._scopes.insert(scope.as_ref().to_string(), ()); self @@ -45899,10 +47172,10 @@ impl<'a, C, A> DiskTypeGetCall<'a, C, A> where C: BorrowMut, A: o } -/// Retrieves the list of disk type resources grouped by scope. +/// Retrieves a list of managed instance groups that are contained within the specified project and zone. /// -/// A builder for the *aggregatedList* method supported by a *diskType* resource. -/// It is not used directly, but through a `DiskTypeMethods` instance. +/// A builder for the *list* method supported by a *instanceGroupManager* resource. +/// It is not used directly, but through a `InstanceGroupManagerMethods` instance. /// /// # Example /// @@ -45925,293 +47198,14 @@ impl<'a, C, A> DiskTypeGetCall<'a, C, A> where C: BorrowMut, A: o /// // You can configure optional parameters by calling 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("eirmod") -/// .max_results(57) -/// .filter("clita") +/// let result = hub.instance_group_managers().list("project", "zone") +/// .page_token("elitr") +/// .max_results(88) +/// .filter("et") /// .doit(); /// # } /// ``` -pub struct DiskTypeAggregatedListCall<'a, C, A> - where C: '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, A> CallBuilder for DiskTypeAggregatedListCall<'a, C, A> {} - -impl<'a, C, A> DiskTypeAggregatedListCall<'a, C, A> where 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 Err(Error::FieldClash(field)); - } - } - for (name, 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_ref().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() { - if let Some(index) = params.iter().position(|t| &t.0 == param_name) { - indices_for_removal.push(index); - } - } - for &index in indices_for_removal.iter() { - params.remove(index); - } - } - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_token }); - let mut req_result = { - let mut client = &mut *self.hub.client.borrow_mut(); - let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = { - let mut json_response = String::new(); - res.read_to_string(&mut json_response).unwrap(); - match json::from_str(&json_response) { - Ok(decoded) => (res, decoded), - Err(err) => { - dlg.response_json_decode_error(&json_response, &err); - return Err(Error::JsonDecodeError(json_response, err)); - } - } - }; - - dlg.finished(true); - return Ok(result_value) - } - } - } - } - - - /// Project ID for this request. - /// - /// 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) -> DiskTypeAggregatedListCall<'a, C, A> { - self._project = new_value.to_string(); - self - } - /// Specifies a page token to use. Use this parameter if you want to list the next page of results. Set pageToken to the nextPageToken returned by a previous list request. - /// - /// Sets the *page token* query property to the given value. - pub fn page_token(mut self, new_value: &str) -> DiskTypeAggregatedListCall<'a, C, A> { - self._page_token = Some(new_value.to_string()); - self - } - /// Maximum count of results to be returned. - /// - /// Sets the *max results* query property to the given value. - pub fn max_results(mut self, new_value: u32) -> DiskTypeAggregatedListCall<'a, C, A> { - self._max_results = Some(new_value); - self - } - /// Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must contain the following: - /// FIELD_NAME COMPARISON_STRING LITERAL_STRING - /// - /// - FIELD_NAME: The name of the field you want to compare. The field name must be valid for the type of resource being filtered. Only atomic field types are supported (string, number, boolean). Array and object fields are not currently supported. - /// - COMPARISON_STRING: The comparison string, either eq (equals) or ne (not equals). - /// - LITERAL_STRING: The literal string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field. For example, you can filter by the name of a resource: - /// filter=name ne example-instance - /// The above filter returns only results whose name field does not equal example-instance. You can also enclose your literal string in single, double, or no quotes. - /// - /// Sets the *filter* query property to the given value. - pub fn filter(mut self, new_value: &str) -> DiskTypeAggregatedListCall<'a, C, A> { - self._filter = Some(new_value.to_string()); - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> DiskTypeAggregatedListCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. - /// * *fields* (query-string) - Selector specifying which 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, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::Readonly`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing 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, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().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` instance. -/// -/// # 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("ea") -/// .max_results(30) -/// .filter("sed") -/// .doit(); -/// # } -/// ``` -pub struct DiskTypeListCall<'a, C, A> +pub struct InstanceGroupManagerListCall<'a, C, A> where C: 'a, A: 'a { hub: &'a Compute, @@ -46225,13 +47219,13 @@ pub struct DiskTypeListCall<'a, C, A> _scopes: BTreeMap } -impl<'a, C, A> CallBuilder for DiskTypeListCall<'a, C, A> {} +impl<'a, C, A> CallBuilder for InstanceGroupManagerListCall<'a, C, A> {} -impl<'a, C, A> DiskTypeListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { +impl<'a, C, A> InstanceGroupManagerListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { /// Perform the operation you have build so far. - pub fn doit(mut self) -> Result<(hyper::client::Response, DiskTypeList)> { + pub fn doit(mut self) -> Result<(hyper::client::Response, InstanceGroupManagerList)> { use std::io::{Read, Seek}; use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; let mut dd = DefaultDelegate; @@ -46239,7 +47233,7 @@ impl<'a, C, A> DiskTypeListCall<'a, C, A> where C: BorrowMut, A: Some(d) => d, None => &mut dd }; - dlg.begin(MethodInfo { id: "compute.diskTypes.list", + dlg.begin(MethodInfo { id: "compute.instanceGroupManagers.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())); @@ -46265,7 +47259,7 @@ impl<'a, C, A> DiskTypeListCall<'a, C, A> where C: BorrowMut, A: params.push(("alt", "json".to_string())); - let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/zones/{zone}/diskTypes".to_string(); + let mut url = "https://www.googleapis.com/compute/v1/projects/{project}/zones/{zone}/instanceGroupManagers".to_string(); if self._scopes.len() == 0 { self._scopes.insert(Scope::Readonly.as_ref().to_string(), ()); } @@ -46369,51 +47363,48 @@ impl<'a, C, A> DiskTypeListCall<'a, C, A> where C: BorrowMut, A: } - /// Project ID for this request. + /// The project ID for this request. /// /// 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) -> DiskTypeListCall<'a, C, A> { + pub fn project(mut self, new_value: &str) -> InstanceGroupManagerListCall<'a, C, A> { self._project = new_value.to_string(); self } - /// The name of the zone for this request. + /// The name of the zone where the managed instance group is located. /// /// 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) -> DiskTypeListCall<'a, C, A> { + pub fn zone(mut self, new_value: &str) -> InstanceGroupManagerListCall<'a, C, A> { self._zone = new_value.to_string(); self } /// Specifies a page token to use. Use this parameter if you want to list the next page of results. Set pageToken to the nextPageToken returned by a previous list request. /// /// Sets the *page token* query property to the given value. - pub fn page_token(mut self, new_value: &str) -> DiskTypeListCall<'a, C, A> { + pub fn page_token(mut self, new_value: &str) -> InstanceGroupManagerListCall<'a, C, A> { self._page_token = Some(new_value.to_string()); self } /// Maximum count of results to be returned. /// /// Sets the *max results* query property to the given value. - pub fn max_results(mut self, new_value: u32) -> DiskTypeListCall<'a, C, A> { + pub fn max_results(mut self, new_value: u32) -> InstanceGroupManagerListCall<'a, C, A> { self._max_results = Some(new_value); self } - /// Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must contain the following: - /// FIELD_NAME COMPARISON_STRING LITERAL_STRING - /// - /// - FIELD_NAME: The name of the field you want to compare. The field name must be valid for the type of resource being filtered. Only atomic field types are supported (string, number, boolean). Array and object fields are not currently supported. - /// - COMPARISON_STRING: The comparison string, either eq (equals) or ne (not equals). - /// - LITERAL_STRING: The literal string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field. For example, you can filter by the name of a resource: - /// filter=name ne example-instance - /// The above filter returns only results whose name field does not equal example-instance. You can also enclose your literal string in single, double, or no quotes. + /// Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must be in the format: FIELD_NAME COMPARISON_STRING LITERAL_STRING. + /// + /// The FIELD_NAME is the name of the field you want to compare. Only atomic field types are supported (string, number, boolean). The COMPARISON_STRING must be either eq (equals) or ne (not equals). The LITERAL_STRING is the string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field. + /// + /// For example, filter=name ne example-instance. /// /// Sets the *filter* query property to the given value. - pub fn filter(mut self, new_value: &str) -> DiskTypeListCall<'a, C, A> { + pub fn filter(mut self, new_value: &str) -> InstanceGroupManagerListCall<'a, C, A> { self._filter = Some(new_value.to_string()); self } @@ -46423,7 +47414,7 @@ impl<'a, C, A> DiskTypeListCall<'a, C, A> where C: BorrowMut, A: /// It should be used to handle progress information, and to implement a certain level of resilience. /// /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> DiskTypeListCall<'a, C, A> { + pub fn delegate(mut self, new_value: &'a mut Delegate) -> InstanceGroupManagerListCall<'a, C, A> { self._delegate = Some(new_value); self } @@ -46444,7 +47435,7 @@ impl<'a, C, A> DiskTypeListCall<'a, C, A> where C: BorrowMut, A: /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. /// * *fields* (query-string) - Selector specifying which 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, A> + pub fn param(mut self, name: T, value: T) -> InstanceGroupManagerListCall<'a, C, A> where T: AsRef { self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); self @@ -46461,7 +47452,2797 @@ impl<'a, C, A> DiskTypeListCall<'a, C, A> where C: BorrowMut, A: /// Usually there is more than one suitable scope to authorize an operation, some of which may /// encompass more rights than others. For example, for listing 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, A> + pub fn add_scope(mut self, scope: T) -> InstanceGroupManagerListCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Lists all of the instances in the managed instance group. Each instance in the list has a currentAction, which indicates the action that the managed instance group is performing on the instance. For example, if the group is still creating an instance, the currentAction is CREATING. If a previous action failed, the list displays the errors for that failed action. +/// +/// A builder for the *listManagedInstances* method supported by a *instanceGroupManager* resource. +/// It is not used directly, but through a `InstanceGroupManagerMethods` instance. +/// +/// # 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_group_managers().list_managed_instances("project", "zone", "instanceGroupManager") +/// .doit(); +/// # } +/// ``` +pub struct InstanceGroupManagerListManagedInstanceCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _zone: String, + _instance_group_manager: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for InstanceGroupManagerListManagedInstanceCall<'a, C, A> {} + +impl<'a, C, A> InstanceGroupManagerListManagedInstanceCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, InstanceGroupManagersListManagedInstancesResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.instanceGroupManagers.listManagedInstances", + 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(("instanceGroupManager", self._instance_group_manager.to_string())); + for &field in ["alt", "project", "zone", "instanceGroupManager"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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}/instanceGroupManagers/{instanceGroupManager}/listManagedInstances".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{zone}", "zone"), ("{instanceGroupManager}", "instanceGroupManager")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + 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 ["instanceGroupManager", "zone", "project"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The project ID for this request. + /// + /// 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) -> InstanceGroupManagerListManagedInstanceCall<'a, C, A> { + self._project = new_value.to_string(); + self + } + /// The name of the zone where the managed instance group is located. + /// + /// 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) -> InstanceGroupManagerListManagedInstanceCall<'a, C, A> { + self._zone = new_value.to_string(); + self + } + /// The name of the managed instance group. + /// + /// Sets the *instance group manager* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn instance_group_manager(mut self, new_value: &str) -> InstanceGroupManagerListManagedInstanceCall<'a, C, A> { + self._instance_group_manager = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> InstanceGroupManagerListManagedInstanceCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> InstanceGroupManagerListManagedInstanceCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> InstanceGroupManagerListManagedInstanceCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Creates a managed instance group using the information that you specify in the request. After the group is created, it schedules an action to create instances in the group using the specified instance template. This operation is marked as DONE when the group is created even if the instances in the group have not yet been created. You must separately verify the status of the individual instances with the listmanagedinstances method. +/// +/// A builder for the *insert* method supported by a *instanceGroupManager* resource. +/// It is not used directly, but through a `InstanceGroupManagerMethods` instance. +/// +/// # 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::InstanceGroupManager; +/// # #[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 = InstanceGroupManager::default(); +/// +/// // You can configure optional parameters by calling 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_group_managers().insert(req, "project", "zone") +/// .doit(); +/// # } +/// ``` +pub struct InstanceGroupManagerInsertCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Compute, + _request: InstanceGroupManager, + _project: String, + _zone: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for InstanceGroupManagerInsertCall<'a, C, A> {} + +impl<'a, C, A> InstanceGroupManagerInsertCall<'a, C, A> where 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.instanceGroupManagers.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 Err(Error::FieldClash(field)); + } + } + for (name, 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}/instanceGroupManagers".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().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 ["zone", "project"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: InstanceGroupManager) -> InstanceGroupManagerInsertCall<'a, C, A> { + self._request = new_value; + self + } + /// The project ID for this request. + /// + /// 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) -> InstanceGroupManagerInsertCall<'a, C, A> { + self._project = new_value.to_string(); + self + } + /// The name of the zone where you want to create the managed instance group. + /// + /// 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) -> InstanceGroupManagerInsertCall<'a, C, A> { + self._zone = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> InstanceGroupManagerInsertCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> InstanceGroupManagerInsertCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> InstanceGroupManagerInsertCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Retrieves the list of managed instance groups and groups them by zone. +/// +/// A builder for the *aggregatedList* method supported by a *instanceGroupManager* resource. +/// It is not used directly, but through a `InstanceGroupManagerMethods` instance. +/// +/// # 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_group_managers().aggregated_list("project") +/// .page_token("ipsum") +/// .max_results(39) +/// .filter("eos") +/// .doit(); +/// # } +/// ``` +pub struct InstanceGroupManagerAggregatedListCall<'a, C, A> + where C: '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, A> CallBuilder for InstanceGroupManagerAggregatedListCall<'a, C, A> {} + +impl<'a, C, A> InstanceGroupManagerAggregatedListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, InstanceGroupManagerAggregatedList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.instanceGroupManagers.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 Err(Error::FieldClash(field)); + } + } + for (name, 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/instanceGroupManagers".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The project ID for this request. + /// + /// 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) -> InstanceGroupManagerAggregatedListCall<'a, C, A> { + self._project = new_value.to_string(); + self + } + /// Specifies a page token to use. Use this parameter if you want to list the next page of results. Set pageToken to the nextPageToken returned by a previous list request. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> InstanceGroupManagerAggregatedListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Maximum count of results to be returned. + /// + /// Sets the *max results* query property to the given value. + pub fn max_results(mut self, new_value: u32) -> InstanceGroupManagerAggregatedListCall<'a, C, A> { + self._max_results = Some(new_value); + self + } + /// Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must be in the format: FIELD_NAME COMPARISON_STRING LITERAL_STRING. + /// + /// The FIELD_NAME is the name of the field you want to compare. Only atomic field types are supported (string, number, boolean). The COMPARISON_STRING must be either eq (equals) or ne (not equals). The LITERAL_STRING is the string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field. + /// + /// For example, filter=name ne example-instance. + /// + /// Sets the *filter* query property to the given value. + pub fn filter(mut self, new_value: &str) -> InstanceGroupManagerAggregatedListCall<'a, C, A> { + self._filter = Some(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> InstanceGroupManagerAggregatedListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> InstanceGroupManagerAggregatedListCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Readonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> InstanceGroupManagerAggregatedListCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Schedules a group action to delete the specified instances in the managed instance group. The instances are also removed from any target pools of which they were a member. This method reduces the targetSize of the managed instance group by the number of instances that you delete. This operation is marked as DONE when the action is scheduled even if the instances are still being deleted. You must separately verify the status of the deleting action with the listmanagedinstances method. +/// +/// A builder for the *deleteInstances* method supported by a *instanceGroupManager* resource. +/// It is not used directly, but through a `InstanceGroupManagerMethods` instance. +/// +/// # 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::InstanceGroupManagersDeleteInstancesRequest; +/// # #[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 = InstanceGroupManagersDeleteInstancesRequest::default(); +/// +/// // You can configure optional parameters by calling 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_group_managers().delete_instances(req, "project", "zone", "instanceGroupManager") +/// .doit(); +/// # } +/// ``` +pub struct InstanceGroupManagerDeleteInstanceCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Compute, + _request: InstanceGroupManagersDeleteInstancesRequest, + _project: String, + _zone: String, + _instance_group_manager: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for InstanceGroupManagerDeleteInstanceCall<'a, C, A> {} + +impl<'a, C, A> InstanceGroupManagerDeleteInstanceCall<'a, C, A> where 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.instanceGroupManagers.deleteInstances", + 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(("instanceGroupManager", self._instance_group_manager.to_string())); + for &field in ["alt", "project", "zone", "instanceGroupManager"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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}/instanceGroupManagers/{instanceGroupManager}/deleteInstances".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{zone}", "zone"), ("{instanceGroupManager}", "instanceGroupManager")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + 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 ["instanceGroupManager", "zone", "project"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: InstanceGroupManagersDeleteInstancesRequest) -> InstanceGroupManagerDeleteInstanceCall<'a, C, A> { + self._request = new_value; + self + } + /// The project ID for this request. + /// + /// 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) -> InstanceGroupManagerDeleteInstanceCall<'a, C, A> { + self._project = new_value.to_string(); + self + } + /// The name of the zone where the managed instance group is located. + /// + /// 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) -> InstanceGroupManagerDeleteInstanceCall<'a, C, A> { + self._zone = new_value.to_string(); + self + } + /// The name of the managed instance group. + /// + /// Sets the *instance group manager* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn instance_group_manager(mut self, new_value: &str) -> InstanceGroupManagerDeleteInstanceCall<'a, C, A> { + self._instance_group_manager = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> InstanceGroupManagerDeleteInstanceCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> InstanceGroupManagerDeleteInstanceCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> InstanceGroupManagerDeleteInstanceCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Specifies the instance template to use when creating new instances in this group. The templates for existing instances in the group do not change unless you recreate them. +/// +/// A builder for the *setInstanceTemplate* method supported by a *instanceGroupManager* resource. +/// It is not used directly, but through a `InstanceGroupManagerMethods` instance. +/// +/// # 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::InstanceGroupManagersSetInstanceTemplateRequest; +/// # #[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 = InstanceGroupManagersSetInstanceTemplateRequest::default(); +/// +/// // You can configure optional parameters by calling 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_group_managers().set_instance_template(req, "project", "zone", "instanceGroupManager") +/// .doit(); +/// # } +/// ``` +pub struct InstanceGroupManagerSetInstanceTemplateCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Compute, + _request: InstanceGroupManagersSetInstanceTemplateRequest, + _project: String, + _zone: String, + _instance_group_manager: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for InstanceGroupManagerSetInstanceTemplateCall<'a, C, A> {} + +impl<'a, C, A> InstanceGroupManagerSetInstanceTemplateCall<'a, C, A> where 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.instanceGroupManagers.setInstanceTemplate", + 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(("instanceGroupManager", self._instance_group_manager.to_string())); + for &field in ["alt", "project", "zone", "instanceGroupManager"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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}/instanceGroupManagers/{instanceGroupManager}/setInstanceTemplate".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{zone}", "zone"), ("{instanceGroupManager}", "instanceGroupManager")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + 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 ["instanceGroupManager", "zone", "project"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: InstanceGroupManagersSetInstanceTemplateRequest) -> InstanceGroupManagerSetInstanceTemplateCall<'a, C, A> { + self._request = new_value; + self + } + /// The project ID for this request. + /// + /// 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) -> InstanceGroupManagerSetInstanceTemplateCall<'a, C, A> { + self._project = new_value.to_string(); + self + } + /// The name of the zone where the managed instance group is located. + /// + /// 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) -> InstanceGroupManagerSetInstanceTemplateCall<'a, C, A> { + self._zone = new_value.to_string(); + self + } + /// The name of the managed instance group. + /// + /// Sets the *instance group manager* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn instance_group_manager(mut self, new_value: &str) -> InstanceGroupManagerSetInstanceTemplateCall<'a, C, A> { + self._instance_group_manager = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> InstanceGroupManagerSetInstanceTemplateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> InstanceGroupManagerSetInstanceTemplateCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> InstanceGroupManagerSetInstanceTemplateCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Modifies the target pools to which all instances in this managed instance group are assigned. The target pools automatically apply to all of the instances in the managed instance group. This operation is marked DONE when you make the request even if the instances have not yet been added to their target pools. The change might take some time to apply to all of the instances in the group depending on the size of the group. +/// +/// A builder for the *setTargetPools* method supported by a *instanceGroupManager* resource. +/// It is not used directly, but through a `InstanceGroupManagerMethods` instance. +/// +/// # 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::InstanceGroupManagersSetTargetPoolsRequest; +/// # #[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 = InstanceGroupManagersSetTargetPoolsRequest::default(); +/// +/// // You can configure optional parameters by calling 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_group_managers().set_target_pools(req, "project", "zone", "instanceGroupManager") +/// .doit(); +/// # } +/// ``` +pub struct InstanceGroupManagerSetTargetPoolCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Compute, + _request: InstanceGroupManagersSetTargetPoolsRequest, + _project: String, + _zone: String, + _instance_group_manager: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for InstanceGroupManagerSetTargetPoolCall<'a, C, A> {} + +impl<'a, C, A> InstanceGroupManagerSetTargetPoolCall<'a, C, A> where 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.instanceGroupManagers.setTargetPools", + 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(("instanceGroupManager", self._instance_group_manager.to_string())); + for &field in ["alt", "project", "zone", "instanceGroupManager"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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}/instanceGroupManagers/{instanceGroupManager}/setTargetPools".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{zone}", "zone"), ("{instanceGroupManager}", "instanceGroupManager")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + 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 ["instanceGroupManager", "zone", "project"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: InstanceGroupManagersSetTargetPoolsRequest) -> InstanceGroupManagerSetTargetPoolCall<'a, C, A> { + self._request = new_value; + self + } + /// The project ID for this request. + /// + /// 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) -> InstanceGroupManagerSetTargetPoolCall<'a, C, A> { + self._project = new_value.to_string(); + self + } + /// The name of the zone where the managed instance group is located. + /// + /// 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) -> InstanceGroupManagerSetTargetPoolCall<'a, C, A> { + self._zone = new_value.to_string(); + self + } + /// The name of the managed instance group. + /// + /// Sets the *instance group manager* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn instance_group_manager(mut self, new_value: &str) -> InstanceGroupManagerSetTargetPoolCall<'a, C, A> { + self._instance_group_manager = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> InstanceGroupManagerSetTargetPoolCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> InstanceGroupManagerSetTargetPoolCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> InstanceGroupManagerSetTargetPoolCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Deletes the specified managed instance group and all of the instances in that group. +/// +/// A builder for the *delete* method supported by a *instanceGroupManager* resource. +/// It is not used directly, but through a `InstanceGroupManagerMethods` instance. +/// +/// # 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_group_managers().delete("project", "zone", "instanceGroupManager") +/// .doit(); +/// # } +/// ``` +pub struct InstanceGroupManagerDeleteCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _zone: String, + _instance_group_manager: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for InstanceGroupManagerDeleteCall<'a, C, A> {} + +impl<'a, C, A> InstanceGroupManagerDeleteCall<'a, C, A> where 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.instanceGroupManagers.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(("instanceGroupManager", self._instance_group_manager.to_string())); + for &field in ["alt", "project", "zone", "instanceGroupManager"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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}/instanceGroupManagers/{instanceGroupManager}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{zone}", "zone"), ("{instanceGroupManager}", "instanceGroupManager")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + 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 ["instanceGroupManager", "zone", "project"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The project ID for this request. + /// + /// 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) -> InstanceGroupManagerDeleteCall<'a, C, A> { + self._project = new_value.to_string(); + self + } + /// The name of the zone where the managed instance group is located. + /// + /// 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) -> InstanceGroupManagerDeleteCall<'a, C, A> { + self._zone = new_value.to_string(); + self + } + /// The name of the managed instance group to delete. + /// + /// Sets the *instance group manager* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn instance_group_manager(mut self, new_value: &str) -> InstanceGroupManagerDeleteCall<'a, C, A> { + self._instance_group_manager = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> InstanceGroupManagerDeleteCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> InstanceGroupManagerDeleteCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> InstanceGroupManagerDeleteCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Returns all of the details about the specified managed instance group. +/// +/// A builder for the *get* method supported by a *instanceGroupManager* resource. +/// It is not used directly, but through a `InstanceGroupManagerMethods` instance. +/// +/// # 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_group_managers().get("project", "zone", "instanceGroupManager") +/// .doit(); +/// # } +/// ``` +pub struct InstanceGroupManagerGetCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _zone: String, + _instance_group_manager: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for InstanceGroupManagerGetCall<'a, C, A> {} + +impl<'a, C, A> InstanceGroupManagerGetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, InstanceGroupManager)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.instanceGroupManagers.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(("instanceGroupManager", self._instance_group_manager.to_string())); + for &field in ["alt", "project", "zone", "instanceGroupManager"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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}/instanceGroupManagers/{instanceGroupManager}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{zone}", "zone"), ("{instanceGroupManager}", "instanceGroupManager")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + 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 ["instanceGroupManager", "zone", "project"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The project ID for this request. + /// + /// 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) -> InstanceGroupManagerGetCall<'a, C, A> { + self._project = new_value.to_string(); + self + } + /// The name of the zone where the managed instance group is located. + /// + /// 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) -> InstanceGroupManagerGetCall<'a, C, A> { + self._zone = new_value.to_string(); + self + } + /// The name of the managed instance group. + /// + /// Sets the *instance group manager* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn instance_group_manager(mut self, new_value: &str) -> InstanceGroupManagerGetCall<'a, C, A> { + self._instance_group_manager = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> InstanceGroupManagerGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> InstanceGroupManagerGetCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Readonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> InstanceGroupManagerGetCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Schedules a group action to remove the specified instances from the managed instance group. Abandoning an instance does not delete the instance, but it does remove the instance from any target pools that are applied by the managed instance group. This method reduces the targetSize of the managed instance group by the number of instances that you abandon. This operation is marked as DONE when the action is scheduled even if the instances have not yet been removed from the group. You must separately verify the status of the abandoning action with the listmanagedinstances method. +/// +/// A builder for the *abandonInstances* method supported by a *instanceGroupManager* resource. +/// It is not used directly, but through a `InstanceGroupManagerMethods` instance. +/// +/// # 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::InstanceGroupManagersAbandonInstancesRequest; +/// # #[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 = InstanceGroupManagersAbandonInstancesRequest::default(); +/// +/// // You can configure optional parameters by calling 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_group_managers().abandon_instances(req, "project", "zone", "instanceGroupManager") +/// .doit(); +/// # } +/// ``` +pub struct InstanceGroupManagerAbandonInstanceCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Compute, + _request: InstanceGroupManagersAbandonInstancesRequest, + _project: String, + _zone: String, + _instance_group_manager: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for InstanceGroupManagerAbandonInstanceCall<'a, C, A> {} + +impl<'a, C, A> InstanceGroupManagerAbandonInstanceCall<'a, C, A> where 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.instanceGroupManagers.abandonInstances", + 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(("instanceGroupManager", self._instance_group_manager.to_string())); + for &field in ["alt", "project", "zone", "instanceGroupManager"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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}/instanceGroupManagers/{instanceGroupManager}/abandonInstances".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{zone}", "zone"), ("{instanceGroupManager}", "instanceGroupManager")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + 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 ["instanceGroupManager", "zone", "project"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: InstanceGroupManagersAbandonInstancesRequest) -> InstanceGroupManagerAbandonInstanceCall<'a, C, A> { + self._request = new_value; + self + } + /// The project ID for this request. + /// + /// 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) -> InstanceGroupManagerAbandonInstanceCall<'a, C, A> { + self._project = new_value.to_string(); + self + } + /// The name of the zone where the managed instance group is located. + /// + /// 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) -> InstanceGroupManagerAbandonInstanceCall<'a, C, A> { + self._zone = new_value.to_string(); + self + } + /// The name of the managed instance group. + /// + /// Sets the *instance group manager* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn instance_group_manager(mut self, new_value: &str) -> InstanceGroupManagerAbandonInstanceCall<'a, C, A> { + self._instance_group_manager = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> InstanceGroupManagerAbandonInstanceCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> InstanceGroupManagerAbandonInstanceCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> InstanceGroupManagerAbandonInstanceCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Schedules a group action to recreate the specified instances in the managed instance group. The instances are deleted and recreated using the current instance template for the managed instance group. This operation is marked as DONE when the action is scheduled even if the instances have not yet been recreated. You must separately verify the status of the recreating action with the listmanagedinstances method. +/// +/// A builder for the *recreateInstances* method supported by a *instanceGroupManager* resource. +/// It is not used directly, but through a `InstanceGroupManagerMethods` instance. +/// +/// # 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::InstanceGroupManagersRecreateInstancesRequest; +/// # #[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 = InstanceGroupManagersRecreateInstancesRequest::default(); +/// +/// // You can configure optional parameters by calling 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_group_managers().recreate_instances(req, "project", "zone", "instanceGroupManager") +/// .doit(); +/// # } +/// ``` +pub struct InstanceGroupManagerRecreateInstanceCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Compute, + _request: InstanceGroupManagersRecreateInstancesRequest, + _project: String, + _zone: String, + _instance_group_manager: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for InstanceGroupManagerRecreateInstanceCall<'a, C, A> {} + +impl<'a, C, A> InstanceGroupManagerRecreateInstanceCall<'a, C, A> where 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.instanceGroupManagers.recreateInstances", + 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(("instanceGroupManager", self._instance_group_manager.to_string())); + for &field in ["alt", "project", "zone", "instanceGroupManager"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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}/instanceGroupManagers/{instanceGroupManager}/recreateInstances".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{zone}", "zone"), ("{instanceGroupManager}", "instanceGroupManager")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + 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 ["instanceGroupManager", "zone", "project"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: InstanceGroupManagersRecreateInstancesRequest) -> InstanceGroupManagerRecreateInstanceCall<'a, C, A> { + self._request = new_value; + self + } + /// The project ID for this request. + /// + /// 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) -> InstanceGroupManagerRecreateInstanceCall<'a, C, A> { + self._project = new_value.to_string(); + self + } + /// The name of the zone where the managed instance group is located. + /// + /// 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) -> InstanceGroupManagerRecreateInstanceCall<'a, C, A> { + self._zone = new_value.to_string(); + self + } + /// The name of the managed instance group. + /// + /// Sets the *instance group manager* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn instance_group_manager(mut self, new_value: &str) -> InstanceGroupManagerRecreateInstanceCall<'a, C, A> { + self._instance_group_manager = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> InstanceGroupManagerRecreateInstanceCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> InstanceGroupManagerRecreateInstanceCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> InstanceGroupManagerRecreateInstanceCall<'a, C, A> where T: AsRef { self._scopes.insert(scope.as_ref().to_string(), ()); self @@ -48328,8 +52109,8 @@ impl<'a, C, A> HttpHealthCheckPatchCall<'a, C, A> where C: BorrowMut HttpHealthCheckListCall<'a, C, A> where C: BorrowMut HttpHealthCheckListCall<'a, C, A> { @@ -49896,9 +53674,9 @@ impl<'a, C, A> InstanceTemplateGetCall<'a, C, A> where C: BorrowMut InstanceTemplateListCall<'a, C, A> where C: BorrowMut InstanceTemplateListCall<'a, C, A> { @@ -50690,9 +54465,9 @@ impl<'a, C, A> TargetHttpProxyDeleteCall<'a, C, A> where C: BorrowMut TargetHttpProxyListCall<'a, C, A> where C: BorrowMut TargetHttpProxyListCall<'a, C, A> { @@ -51736,6 +55508,1045 @@ impl<'a, C, A> TargetHttpProxyInsertCall<'a, C, A> where C: BorrowMut::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.ssl_certificates().delete("project", "sslCertificate") +/// .doit(); +/// # } +/// ``` +pub struct SslCertificateDeleteCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _ssl_certificate: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for SslCertificateDeleteCall<'a, C, A> {} + +impl<'a, C, A> SslCertificateDeleteCall<'a, C, A> where 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.sslCertificates.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(("sslCertificate", self._ssl_certificate.to_string())); + for &field in ["alt", "project", "sslCertificate"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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/sslCertificates/{sslCertificate}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{sslCertificate}", "sslCertificate")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["sslCertificate", "project"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Name of the project scoping this request. + /// + /// 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) -> SslCertificateDeleteCall<'a, C, A> { + self._project = new_value.to_string(); + self + } + /// Name of the SslCertificate resource to delete. + /// + /// Sets the *ssl certificate* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn ssl_certificate(mut self, new_value: &str) -> SslCertificateDeleteCall<'a, C, A> { + self._ssl_certificate = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> SslCertificateDeleteCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> SslCertificateDeleteCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> SslCertificateDeleteCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Retrieves the list of SslCertificate resources available to the specified project. +/// +/// A builder for the *list* method supported by a *sslCertificate* resource. +/// It is not used directly, but through a `SslCertificateMethods` instance. +/// +/// # 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.ssl_certificates().list("project") +/// .page_token("ea") +/// .max_results(78) +/// .filter("sanctus") +/// .doit(); +/// # } +/// ``` +pub struct SslCertificateListCall<'a, C, A> + where C: '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, A> CallBuilder for SslCertificateListCall<'a, C, A> {} + +impl<'a, C, A> SslCertificateListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, SslCertificateList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.sslCertificates.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 Err(Error::FieldClash(field)); + } + } + for (name, 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/sslCertificates".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Name of the project scoping this request. + /// + /// 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) -> SslCertificateListCall<'a, C, A> { + self._project = new_value.to_string(); + self + } + /// Specifies a page token to use. Use this parameter if you want to list the next page of results. Set pageToken to the nextPageToken returned by a previous list request. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> SslCertificateListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Maximum count of results to be returned. + /// + /// Sets the *max results* query property to the given value. + pub fn max_results(mut self, new_value: u32) -> SslCertificateListCall<'a, C, A> { + self._max_results = Some(new_value); + self + } + /// Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must be in the format: FIELD_NAME COMPARISON_STRING LITERAL_STRING. + /// + /// The FIELD_NAME is the name of the field you want to compare. Only atomic field types are supported (string, number, boolean). The COMPARISON_STRING must be either eq (equals) or ne (not equals). The LITERAL_STRING is the string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field. + /// + /// For example, filter=name ne example-instance. + /// + /// Sets the *filter* query property to the given value. + pub fn filter(mut self, new_value: &str) -> SslCertificateListCall<'a, C, A> { + self._filter = Some(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> SslCertificateListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> SslCertificateListCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Readonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> SslCertificateListCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Creates a SslCertificate resource in the specified project using the data included in the request. +/// +/// A builder for the *insert* method supported by a *sslCertificate* resource. +/// It is not used directly, but through a `SslCertificateMethods` instance. +/// +/// # 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::SslCertificate; +/// # #[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 = SslCertificate::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.ssl_certificates().insert(req, "project") +/// .doit(); +/// # } +/// ``` +pub struct SslCertificateInsertCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Compute, + _request: SslCertificate, + _project: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for SslCertificateInsertCall<'a, C, A> {} + +impl<'a, C, A> SslCertificateInsertCall<'a, C, A> where 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.sslCertificates.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 Err(Error::FieldClash(field)); + } + } + for (name, 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/sslCertificates".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: SslCertificate) -> SslCertificateInsertCall<'a, C, A> { + self._request = new_value; + self + } + /// Name of the project scoping this request. + /// + /// 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) -> SslCertificateInsertCall<'a, C, A> { + self._project = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> SslCertificateInsertCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> SslCertificateInsertCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> SslCertificateInsertCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Returns the specified SslCertificate resource. +/// +/// A builder for the *get* method supported by a *sslCertificate* resource. +/// It is not used directly, but through a `SslCertificateMethods` instance. +/// +/// # 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.ssl_certificates().get("project", "sslCertificate") +/// .doit(); +/// # } +/// ``` +pub struct SslCertificateGetCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _ssl_certificate: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for SslCertificateGetCall<'a, C, A> {} + +impl<'a, C, A> SslCertificateGetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, SslCertificate)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.sslCertificates.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(("sslCertificate", self._ssl_certificate.to_string())); + for &field in ["alt", "project", "sslCertificate"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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/sslCertificates/{sslCertificate}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{sslCertificate}", "sslCertificate")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["sslCertificate", "project"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Name of the project scoping this request. + /// + /// 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) -> SslCertificateGetCall<'a, C, A> { + self._project = new_value.to_string(); + self + } + /// Name of the SslCertificate resource to return. + /// + /// Sets the *ssl certificate* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn ssl_certificate(mut self, new_value: &str) -> SslCertificateGetCall<'a, C, A> { + self._ssl_certificate = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> SslCertificateGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> SslCertificateGetCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Readonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> SslCertificateGetCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + /// Deletes the specified zone-specific Operations resource. /// /// A builder for the *delete* method supported by a *zoneOperation* resource. @@ -52012,9 +56823,9 @@ impl<'a, C, A> ZoneOperationDeleteCall<'a, C, A> where C: BorrowMut ZoneOperationListCall<'a, C, A> where C: BorrowMut self._max_results = Some(new_value); self } - /// Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must contain the following: - /// FIELD_NAME COMPARISON_STRING LITERAL_STRING - /// - /// - FIELD_NAME: The name of the field you want to compare. The field name must be valid for the type of resource being filtered. Only atomic field types are supported (string, number, boolean). Array and object fields are not currently supported. - /// - COMPARISON_STRING: The comparison string, either eq (equals) or ne (not equals). - /// - LITERAL_STRING: The literal string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field. For example, you can filter by the name of a resource: - /// filter=name ne example-instance - /// The above filter returns only results whose name field does not equal example-instance. You can also enclose your literal string in single, double, or no quotes. + /// Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must be in the format: FIELD_NAME COMPARISON_STRING LITERAL_STRING. + /// + /// The FIELD_NAME is the name of the field you want to compare. Only atomic field types are supported (string, number, boolean). The COMPARISON_STRING must be either eq (equals) or ne (not equals). The LITERAL_STRING is the string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field. + /// + /// For example, filter=name ne example-instance. /// /// Sets the *filter* query property to the given value. pub fn filter(mut self, new_value: &str) -> ZoneOperationListCall<'a, C, A> { @@ -53078,8 +57886,8 @@ impl<'a, C, A> RouteInsertCall<'a, C, A> where C: BorrowMut, A: o /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.routes().list("project") -/// .page_token("elitr") -/// .max_results(89) +/// .page_token("clita") +/// .max_results(95) /// .filter("sit") /// .doit(); /// # } @@ -53264,14 +58072,11 @@ impl<'a, C, A> RouteListCall<'a, C, A> where C: BorrowMut, A: oau self._max_results = Some(new_value); self } - /// Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must contain the following: - /// FIELD_NAME COMPARISON_STRING LITERAL_STRING - /// - /// - FIELD_NAME: The name of the field you want to compare. The field name must be valid for the type of resource being filtered. Only atomic field types are supported (string, number, boolean). Array and object fields are not currently supported. - /// - COMPARISON_STRING: The comparison string, either eq (equals) or ne (not equals). - /// - LITERAL_STRING: The literal string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field. For example, you can filter by the name of a resource: - /// filter=name ne example-instance - /// The above filter returns only results whose name field does not equal example-instance. You can also enclose your literal string in single, double, or no quotes. + /// Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must be in the format: FIELD_NAME COMPARISON_STRING LITERAL_STRING. + /// + /// The FIELD_NAME is the name of the field you want to compare. Only atomic field types are supported (string, number, boolean). The COMPARISON_STRING must be either eq (equals) or ne (not equals). The LITERAL_STRING is the string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field. + /// + /// For example, filter=name ne example-instance. /// /// Sets the *filter* query property to the given value. pub fn filter(mut self, new_value: &str) -> RouteListCall<'a, C, A> { @@ -54678,9 +59483,9 @@ impl<'a, C, A> FirewallInsertCall<'a, C, A> where C: BorrowMut, A /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.firewalls().list("project") -/// .page_token("ea") -/// .max_results(85) -/// .filter("et") +/// .page_token("et") +/// .max_results(13) +/// .filter("amet.") /// .doit(); /// # } /// ``` @@ -54864,14 +59669,11 @@ impl<'a, C, A> FirewallListCall<'a, C, A> where C: BorrowMut, A: self._max_results = Some(new_value); self } - /// Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must contain the following: - /// FIELD_NAME COMPARISON_STRING LITERAL_STRING - /// - /// - FIELD_NAME: The name of the field you want to compare. The field name must be valid for the type of resource being filtered. Only atomic field types are supported (string, number, boolean). Array and object fields are not currently supported. - /// - COMPARISON_STRING: The comparison string, either eq (equals) or ne (not equals). - /// - LITERAL_STRING: The literal string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field. For example, you can filter by the name of a resource: - /// filter=name ne example-instance - /// The above filter returns only results whose name field does not equal example-instance. You can also enclose your literal string in single, double, or no quotes. + /// Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must be in the format: FIELD_NAME COMPARISON_STRING LITERAL_STRING. + /// + /// The FIELD_NAME is the name of the field you want to compare. Only atomic field types are supported (string, number, boolean). The COMPARISON_STRING must be either eq (equals) or ne (not equals). The LITERAL_STRING is the string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field. + /// + /// For example, filter=name ne example-instance. /// /// Sets the *filter* query property to the given value. pub fn filter(mut self, new_value: &str) -> FirewallListCall<'a, C, A> { @@ -55178,266 +59980,6 @@ impl<'a, C, A> FirewallDeleteCall<'a, C, A> where C: BorrowMut, A } -/// Deletes the specified VpnTunnel resource. -/// -/// A builder for the *delete* method supported by a *vpnTunnel* resource. -/// It is not used directly, but through a `VpnTunnelMethods` instance. -/// -/// # 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.vpn_tunnels().delete("project", "region", "vpnTunnel") -/// .doit(); -/// # } -/// ``` -pub struct VpnTunnelDeleteCall<'a, C, A> - where C: 'a, A: 'a { - - hub: &'a Compute, - _project: String, - _region: String, - _vpn_tunnel: String, - _delegate: Option<&'a mut Delegate>, - _additional_params: HashMap, - _scopes: BTreeMap -} - -impl<'a, C, A> CallBuilder for VpnTunnelDeleteCall<'a, C, A> {} - -impl<'a, C, A> VpnTunnelDeleteCall<'a, C, A> where 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.vpnTunnels.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(("vpnTunnel", self._vpn_tunnel.to_string())); - for &field in ["alt", "project", "region", "vpnTunnel"].iter() { - if self._additional_params.contains_key(field) { - dlg.finished(false); - return Err(Error::FieldClash(field)); - } - } - for (name, 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}/vpnTunnels/{vpnTunnel}".to_string(); - if self._scopes.len() == 0 { - self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); - } - - for &(find_this, param_name) in [("{project}", "project"), ("{region}", "region"), ("{vpnTunnel}", "vpnTunnel")].iter() { - let mut replace_with: Option<&str> = None; - for &(name, ref value) in params.iter() { - if name == param_name { - replace_with = Some(value); - 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 ["vpnTunnel", "region", "project"].iter() { - if let Some(index) = params.iter().position(|t| &t.0 == param_name) { - indices_for_removal.push(index); - } - } - for &index in indices_for_removal.iter() { - params.remove(index); - } - } - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_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) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = { - let mut json_response = String::new(); - res.read_to_string(&mut json_response).unwrap(); - match json::from_str(&json_response) { - Ok(decoded) => (res, decoded), - Err(err) => { - dlg.response_json_decode_error(&json_response, &err); - return Err(Error::JsonDecodeError(json_response, err)); - } - } - }; - - dlg.finished(true); - return Ok(result_value) - } - } - } - } - - - /// Project ID for this request. - /// - /// 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) -> VpnTunnelDeleteCall<'a, C, A> { - self._project = new_value.to_string(); - self - } - /// The name of the region for this request. - /// - /// 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. - pub fn region(mut self, new_value: &str) -> VpnTunnelDeleteCall<'a, C, A> { - self._region = new_value.to_string(); - self - } - /// Name of the VpnTunnel resource to delete. - /// - /// Sets the *vpn tunnel* path property to the given value. - /// - /// Even though the property as already been set when instantiating this call, - /// we provide this method for API completeness. - pub fn vpn_tunnel(mut self, new_value: &str) -> VpnTunnelDeleteCall<'a, C, A> { - self._vpn_tunnel = new_value.to_string(); - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> VpnTunnelDeleteCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. - /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. - /// * *alt* (query-string) - Data format for the response. - pub fn param(mut self, name: T, value: T) -> VpnTunnelDeleteCall<'a, C, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::CloudPlatform`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be - /// sufficient, a read-write scope will do as well. - pub fn add_scope(mut self, scope: T) -> VpnTunnelDeleteCall<'a, C, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().to_string(), ()); - self - } -} - - /// Creates a VpnTunnel resource in the specified project and region using the data included in the request. /// /// A builder for the *insert* method supported by a *vpnTunnel* resource. @@ -55717,6 +60259,266 @@ impl<'a, C, A> VpnTunnelInsertCall<'a, C, A> where C: BorrowMut, } +/// Deletes the specified VpnTunnel resource. +/// +/// A builder for the *delete* method supported by a *vpnTunnel* resource. +/// It is not used directly, but through a `VpnTunnelMethods` instance. +/// +/// # 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.vpn_tunnels().delete("project", "region", "vpnTunnel") +/// .doit(); +/// # } +/// ``` +pub struct VpnTunnelDeleteCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Compute, + _project: String, + _region: String, + _vpn_tunnel: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for VpnTunnelDeleteCall<'a, C, A> {} + +impl<'a, C, A> VpnTunnelDeleteCall<'a, C, A> where 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.vpnTunnels.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(("vpnTunnel", self._vpn_tunnel.to_string())); + for &field in ["alt", "project", "region", "vpnTunnel"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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}/vpnTunnels/{vpnTunnel}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{region}", "region"), ("{vpnTunnel}", "vpnTunnel")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + 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 ["vpnTunnel", "region", "project"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Project ID for this request. + /// + /// 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) -> VpnTunnelDeleteCall<'a, C, A> { + self._project = new_value.to_string(); + self + } + /// The name of the region for this request. + /// + /// 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. + pub fn region(mut self, new_value: &str) -> VpnTunnelDeleteCall<'a, C, A> { + self._region = new_value.to_string(); + self + } + /// Name of the VpnTunnel resource to delete. + /// + /// Sets the *vpn tunnel* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn vpn_tunnel(mut self, new_value: &str) -> VpnTunnelDeleteCall<'a, C, A> { + self._vpn_tunnel = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> VpnTunnelDeleteCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> VpnTunnelDeleteCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> VpnTunnelDeleteCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + /// Returns the specified VpnTunnel resource. /// /// A builder for the *get* method supported by a *vpnTunnel* resource. @@ -56004,9 +60806,9 @@ impl<'a, C, A> VpnTunnelGetCall<'a, C, A> where C: BorrowMut, A: /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.vpn_tunnels().list("project", "region") -/// .page_token("no") -/// .max_results(19) -/// .filter("accusam") +/// .page_token("accusam") +/// .max_results(27) +/// .filter("clita") /// .doit(); /// # } /// ``` @@ -56202,14 +61004,11 @@ impl<'a, C, A> VpnTunnelListCall<'a, C, A> where C: BorrowMut, A: self._max_results = Some(new_value); self } - /// Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must contain the following: - /// FIELD_NAME COMPARISON_STRING LITERAL_STRING - /// - /// - FIELD_NAME: The name of the field you want to compare. The field name must be valid for the type of resource being filtered. Only atomic field types are supported (string, number, boolean). Array and object fields are not currently supported. - /// - COMPARISON_STRING: The comparison string, either eq (equals) or ne (not equals). - /// - LITERAL_STRING: The literal string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field. For example, you can filter by the name of a resource: - /// filter=name ne example-instance - /// The above filter returns only results whose name field does not equal example-instance. You can also enclose your literal string in single, double, or no quotes. + /// Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must be in the format: FIELD_NAME COMPARISON_STRING LITERAL_STRING. + /// + /// The FIELD_NAME is the name of the field you want to compare. Only atomic field types are supported (string, number, boolean). The COMPARISON_STRING must be either eq (equals) or ne (not equals). The LITERAL_STRING is the string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field. + /// + /// For example, filter=name ne example-instance. /// /// Sets the *filter* query property to the given value. pub fn filter(mut self, new_value: &str) -> VpnTunnelListCall<'a, C, A> { @@ -56295,9 +61094,9 @@ impl<'a, C, A> VpnTunnelListCall<'a, C, A> where C: BorrowMut, A: /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.vpn_tunnels().aggregated_list("project") -/// .page_token("sea") -/// .max_results(100) -/// .filter("clita") +/// .page_token("ut") +/// .max_results(89) +/// .filter("diam") /// .doit(); /// # } /// ``` @@ -56481,14 +61280,11 @@ impl<'a, C, A> VpnTunnelAggregatedListCall<'a, C, A> where C: BorrowMut VpnTunnelAggregatedListCall<'a, C, A> { @@ -56574,9 +61370,9 @@ impl<'a, C, A> VpnTunnelAggregatedListCall<'a, C, A> where C: BorrowMut RegionOperationListCall<'a, C, A> where C: BorrowMut RegionOperationListCall<'a, C, A> { diff --git a/gen/container1-cli/Cargo.toml b/gen/container1-cli/Cargo.toml new file mode 100644 index 0000000000..9b1418131b --- /dev/null +++ b/gen/container1-cli/Cargo.toml @@ -0,0 +1,35 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-container1-cli" +version = "0.3.2+20150603" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with container (protocol v1)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/container1-cli" +homepage = "https://cloud.google.com/container-engine/" +documentation = "http://byron.github.io/google-apis-rs/google_container1_cli" +license = "MIT" +keywords = ["container", "google", "cli"] + +[[bin]] +name = "container1" + +[dependencies] +hyper = ">= 0.6.8" +mime = "0.1.0" +serde = ">= 0.6.0" +serde_json = ">= 0.6.0" +yup-oauth2 = "*" +strsim = "*" +yup-hyper-mock = ">=1.0.0" +clap = ">= 1.0.3" + +[build-dependencies] +syntex = { version = "*" } +serde_codegen = { version = "*" } + + +[dependencies.google-container1] +path = "../container1" diff --git a/gen/container1-cli/LICENSE.md b/gen/container1-cli/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/container1-cli/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-cli/README.md b/gen/container1-cli/README.md new file mode 100644 index 0000000000..49681427aa --- /dev/null +++ b/gen/container1-cli/README.md @@ -0,0 +1,120 @@ + +The `container1` command-line interface *(CLI)* allows to use most features of the *Google container* service from the comfort of your terminal. + +By default all output is printed to standard out, but flags can be set to direct it into a file independent of your shell's +capabilities. Errors will be printed to standard error, and cause the program's exit code to be non-zero. + +If data-structures are requested, these will be returned as pretty-printed JSON, to be useful as input to other tools. + +Everything else about the *container* API can be found at the +[official documentation site](https://cloud.google.com/container-engine/). + +# Downloads + +You can download the pre-compiled 64bit binaries for the following platforms: + +* ![icon](http://megaicons.net/static/img/icons_sizes/6/140/16/ubuntu-icon.png) [ubuntu](http://dl.byronimo.de/google.rs/cli/0.3.2/ubuntu/container1.tar.gz) +* ![icon](http://hydra-media.cursecdn.com/wow.gamepedia.com/a/a2/Apple-icon-16x16.png?version=25ddd67ac3dd3b634478e3978b76cb74) [osx](http://dl.byronimo.de/google.rs/cli/0.3.2/osx/container1.tar.gz) + +Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/container1-cli). + +# Usage + +This documentation was generated from the *container* API at revision *20150603*. The CLI is at version *0.3.2*. + +```bash +container1 [options] + projects + zones-clusters-create (-r )... [-p ]... [-o ] + zones-clusters-delete [-p ]... [-o ] + zones-clusters-get [-p ]... [-o ] + zones-clusters-list [-p ]... [-o ] + zones-clusters-update (-r )... [-p ]... [-o ] + zones-get-serverconfig [-p ]... [-o ] + zones-operations-get [-p ]... [-o ] + zones-operations-list [-p ]... [-o ] + container1 --help + +Configuration: + [--scope ]... + Specify the authentication a method should be executed in. Each scope + requires the user to grant this application permission to use it. + If unset, it defaults to the shortest scope url for a particular method. + --config-dir + A directory into which we will store our persistent data. Defaults to + a user-writable directory that we will create during the first invocation. + [default: ~/.google-service-cli] + --debug + Output all server communication to standard error. `tx` and `rx` are placed + into the same stream. + --debug-auth + Output all communication related to authentication to standard error. `tx` + and `rx` are placed into the same stream. + +``` + +# Configuration + +The program will store all persistent data in the `~/.google-service-cli` directory in *JSON* files prefixed with `container1-`. You can change the directory used to store configuration with the `--config-dir` flag on a per-invocation basis. + +More information about the various kinds of persistent data are given in the following paragraphs. + +# Authentication + +Most APIs require a user to authenticate any request. If this is the case, the [scope][scopes] determines the +set of permissions granted. The granularity of these is usually no more than *read-only* or *full-access*. + +If not set, the system will automatically select the smallest feasible scope, e.g. when invoking a +method that is read-only, it will ask only for a read-only scope. +You may use the `--scope` flag to specify a scope directly. +All applicable scopes are documented in the respective method's CLI documentation. + +The first time a scope is used, the user is asked for permission. Follow the instructions given +by the CLI to grant permissions, or to decline. + +If a scope was authenticated by the user, the respective information will be stored as *JSON* in the configuration +directory, e.g. `~/.google-service-cli/container1-token-.json`. No manual management of these tokens +is necessary. + +To revoke granted authentication, please refer to the [official documentation][revoke-access]. + +# Application Secrets + +In order to allow any application to use Google services, it will need to be registered using the +[Google Developer Console][google-dev-console]. APIs the application may use are then enabled for it +one by one. Most APIs can be used for free and have a daily quota. + +To allow more comfortable usage of the CLI without forcing anyone to register an own application, the CLI +comes with a default application secret that is configured accordingly. This also means that heavy usage +all around the world may deplete the daily quota. + +You can workaround this limitation by putting your own secrets file at this location: +`~/.google-service-cli/container1-secret.json`, assuming that the required *container* API +was enabled for it. Such a secret file can be downloaded in the *Google Developer Console* at +*APIs & auth -> Credentials -> Download JSON* and used as is. + +Learn more about how to setup Google projects and enable APIs using the [official documentation][google-project-new]. + + +# Debugging + +Even though the CLI does its best to provide usable error messages, sometimes it might be desirable to know +what exactly led to a particular issue. This is done by allowing all client-server communication to be +output to standard error *as-is*. + +The `--debug` flag will print all client-server communication to standard error, whereas the `--debug-auth` flag +will cause all communication related to authentication to standard error. +If the `--debug` flag is set, error-results will be debug-printed, possibly yielding more information about the +issue at hand. + +You may consider redirecting standard error into a file for ease of use, e.g. `container1 --debug [options] 2>debug.txt`. + + +[scopes]: https://developers.google.com/+/api/oauth#scopes +[revoke-access]: http://webapps.stackexchange.com/a/30849 +[google-dev-console]: https://console.developers.google.com/ +[google-project-new]: https://developers.google.com/console/help/new/ \ No newline at end of file diff --git a/gen/container1-cli/mkdocs.yml b/gen/container1-cli/mkdocs.yml new file mode 100644 index 0000000000..3d959737c4 --- /dev/null +++ b/gen/container1-cli/mkdocs.yml @@ -0,0 +1,24 @@ +site_name: container v0.3.2+20150603 +site_url: http://byron.github.io/google-apis-rs/google-container1-cli +site_description: Write integrating applications with bcore + +repo_url: https://github.com/Byron/google-apis-rs/tree/master/gen/container1-cli + +docs_dir: docs +site_dir: build_html + +pages: +- ['index.md', 'Home'] +- ['projects_zones-clusters-create.md', 'Projects', 'Zones Clusters Create'] +- ['projects_zones-clusters-delete.md', 'Projects', 'Zones Clusters Delete'] +- ['projects_zones-clusters-get.md', 'Projects', 'Zones Clusters Get'] +- ['projects_zones-clusters-list.md', 'Projects', 'Zones Clusters List'] +- ['projects_zones-clusters-update.md', 'Projects', 'Zones Clusters Update'] +- ['projects_zones-get-serverconfig.md', 'Projects', 'Zones Get Serverconfig'] +- ['projects_zones-operations-get.md', 'Projects', 'Zones Operations Get'] +- ['projects_zones-operations-list.md', 'Projects', 'Zones Operations List'] + +theme: readthedocs + +copyright: Copyright © 2015, `Sebastian Thiel` + diff --git a/gen/container1-cli/src/cmn.rs b/gen/container1-cli/src/cmn.rs new file mode 100644 index 0000000000..8358f156fa --- /dev/null +++ b/gen/container1-cli/src/cmn.rs @@ -0,0 +1,721 @@ +// COPY OF 'src/rust/cli/cmn.rs' +// DO NOT EDIT +use oauth2::{ApplicationSecret, ConsoleApplicationSecret, TokenStorage, Token}; +use serde_json as json; +use serde_json::value::Value; +use mime::Mime; +use clap::{App, SubCommand}; +use strsim; + +use std::fs; +use std::env; +use std::io; +use std::fmt; +use std::path::{Path, PathBuf}; +use std::str::FromStr; +use std::string::ToString; +use std::io::{Write, Read, stdout}; + +use std::default::Default; + +const FIELD_SEP: char = '.'; + + +pub enum ComplexType { + Pod, + Vec, + Map, +} + + // Null, + // Bool(bool), + // I64(i64), + // U64(u64), + // F64(f64), + // String(String), + +pub enum JsonType { + Boolean, + Int, + Uint, + Float, + String, +} + +pub struct JsonTypeInfo { + pub jtype: JsonType, + pub ctype: ComplexType, +} + +// Based on @erickt user comment. Thanks for the idea ! +// Remove all keys whose values are null from given value (changed in place) +pub fn remove_json_null_values(value: &mut Value) { + match *value { + Value::Object(ref mut map) => { + let mut for_removal = Vec::new(); + + for (key, mut value) in map.iter_mut() { + if value.is_null() { + for_removal.push(key.clone()); + } else { + remove_json_null_values(&mut value); + } + } + + for key in &for_removal { + map.remove(key); + } + } + _ => {} + } +} + +fn did_you_mean<'a>(v: &str, possible_values: &[&'a str]) -> Option<&'a str> { + + let mut candidate: Option<(f64, &str)> = None; + for pv in possible_values { + let confidence = strsim::jaro_winkler(v, pv); + if confidence > 0.8 && (candidate.is_none() || (candidate.as_ref().unwrap().0 < confidence)) { + candidate = Some((confidence, pv)); + } + } + match candidate { + None => None, + Some((_, candidate)) => Some(candidate), + } +} + +pub enum CallType { + Upload(UploadProtocol), + Standard, +} + +arg_enum!{ + pub enum UploadProtocol { + Simple, + Resumable + } +} + +impl AsRef for UploadProtocol { + fn as_ref(&self) -> &str { + match *self { + UploadProtocol::Simple => "simple", + UploadProtocol::Resumable => "resumable" + } + } +} + +impl AsRef for CallType { + fn as_ref(&self) -> &str { + match *self { + CallType::Upload(ref proto) => proto.as_ref(), + CallType::Standard => "standard-request" + } + } +} + +#[derive(Clone, Default)] +pub struct FieldCursor(Vec); + +impl ToString for FieldCursor { + fn to_string(&self) -> String { + self.0.join(".") + } +} + +impl From<&'static str> for FieldCursor { + fn from(value: &'static str) -> FieldCursor { + let mut res = FieldCursor::default(); + res.set(value).unwrap(); + res + } +} + +impl FieldCursor { + pub fn set(&mut self, value: &str) -> Result<(), CLIError> { + if value.len() == 0 { + return Err(CLIError::Field(FieldError::Empty)) + } + + let mut first_is_field_sep = false; + let mut char_count: usize = 0; + let mut last_c = FIELD_SEP; + let mut num_conscutive_field_seps = 0; + + let mut field = String::new(); + let mut fields = self.0.clone(); + + let push_field = |fs: &mut Vec, f: &mut String| { + if f.len() > 0 { + fs.push(f.clone()); + f.truncate(0); + } + }; + + for (cid, c) in value.chars().enumerate() { + char_count += 1; + + if c == FIELD_SEP { + if cid == 0 { + first_is_field_sep = true; + } + num_conscutive_field_seps += 1; + if cid > 0 && last_c == FIELD_SEP { + if fields.pop().is_none() { + return Err(CLIError::Field(FieldError::PopOnEmpty(value.to_string()))) + } + } else { + push_field(&mut fields, &mut field); + } + } else { + num_conscutive_field_seps = 0; + if cid == 1 { + if first_is_field_sep { + fields.truncate(0); + } + } + field.push(c); + } + + last_c = c; + } + + push_field(&mut fields, &mut field); + + if char_count == 1 && first_is_field_sep { + fields.truncate(0); + } + if char_count > 1 && num_conscutive_field_seps == 1 { + return Err(CLIError::Field(FieldError::TrailingFieldSep(value.to_string()))) + } + + self.0 = fields; + Ok(()) + } + + pub fn did_you_mean(value: &str, possible_values: &[&str]) -> Option { + if value.len() == 0 { + return None + } + + let mut last_c = FIELD_SEP; + + let mut field = String::new(); + let mut output = String::new(); + + let push_field = |fs: &mut String, f: &mut String| { + if f.len() > 0 { + fs.push_str( + match did_you_mean(&f, possible_values) { + Some(candidate) => candidate, + None => &f, + }); + f.truncate(0); + } + }; + + for (cid, c) in value.chars().enumerate() { + if c == FIELD_SEP { + if last_c != FIELD_SEP { + push_field(&mut output, &mut field); + } + output.push(c); + } else { + field.push(c); + } + + last_c = c; + } + + push_field(&mut output, &mut field); + + if &output == value { + None + } else { + Some(output) + } + } + + pub fn set_json_value(&self, mut object: &mut Value, + value: &str, type_info: JsonTypeInfo, + err: &mut InvalidOptionsError, + orig_cursor: &FieldCursor) { + assert!(self.0.len() > 0); + + for field in &self.0[..self.0.len()-1] { + let tmp = object; + object = + match *tmp { + Value::Object(ref mut mapping) => { + mapping.entry(field.to_owned()).or_insert( + Value::Object(Default::default()) + ) + }, + _ => panic!("We don't expect non-object Values here ...") + }; + } + + match *object { + Value::Object(ref mut mapping) => { + let field = &self.0[self.0.len()-1]; + let to_jval = + |value: &str, jtype: JsonType, err: &mut InvalidOptionsError| + -> Value { + match jtype { + JsonType::Boolean => + Value::Bool(arg_from_str(value, err, &field, "boolean")), + JsonType::Int => + Value::I64(arg_from_str(value, err, &field, "int")), + JsonType::Uint => + Value::U64(arg_from_str(value, err, &field, "uint")), + JsonType::Float => + Value::F64(arg_from_str(value, err, &field, "float")), + JsonType::String => + Value::String(value.to_owned()), + } + }; + + match type_info.ctype { + ComplexType::Pod => { + if mapping.insert(field.to_owned(), to_jval(value, type_info.jtype, err)).is_some() { + err.issues.push(CLIError::Field(FieldError::Duplicate(orig_cursor.to_string()))); + } + }, + ComplexType::Vec => { + match *mapping.entry(field.to_owned()) + .or_insert(Value::Array(Default::default())) { + Value::Array(ref mut values) => values.push(to_jval(value, type_info.jtype, err)), + _ => unreachable!() + } + }, + ComplexType::Map => { + let (key, value) = parse_kv_arg(value, err, true); + let jval = to_jval(value.unwrap_or(""), type_info.jtype, err); + + match *mapping.entry(field.to_owned()) + .or_insert(Value::Object(Default::default())) { + Value::Object(ref mut value_map) => { + if value_map.insert(key.to_owned(), jval).is_some() { + err.issues.push(CLIError::Field(FieldError::Duplicate(orig_cursor.to_string()))); + } + } + _ => unreachable!() + } + } + } + }, + _ => unreachable!() + } + } + + pub fn num_fields(&self) -> usize { + self.0.len() + } +} + +pub fn parse_kv_arg<'a>(kv: &'a str, err: &mut InvalidOptionsError, for_hashmap: bool) + -> (&'a str, Option<&'a str>) { + let mut add_err = || err.issues.push(CLIError::InvalidKeyValueSyntax(kv.to_string(),for_hashmap)); + match kv.find('=') { + None => { + add_err(); + return (kv, None) + }, + Some(pos) => { + let key = &kv[..pos]; + if kv.len() <= pos + 1 { + add_err(); + return (key, Some("")) + } + (key, Some(&kv[pos+1..])) + } + } +} + +pub fn calltype_from_str(name: &str, valid_protocols: Vec, err: &mut InvalidOptionsError) -> CallType { + CallType::Upload( + match UploadProtocol::from_str(name) { + Ok(up) => up, + Err(msg) => { + err.issues.push(CLIError::InvalidUploadProtocol(name.to_string(), valid_protocols)); + UploadProtocol::Simple + } + }) +} + +pub fn input_file_from_opts(file_path: &str, err: &mut InvalidOptionsError) -> Option { + match fs::File::open(file_path) { + Ok(f) => Some(f), + Err(io_err) => { + err.issues.push(CLIError::Input(InputError::IOError((file_path.to_string(), io_err)))); + None + } + } +} + +pub fn input_mime_from_opts(mime: &str, err: &mut InvalidOptionsError) -> Option { + match mime.parse() { + Ok(m) => Some(m), + Err(_) => { + err.issues.push(CLIError::Input(InputError::Mime(mime.to_string()))); + None + } + } +} + +pub fn writer_from_opts(arg: Option<&str>) -> Result, io::Error> { + let f = arg.unwrap_or("-"); + match f { + "-" => Ok(Box::new(stdout())), + _ => match fs::OpenOptions::new().create(true).write(true).open(f) { + Ok(f) => Ok(Box::new(f)), + Err(io_err) => Err(io_err), + } + } +} + + +pub fn arg_from_str<'a, T>(arg: &str, err: &mut InvalidOptionsError, + arg_name: &'a str, + arg_type: &'a str) -> T + where T: FromStr + Default, + ::Err: fmt::Display { + match FromStr::from_str(arg) { + Err(perr) => { + err.issues.push( + CLIError::ParseError(arg_name.to_owned(), arg_type.to_owned(), arg.to_string(), format!("{}", perr)) + ); + Default::default() + }, + Ok(v) => v, + } +} + +pub struct JsonTokenStorage { + pub program_name: &'static str, + pub db_dir: String, +} + +impl JsonTokenStorage { + fn path(&self, scope_hash: u64) -> PathBuf { + Path::new(&self.db_dir).join(&format!("{}-token-{}.json", self.program_name, scope_hash)) + } +} + +impl TokenStorage for JsonTokenStorage { + type Error = json::Error; + + // NOTE: logging might be interesting, currently we swallow all errors + fn set(&mut self, scope_hash: u64, _: &Vec<&str>, token: Option) -> Result<(), json::Error> { + match token { + None => { + match fs::remove_file(self.path(scope_hash)) { + Err(err) => + match err.kind() { + io::ErrorKind::NotFound => Ok(()), + _ => Err(json::Error::IoError(err)) + }, + Ok(_) => Ok(()), + } + } + Some(token) => { + match fs::OpenOptions::new().create(true).write(true).open(&self.path(scope_hash)) { + Ok(mut f) => { + match json::to_writer_pretty(&mut f, &token) { + Ok(_) => Ok(()), + Err(serde_err) => Err(serde_err), + } + }, + Err(io_err) => Err(json::Error::IoError(io_err)) + } + } + } + } + + fn get(&self, scope_hash: u64, _: &Vec<&str>) -> Result, json::Error> { + match fs::File::open(&self.path(scope_hash)) { + Ok(mut f) => { + match json::de::from_reader(f) { + Ok(token) => Ok(Some(token)), + Err(err) => Err(err), + } + }, + Err(io_err) => { + match io_err.kind() { + io::ErrorKind::NotFound => Ok(None), + _ => Err(json::Error::IoError(io_err)) + } + } + } + } +} + + +#[derive(Debug)] +pub enum ApplicationSecretError { + DecoderError((String, json::Error)), + FormatError(String), +} + +impl fmt::Display for ApplicationSecretError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + ApplicationSecretError::DecoderError((ref path, ref err)) + => writeln!(f, "Could not decode file at '{}' with error: {}.", + path, err), + ApplicationSecretError::FormatError(ref path) + => writeln!(f, "'installed' field is unset in secret file at '{}'.", + path), + } + } +} + +#[derive(Debug)] +pub enum ConfigurationError { + DirectoryCreationFailed((String, io::Error)), + DirectoryUnset, + HomeExpansionFailed(String), + Secret(ApplicationSecretError), + IOError((String, io::Error)), +} + +impl fmt::Display for ConfigurationError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + ConfigurationError::DirectoryCreationFailed((ref dir, ref err)) + => writeln!(f, "Directory '{}' could not be created with error: {}.", dir, err), + ConfigurationError::DirectoryUnset + => writeln!(f, "--config-dir was unset or empty."), + ConfigurationError::HomeExpansionFailed(ref dir) + => writeln!(f, "Couldn't find HOME directory of current user, failed to expand '{}'.", dir), + ConfigurationError::Secret(ref err) + => writeln!(f, "Secret -> {}", err), + ConfigurationError::IOError((ref path, ref err)) + => writeln!(f, "IO operation failed on path '{}' with error: {}.", path, err), + } + } +} + +#[derive(Debug)] +pub enum InputError { + IOError((String, io::Error)), + Mime(String), +} + +impl fmt::Display for InputError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + InputError::IOError((ref file_path, ref io_err)) + => writeln!(f, "Failed to open '{}' for reading with error: {}.", file_path, io_err), + InputError::Mime(ref mime) + => writeln!(f, "'{}' is not a known mime-type.", mime), + } + } +} + +#[derive(Debug)] +pub enum FieldError { + PopOnEmpty(String), + TrailingFieldSep(String), + Unknown(String, Option, Option), + Duplicate(String), + Empty, +} + + +impl fmt::Display for FieldError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + FieldError::PopOnEmpty(ref field) + => writeln!(f, "'{}': Cannot move up on empty field cursor.", field), + FieldError::TrailingFieldSep(ref field) + => writeln!(f, "'{}': Single field separator may not be last character.", field), + FieldError::Unknown(ref field, ref suggestion, ref value) => { + let suffix = + match *suggestion { + Some(ref s) => { + let kv = + match *value { + Some(ref v) => format!("{}={}", s, v), + None => s.clone(), + }; + format!(" Did you mean '{}' ?", kv) + }, + None => String::new(), + }; + writeln!(f, "Field '{}' does not exist.{}", field, suffix) + }, + FieldError::Duplicate(ref cursor) + => writeln!(f, "Value at '{}' was already set", cursor), + FieldError::Empty + => writeln!(f, "Field names must not be empty."), + } + } +} + + +#[derive(Debug)] +pub enum CLIError { + Configuration(ConfigurationError), + ParseError(String, String, String, String), + UnknownParameter(String, Vec<&'static str>), + InvalidUploadProtocol(String, Vec), + InvalidKeyValueSyntax(String, bool), + Input(InputError), + Field(FieldError), + MissingCommandError, + MissingMethodError(String), +} + +impl fmt::Display for CLIError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + CLIError::Configuration(ref err) => write!(f, "Configuration -> {}", err), + CLIError::Input(ref err) => write!(f, "Input -> {}", err), + CLIError::Field(ref err) => write!(f, "Field -> {}", err), + CLIError::InvalidUploadProtocol(ref proto_name, ref valid_names) + => writeln!(f, "'{}' is not a valid upload protocol. Choose from one of {}.", proto_name, valid_names.join(", ")), + CLIError::ParseError(ref arg_name, ref type_name, ref value, ref err_desc) + => writeln!(f, "Failed to parse argument '{}' with value '{}' as {} with error: {}.", + arg_name, value, type_name, err_desc), + CLIError::UnknownParameter(ref param_name, ref possible_values) => { + let mut suffix = + match did_you_mean(param_name, &possible_values) { + Some(v) => format!(" Did you mean '{}' ?", v), + None => String::new(), + }; + write!(f, "Parameter '{}' is unknown.{}\n", param_name, suffix) + }, + CLIError::InvalidKeyValueSyntax(ref kv, is_hashmap) => { + let hashmap_info = if is_hashmap { "hashmap " } else { "" }; + writeln!(f, "'{}' does not match {}pattern =.", kv, hashmap_info) + }, + CLIError::MissingCommandError => writeln!(f, "Please specify the main sub-command."), + CLIError::MissingMethodError(ref cmd) => writeln!(f, "Please specify the method to call on the '{}' command.", cmd), + } + } +} + +#[derive(Debug)] +pub struct InvalidOptionsError { + pub issues: Vec, + pub exit_code: i32, +} + +impl fmt::Display for InvalidOptionsError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + for issue in &self.issues { + try!(issue.fmt(f)); + } + Ok(()) + } +} + +impl InvalidOptionsError { + pub fn single(err: CLIError, exit_code: i32) -> InvalidOptionsError { + InvalidOptionsError { + issues: vec![err], + exit_code: exit_code, + } + } + + pub fn new() -> InvalidOptionsError { + InvalidOptionsError { + issues: Vec::new(), + exit_code: 1, + } + } +} + +pub fn assure_config_dir_exists(dir: &str) -> Result { + let trdir = dir.trim(); + if trdir.len() == 0 { + return Err(CLIError::Configuration(ConfigurationError::DirectoryUnset)) + } + + let expanded_config_dir = + if trdir.as_bytes()[0] == b'~' { + match env::var("HOME").ok().or(env::var("UserProfile").ok()) { + None => return Err(CLIError::Configuration(ConfigurationError::HomeExpansionFailed(trdir.to_string()))), + Some(mut user) => { + user.push_str(&trdir[1..]); + user + } + } + } else { + trdir.to_string() + }; + + if let Err(err) = fs::create_dir(&expanded_config_dir) { + if err.kind() != io::ErrorKind::AlreadyExists { + return Err(CLIError::Configuration( + ConfigurationError::DirectoryCreationFailed((expanded_config_dir, err)))) + } + } + + Ok(expanded_config_dir) +} + +pub fn application_secret_from_directory(dir: &str, + secret_basename: &str, + json_console_secret: &str) + -> Result { + let secret_path = Path::new(dir).join(secret_basename); + let secret_str = || secret_path.as_path().to_str().unwrap().to_string(); + let secret_io_error = |io_err: io::Error| { + Err(CLIError::Configuration(ConfigurationError::IOError( + (secret_str(), io_err) + ))) + }; + + for _ in 0..2 { + match fs::File::open(&secret_path) { + Err(mut err) => { + if err.kind() == io::ErrorKind::NotFound { + // Write our built-in one - user may adjust the written file at will + + err = match fs::OpenOptions::new().create(true).write(true).open(&secret_path) { + Err(cfe) => cfe, + Ok(mut f) => { + // Assure we convert 'ugly' json string into pretty one + let console_secret: ConsoleApplicationSecret + = json::from_str(json_console_secret).unwrap(); + match json::to_writer_pretty(&mut f, &console_secret) { + Err(serde_err) => match serde_err { + json::Error::IoError(err) => err, + _ => panic!("Unexpected serde error: {:#?}", serde_err) + }, + Ok(_) => continue, + } + } + }; + // fall through to IO error handling + } + return secret_io_error(err) + }, + Ok(mut f) => { + match json::de::from_reader::<_, ConsoleApplicationSecret>(f) { + Err(json::Error::IoError(err)) => + return secret_io_error(err), + Err(json_err) => + return Err(CLIError::Configuration( + ConfigurationError::Secret( + ApplicationSecretError::DecoderError( + (secret_str(), json_err) + )))), + Ok(console_secret) => + match console_secret.installed { + Some(secret) => return Ok(secret), + None => return Err( + CLIError::Configuration( + ConfigurationError::Secret( + ApplicationSecretError::FormatError(secret_str()) + ))) + }, + } + } + } + } + unreachable!(); +} diff --git a/gen/container1-cli/src/main.rs b/gen/container1-cli/src/main.rs new file mode 100644 index 0000000000..5045637494 --- /dev/null +++ b/gen/container1-cli/src/main.rs @@ -0,0 +1,1039 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/cli/main.rs.mako' +// DO NOT EDIT ! +#![allow(unused_variables, unused_imports, dead_code, unused_mut)] + +#[macro_use] +extern crate clap; +extern crate yup_oauth2 as oauth2; +extern crate yup_hyper_mock as mock; +extern crate serde; +extern crate serde_json; +extern crate hyper; +extern crate mime; +extern crate strsim; +extern crate google_container1 as api; + +use std::env; +use std::io::{self, Write}; +use clap::{App, SubCommand, Arg}; + +mod cmn; + +use cmn::{InvalidOptionsError, CLIError, JsonTokenStorage, arg_from_str, writer_from_opts, parse_kv_arg, + input_file_from_opts, input_mime_from_opts, FieldCursor, FieldError, CallType, UploadProtocol, + calltype_from_str, remove_json_null_values, ComplexType, JsonType, JsonTypeInfo}; + +use std::default::Default; +use std::str::FromStr; + +use oauth2::{Authenticator, DefaultAuthenticatorDelegate}; +use serde_json as json; +use clap::ArgMatches; + +enum DoitError { + IoError(String, io::Error), + ApiError(api::Error), +} + +struct Engine<'n, 'a> { + opt: ArgMatches<'n, 'a>, + hub: api::Container>, + gp: Vec<&'static str>, + gpm: Vec<(&'static str, &'static str)>, +} + + +impl<'n, 'a> Engine<'n, 'a> { + fn _projects_zones_clusters_create(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "cluster.status" => Some(("cluster.status", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "cluster.node-ipv4-cidr-size" => Some(("cluster.nodeIpv4CidrSize", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "cluster.status-message" => Some(("cluster.statusMessage", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "cluster.endpoint" => Some(("cluster.endpoint", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "cluster.description" => Some(("cluster.description", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "cluster.logging-service" => Some(("cluster.loggingService", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "cluster.current-node-version" => Some(("cluster.currentNodeVersion", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "cluster.instance-group-urls" => Some(("cluster.instanceGroupUrls", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "cluster.current-master-version" => Some(("cluster.currentMasterVersion", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "cluster.services-ipv4-cidr" => Some(("cluster.servicesIpv4Cidr", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "cluster.master-auth.username" => Some(("cluster.masterAuth.username", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "cluster.master-auth.password" => Some(("cluster.masterAuth.password", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "cluster.master-auth.client-key" => Some(("cluster.masterAuth.clientKey", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "cluster.master-auth.client-certificate" => Some(("cluster.masterAuth.clientCertificate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "cluster.master-auth.cluster-ca-certificate" => Some(("cluster.masterAuth.clusterCaCertificate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "cluster.name" => Some(("cluster.name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "cluster.initial-cluster-version" => Some(("cluster.initialClusterVersion", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "cluster.node-config.disk-size-gb" => Some(("cluster.nodeConfig.diskSizeGb", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "cluster.node-config.machine-type" => Some(("cluster.nodeConfig.machineType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "cluster.node-config.oauth-scopes" => Some(("cluster.nodeConfig.oauthScopes", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "cluster.initial-node-count" => Some(("cluster.initialNodeCount", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "cluster.cluster-ipv4-cidr" => Some(("cluster.clusterIpv4Cidr", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "cluster.monitoring-service" => Some(("cluster.monitoringService", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "cluster.zone" => Some(("cluster.zone", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "cluster.create-time" => Some(("cluster.createTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "cluster.self-link" => Some(("cluster.selfLink", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "cluster.network" => Some(("cluster.network", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["client-certificate", "client-key", "cluster", "cluster-ca-certificate", "cluster-ipv4-cidr", "create-time", "current-master-version", "current-node-version", "description", "disk-size-gb", "endpoint", "initial-cluster-version", "initial-node-count", "instance-group-urls", "logging-service", "machine-type", "master-auth", "monitoring-service", "name", "network", "node-config", "node-ipv4-cidr-size", "oauth-scopes", "password", "self-link", "services-ipv4-cidr", "status", "status-message", "username", "zone"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::CreateClusterRequest = json::value::from_value(object).unwrap(); + let mut call = self.hub.projects().zones_clusters_create(request, opt.value_of("project-id").unwrap_or(""), opt.value_of("zone").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _projects_zones_clusters_delete(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.projects().zones_clusters_delete(opt.value_of("project-id").unwrap_or(""), opt.value_of("zone").unwrap_or(""), opt.value_of("cluster-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _projects_zones_clusters_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.projects().zones_clusters_get(opt.value_of("project-id").unwrap_or(""), opt.value_of("zone").unwrap_or(""), opt.value_of("cluster-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _projects_zones_clusters_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.projects().zones_clusters_list(opt.value_of("project-id").unwrap_or(""), opt.value_of("zone").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _projects_zones_clusters_update(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "update.desired-node-version" => Some(("update.desiredNodeVersion", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["desired-node-version", "update"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::UpdateClusterRequest = json::value::from_value(object).unwrap(); + let mut call = self.hub.projects().zones_clusters_update(request, opt.value_of("project-id").unwrap_or(""), opt.value_of("zone").unwrap_or(""), opt.value_of("cluster-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _projects_zones_get_serverconfig(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.projects().zones_get_serverconfig(opt.value_of("project-id").unwrap_or(""), opt.value_of("zone").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _projects_zones_operations_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.projects().zones_operations_get(opt.value_of("project-id").unwrap_or(""), opt.value_of("zone").unwrap_or(""), opt.value_of("operation-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _projects_zones_operations_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.projects().zones_operations_list(opt.value_of("project-id").unwrap_or(""), opt.value_of("zone").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _doit(&self, dry_run: bool) -> Result, Option> { + let mut err = InvalidOptionsError::new(); + let mut call_result: Result<(), DoitError> = Ok(()); + let mut err_opt: Option = None; + match self.opt.subcommand() { + ("projects", Some(opt)) => { + match opt.subcommand() { + ("zones-clusters-create", Some(opt)) => { + call_result = self._projects_zones_clusters_create(opt, dry_run, &mut err); + }, + ("zones-clusters-delete", Some(opt)) => { + call_result = self._projects_zones_clusters_delete(opt, dry_run, &mut err); + }, + ("zones-clusters-get", Some(opt)) => { + call_result = self._projects_zones_clusters_get(opt, dry_run, &mut err); + }, + ("zones-clusters-list", Some(opt)) => { + call_result = self._projects_zones_clusters_list(opt, dry_run, &mut err); + }, + ("zones-clusters-update", Some(opt)) => { + call_result = self._projects_zones_clusters_update(opt, dry_run, &mut err); + }, + ("zones-get-serverconfig", Some(opt)) => { + call_result = self._projects_zones_get_serverconfig(opt, dry_run, &mut err); + }, + ("zones-operations-get", Some(opt)) => { + call_result = self._projects_zones_operations_get(opt, dry_run, &mut err); + }, + ("zones-operations-list", Some(opt)) => { + call_result = self._projects_zones_operations_list(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("projects".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + _ => { + err.issues.push(CLIError::MissingCommandError); + writeln!(io::stderr(), "{}\n", self.opt.usage()).ok(); + } + } + + if dry_run { + if err.issues.len() > 0 { + err_opt = Some(err); + } + Err(err_opt) + } else { + Ok(call_result) + } + } + + // Please note that this call will fail if any part of the opt can't be handled + fn new(opt: ArgMatches<'a, 'n>) -> Result, InvalidOptionsError> { + let (config_dir, secret) = { + let config_dir = match cmn::assure_config_dir_exists(opt.value_of("folder").unwrap_or("~/.google-service-cli")) { + Err(e) => return Err(InvalidOptionsError::single(e, 3)), + Ok(p) => p, + }; + + match cmn::application_secret_from_directory(&config_dir, "container1-secret.json", + "{\"installed\":{\"auth_uri\":\"https://accounts.google.com/o/oauth2/auth\",\"client_secret\":\"hCsslbCUyfehWMmbkG8vTYxG\",\"token_uri\":\"https://accounts.google.com/o/oauth2/token\",\"client_email\":\"\",\"redirect_uris\":[\"urn:ietf:wg:oauth:2.0:oob\",\"oob\"],\"client_x509_cert_url\":\"\",\"client_id\":\"620010449518-9ngf7o4dhs0dka470npqvor6dc5lqb9b.apps.googleusercontent.com\",\"auth_provider_x509_cert_url\":\"https://www.googleapis.com/oauth2/v1/certs\"}}") { + Ok(secret) => (config_dir, secret), + Err(e) => return Err(InvalidOptionsError::single(e, 4)) + } + }; + + let auth = Authenticator::new( &secret, DefaultAuthenticatorDelegate, + if opt.is_present("debug-auth") { + hyper::Client::with_connector(mock::TeeConnector { + connector: hyper::net::HttpsConnector::::default() + }) + } else { + hyper::Client::new() + }, + JsonTokenStorage { + program_name: "container1", + db_dir: config_dir.clone(), + }, None); + + let client = + if opt.is_present("debug") { + hyper::Client::with_connector(mock::TeeConnector { + connector: hyper::net::HttpsConnector::::default() + }) + } else { + hyper::Client::new() + }; + let engine = Engine { + opt: opt, + hub: api::Container::new(client, auth), + gp: vec!["$-xgafv", "access-token", "alt", "bearer-token", "callback", "fields", "key", "oauth-token", "pp", "pretty-print", "quota-user", "upload-type", "upload-protocol"], + gpm: vec![ + ("$-xgafv", "$.xgafv"), + ("access-token", "access_token"), + ("bearer-token", "bearer_token"), + ("oauth-token", "oauth_token"), + ("pretty-print", "prettyPrint"), + ("quota-user", "quotaUser"), + ("upload-type", "uploadType"), + ("upload-protocol", "upload_protocol"), + ] + }; + + match engine._doit(true) { + Err(Some(err)) => Err(err), + Err(None) => Ok(engine), + Ok(_) => unreachable!(), + } + } + + fn doit(&self) -> Result<(), DoitError> { + match self._doit(false) { + Ok(res) => res, + Err(_) => unreachable!(), + } + } +} + +fn main() { + let mut exit_status = 0i32; + let arg_data = [ + ("projects", "methods: 'zones-clusters-create', 'zones-clusters-delete', 'zones-clusters-get', 'zones-clusters-list', 'zones-clusters-update', 'zones-get-serverconfig', 'zones-operations-get' and 'zones-operations-list'", vec![ + ("zones-clusters-create", + Some(r##"Creates a cluster, consisting of the specified number and type of Google Compute Engine instances, plus a Kubernetes master endpoint. By default, the cluster is created in the project's [default network](/compute/docs/networking#networks_1). One firewall is added for the cluster. After cluster creation, the cluster creates routes for each node to allow the containers on that node to communicate with all other instances in the cluster. Finally, an entry is added to the project's global metadata indicating which CIDR range is being used by the cluster."##), + "Details at http://byron.github.io/google-apis-rs/google_container1_cli/projects_zones-clusters-create", + vec![ + (Some(r##"project-id"##), + None, + Some(r##"The Google Developers Console [project ID or project number](https://developers.google.com/console/help/new/#projectnumber)."##), + Some(true), + Some(false)), + + (Some(r##"zone"##), + None, + Some(r##"The name of the Google Compute Engine [zone](/compute/docs/zones#available) in which the cluster resides."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("zones-clusters-delete", + Some(r##"Deletes the cluster, including the Kubernetes endpoint and all worker nodes. Firewalls and routes that were configured during cluster creation are also deleted."##), + "Details at http://byron.github.io/google-apis-rs/google_container1_cli/projects_zones-clusters-delete", + vec![ + (Some(r##"project-id"##), + None, + Some(r##"The Google Developers Console [project ID or project number](https://developers.google.com/console/help/new/#projectnumber)."##), + Some(true), + Some(false)), + + (Some(r##"zone"##), + None, + Some(r##"The name of the Google Compute Engine [zone](/compute/docs/zones#available) in which the cluster resides."##), + Some(true), + Some(false)), + + (Some(r##"cluster-id"##), + None, + Some(r##"The name of the cluster to delete."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("zones-clusters-get", + Some(r##"Gets a specific cluster."##), + "Details at http://byron.github.io/google-apis-rs/google_container1_cli/projects_zones-clusters-get", + vec![ + (Some(r##"project-id"##), + None, + Some(r##"The Google Developers Console [project ID or project number](https://developers.google.com/console/help/new/#projectnumber)."##), + Some(true), + Some(false)), + + (Some(r##"zone"##), + None, + Some(r##"The name of the Google Compute Engine [zone](/compute/docs/zones#available) in which the cluster resides."##), + Some(true), + Some(false)), + + (Some(r##"cluster-id"##), + None, + Some(r##"The name of the cluster to retrieve."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("zones-clusters-list", + Some(r##"Lists all clusters owned by a project in either the specified zone or all zones."##), + "Details at http://byron.github.io/google-apis-rs/google_container1_cli/projects_zones-clusters-list", + vec![ + (Some(r##"project-id"##), + None, + Some(r##"The Google Developers Console [project ID or project number](https://developers.google.com/console/help/new/#projectnumber)."##), + Some(true), + Some(false)), + + (Some(r##"zone"##), + None, + Some(r##"The name of the Google Compute Engine [zone](/compute/docs/zones#available) in which the cluster resides, or "-" for all zones."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("zones-clusters-update", + Some(r##"Update settings of a specific cluster."##), + "Details at http://byron.github.io/google-apis-rs/google_container1_cli/projects_zones-clusters-update", + vec![ + (Some(r##"project-id"##), + None, + Some(r##"The Google Developers Console [project ID or project number](https://developers.google.com/console/help/new/#projectnumber)."##), + Some(true), + Some(false)), + + (Some(r##"zone"##), + None, + Some(r##"The name of the Google Compute Engine [zone](/compute/docs/zones#available) in which the cluster resides."##), + Some(true), + Some(false)), + + (Some(r##"cluster-id"##), + None, + Some(r##"The name of the cluster to upgrade."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("zones-get-serverconfig", + Some(r##"Returns configuration info about the Container Engine service."##), + "Details at http://byron.github.io/google-apis-rs/google_container1_cli/projects_zones-get-serverconfig", + vec![ + (Some(r##"project-id"##), + None, + Some(r##"The Google Developers Console [project ID or project number](https://developers.google.com/console/help/new/#projectnumber)."##), + Some(true), + Some(false)), + + (Some(r##"zone"##), + None, + Some(r##"The name of the Google Compute Engine [zone](/compute/docs/zones#available) to return operations for, or "-" for all zones."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("zones-operations-get", + Some(r##"Gets the specified operation."##), + "Details at http://byron.github.io/google-apis-rs/google_container1_cli/projects_zones-operations-get", + vec![ + (Some(r##"project-id"##), + None, + Some(r##"The Google Developers Console [project ID or project number](https://developers.google.com/console/help/new/#projectnumber)."##), + Some(true), + Some(false)), + + (Some(r##"zone"##), + None, + Some(r##"The name of the Google Compute Engine [zone](/compute/docs/zones#available) in which the cluster resides."##), + Some(true), + Some(false)), + + (Some(r##"operation-id"##), + None, + Some(r##"The server-assigned `name` of the operation."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("zones-operations-list", + Some(r##"Lists all operations in a project in a specific zone or all zones."##), + "Details at http://byron.github.io/google-apis-rs/google_container1_cli/projects_zones-operations-list", + vec![ + (Some(r##"project-id"##), + None, + Some(r##"The Google Developers Console [project ID or project number](https://developers.google.com/console/help/new/#projectnumber)."##), + Some(true), + Some(false)), + + (Some(r##"zone"##), + None, + Some(r##"The name of the Google Compute Engine [zone](/compute/docs/zones#available) to return operations for, or "-" for all zones."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ]; + + let mut app = App::new("container1") + .author("Sebastian Thiel ") + .version("0.3.2+20150603") + .about("The Google Container Engine API is used for building and managing container based applications, powered by the open source Kubernetes technology.") + .after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_container1_cli") + .arg(Arg::with_name("url") + .long("scope") + .help("Specify the authentication a method should be executed in. Each scope requires the user to grant this application permission to use it.If unset, it defaults to the shortest scope url for a particular method.") + .multiple(true) + .takes_value(true)) + .arg(Arg::with_name("folder") + .long("config-dir") + .help("A directory into which we will store our persistent data. Defaults to a user-writable directory that we will create during the first invocation.[default: ~/.google-service-cli") + .multiple(false) + .takes_value(true)) + .arg(Arg::with_name("debug") + .long("debug") + .help("Output all server communication to standard error. `tx` and `rx` are placed into the same stream.") + .multiple(false) + .takes_value(false)) + .arg(Arg::with_name("debug-auth") + .long("debug-auth") + .help("Output all communication related to authentication to standard error. `tx` and `rx` are placed into the same stream.") + .multiple(false) + .takes_value(false)); + + for &(main_command_name, ref about, ref subcommands) in arg_data.iter() { + let mut mcmd = SubCommand::with_name(main_command_name).about(about); + + for &(sub_command_name, ref desc, url_info, ref args) in subcommands { + let mut scmd = SubCommand::with_name(sub_command_name); + if let &Some(desc) = desc { + scmd = scmd.about(desc); + } + scmd = scmd.after_help(url_info); + + for &(ref arg_name, ref flag, ref desc, ref required, ref multi) in args { + let arg_name_str = + match (arg_name, flag) { + (&Some(an), _ ) => an, + (_ , &Some(f)) => f, + _ => unreachable!(), + }; + let mut arg = Arg::with_name(arg_name_str) + .empty_values(false); + if let &Some(short_flag) = flag { + arg = arg.short(short_flag); + } + if let &Some(desc) = desc { + arg = arg.help(desc); + } + if arg_name.is_some() && flag.is_some() { + arg = arg.takes_value(true); + } + if let &Some(required) = required { + arg = arg.required(required); + } + if let &Some(multi) = multi { + arg = arg.multiple(multi); + } + scmd = scmd.arg(arg); + } + mcmd = mcmd.subcommand(scmd); + } + app = app.subcommand(mcmd); + } + + let matches = app.get_matches(); + + let debug = matches.is_present("debug"); + match Engine::new(matches) { + Err(err) => { + exit_status = err.exit_code; + writeln!(io::stderr(), "{}", err).ok(); + }, + Ok(engine) => { + if let Err(doit_err) = engine.doit() { + exit_status = 1; + match doit_err { + DoitError::IoError(path, err) => { + writeln!(io::stderr(), "Failed to open output file '{}': {}", path, err).ok(); + }, + DoitError::ApiError(err) => { + if debug { + writeln!(io::stderr(), "{:#?}", err).ok(); + } else { + writeln!(io::stderr(), "{}", err).ok(); + } + } + } + } + } + } + + std::process::exit(exit_status); +} \ No newline at end of file diff --git a/gen/container1/Cargo.toml b/gen/container1/Cargo.toml new file mode 100644 index 0000000000..682333b147 --- /dev/null +++ b/gen/container1/Cargo.toml @@ -0,0 +1,29 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-container1" +version = "0.1.9+20150603" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with container (protocol v1)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/container1" +homepage = "https://cloud.google.com/container-engine/" +documentation = "http://byron.github.io/google-apis-rs/google_container1" +license = "MIT" +keywords = ["container", "google", "protocol", "web", "api"] +build = "src/build.rs" + + +[dependencies] +hyper = ">= 0.6.8" +mime = "0.1.0" +serde = ">= 0.6.0" +serde_json = ">= 0.6.0" +yup-oauth2 = "*" +url = "*" + +[build-dependencies] +syntex = { version = "*" } +serde_codegen = { version = "*" } + diff --git a/gen/container1/LICENSE.md b/gen/container1/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/container1/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/README.md b/gen/container1/README.md new file mode 100644 index 0000000000..0cae72a5a9 --- /dev/null +++ b/gen/container1/README.md @@ -0,0 +1,182 @@ + +The `google-container1` library allows access to all features of the *Google container* service. + +This documentation was generated from *container* crate version *0.1.9+20150603*, where *20150603* is the exact revision of the *container:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. + +Everything else about the *container* *v1* API can be found at the +[official documentation site](https://cloud.google.com/container-engine/). +# Features + +Handle the following *Resources* with ease from the central [hub](http://byron.github.io/google-apis-rs/google_container1/struct.Container.html) ... + +* projects + * [*zones clusters create*](http://byron.github.io/google-apis-rs/google_container1/struct.ProjectZoneClusterCreateCall.html), [*zones clusters delete*](http://byron.github.io/google-apis-rs/google_container1/struct.ProjectZoneClusterDeleteCall.html), [*zones clusters get*](http://byron.github.io/google-apis-rs/google_container1/struct.ProjectZoneClusterGetCall.html), [*zones clusters list*](http://byron.github.io/google-apis-rs/google_container1/struct.ProjectZoneClusterListCall.html), [*zones clusters update*](http://byron.github.io/google-apis-rs/google_container1/struct.ProjectZoneClusterUpdateCall.html), [*zones get serverconfig*](http://byron.github.io/google-apis-rs/google_container1/struct.ProjectZoneGetServerconfigCall.html), [*zones operations get*](http://byron.github.io/google-apis-rs/google_container1/struct.ProjectZoneOperationGetCall.html) and [*zones operations list*](http://byron.github.io/google-apis-rs/google_container1/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/struct.Container.html)** + * a central object to maintain state and allow accessing all *Activities* + * creates [*Method Builders*](http://byron.github.io/google-apis-rs/google_container1/trait.MethodsBuilder.html) which in turn + allow access to individual [*Call Builders*](http://byron.github.io/google-apis-rs/google_container1/trait.CallBuilder.html) +* **[Resources](http://byron.github.io/google-apis-rs/google_container1/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/trait.Part.html)** + * a collection of properties + * never directly used in *Activities* +* **[Activities](http://byron.github.io/google-apis-rs/google_container1/trait.CallBuilder.html)** + * operations to apply to *Resources* + +All *structures* are marked with applicable traits to further categorize them and ease browsing. + +Generally speaking, you can invoke *Activities* like this: + +```Rust,ignore +let r = hub.resource().activity(...).doit() +``` + +Or specifically ... + +```ignore +let r = hub.projects().zones_clusters_update(...).doit() +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 = "*" +``` + +## A complete example + +```Rust +extern crate hyper; +extern crate yup_oauth2 as oauth2; +extern crate google_container1 as container1; +use container1::UpdateClusterRequest; +use container1::{Result, Error}; +use std::default::Default; +use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +use container1::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); +// As the method needs a request, you would usually fill it with the desired information +// into the respective structure. Some of the parts shown here might not be applicable ! +// Values shown here are possibly random and not representative ! +let mut req = UpdateClusterRequest::default(); + +// You can configure optional parameters by calling 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_update(req, "projectId", "zone", "clusterId") + .doit(); + +match result { + Err(e) => match e { + // The Error enum provides details about what exactly happened. + // You can also just use its `Debug`, `Display` or `Error` traits + Error::HttpError(_) + |Error::MissingAPIKey + |Error::MissingToken(_) + |Error::Cancelled + |Error::UploadSizeLimitExceeded(_, _) + |Error::Failure(_) + |Error::BadRequest(_) + |Error::FieldClash(_) + |Error::JsonDecodeError(_, _) => println!("{}", e), + }, + Ok(res) => println!("Success: {:?}", res), +} + +``` +## Handling Errors + +All errors produced by the system are provided either as [Result](http://byron.github.io/google-apis-rs/google_container1/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/trait.Delegate.html), or the [Authenticator Delegate](http://byron.github.io/google-apis-rs/google_container1/../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 Downloads +If a method supports downloads, the response body, which is part of the [Result](http://byron.github.io/google-apis-rs/google_container1/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/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/trait.Delegate.html) to the +[Method Builder](http://byron.github.io/google-apis-rs/google_container1/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/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/trait.RequestValue.html) and +[decodable](http://byron.github.io/google-apis-rs/google_container1/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/trait.Part.html) which are identifiable 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/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/trait.RequestValue.html) are moved + +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** 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/src/build.rs b/gen/container1/src/build.rs new file mode 100644 index 0000000000..7265b49462 --- /dev/null +++ b/gen/container1/src/build.rs @@ -0,0 +1,16 @@ +extern crate syntex; +extern crate serde_codegen; + +use std::env; +use std::path::Path; + +pub fn main() { + let out_dir = env::var_os("OUT_DIR").unwrap(); + + let src = Path::new("src/lib.rs.in"); + let dst = Path::new(&out_dir).join("lib.rs"); + + let mut registry = syntex::Registry::new(); + serde_codegen::register(&mut registry); + registry.expand("google-container1", &src, &dst).unwrap(); +} diff --git a/gen/container1/src/cmn.rs b/gen/container1/src/cmn.rs new file mode 100644 index 0000000000..0e31353ba3 --- /dev/null +++ b/gen/container1/src/cmn.rs @@ -0,0 +1,762 @@ +// COPY OF 'src/rust/api/cmn.rs' +// DO NOT EDIT +use std::io::{self, Read, Seek, Cursor, Write, SeekFrom}; +use std; +use std::fmt::{self, Display}; +use std::str::FromStr; +use std::error; +use std::thread::sleep_ms; + +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::h1::LINE_ENDING; +use hyper::method::Method; +use hyper::status::StatusCode; + +use serde_json as json; + +/// 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 {} + +/// Identifies types for building methods of a particular resource type +pub trait MethodsBuilder {} + +/// Identifies types which represent builders for a particular resource method +pub trait CallBuilder {} + +/// Identifies types which can be inserted and deleted. +/// Types with this trait are most commonly used by clients of this API. +pub trait Resource {} + +/// Identifies types which are used in API responses. +pub trait ResponseResult {} + +/// Identifies types which are used in API requests. +pub trait RequestValue {} + +/// Identifies types which are not actually used by the API +/// This might be a bug within the google API schema. +pub trait UnusedType {} + +/// Identifies types which are only used as part of other types, which +/// usually are carrying the `Resource` trait. +pub trait Part {} + +/// 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 {} + +/// 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 +} + +/// A utility to represent detailed errors we might see in case there are BadRequests. +/// The latter happen if the sent parameters or request structures are unsound +#[derive(Deserialize, Serialize, Debug)] +pub struct ErrorResponse { + error: ServerError, +} + +#[derive(Deserialize, Serialize, Debug)] +pub struct ServerError { + errors: Vec, + code: u16, + message: String, +} + +#[derive(Deserialize, Serialize, Debug)] +pub struct ServerMessage { + domain: String, + reason: String, + message: String, + #[serde(rename="locationType")] + location_type: Option, + location: 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 successful. That way, the delegate 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. + /// + /// If you choose to retry after a duration, the duration should be chosen using the + /// [exponential backoff algorithm](http://en.wikipedia.org/wiki/Exponential_backoff). + /// + /// Return retry information. + fn http_error(&mut self, &hyper::Error) -> 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 it as a general information about the + /// impending failure. + /// The given Error provides information about why the token couldn't be acquired in the + /// first place + fn token(&mut self, err: &error::Error) -> Option { + let _ = err; + 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/canceled, 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()`. + /// It will also be called with None after a successful upload, which allows the delegate + /// to forget the URL. That way, we will not attempt to resume an upload that has already + /// finished. + fn store_upload_url(&mut self, url: Option<&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: &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. + /// + /// If you choose to retry after a duration, the duration should be chosen using the + /// [exponential backoff algorithm](http://en.wikipedia.org/wiki/Exponential_backoff). + fn http_failure(&mut self, _: &hyper::client::Response, Option, _: 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 {} + + +#[derive(Debug)] +pub enum Error { + /// The http connection failed + HttpError(hyper::Error), + + /// 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), + + /// Represents information about a request that was not understood by the server. + /// Details are included. + BadRequest(ErrorResponse), + + /// 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(Box), + + /// 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(String, json::Error), + + /// Indicates an HTTP repsonse with a non-success status code + Failure(hyper::client::Response), +} + + +impl Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + Error::HttpError(ref err) => err.fmt(f), + Error::UploadSizeLimitExceeded(ref resource_size, ref max_size) => + writeln!(f, "The media size {} exceeds the maximum allowed upload size of {}" + , resource_size, max_size), + Error::MissingAPIKey => { + (writeln!(f, "The application's API key was not found in the configuration")).ok(); + writeln!(f, "It is used as there are no Scopes defined for this method.") + }, + Error::BadRequest(ref err) => { + try!(writeln!(f, "Bad Requst ({}): {}", err.error.code, err.error.message)); + for err in err.error.errors.iter() { + try!(writeln!(f, " {}: {}, {}{}", + err.domain, + err.message, + err.reason, + match &err.location { + &Some(ref loc) => format!("@{}", loc), + &None => String::new(), + })); + } + Ok(()) + }, + Error::MissingToken(ref err) => + writeln!(f, "Token retrieval failed with error: {}", err), + Error::Cancelled => + writeln!(f, "Operation cancelled by delegate"), + Error::FieldClash(field) => + writeln!(f, "The custom parameter '{}' is already provided natively by the CallBuilder.", field), + Error::JsonDecodeError(ref json_str, ref err) + => writeln!(f, "{}: {}", err, json_str), + Error::Failure(ref response) => + writeln!(f, "Http status indicates failure: {:?}", response), + } + } +} + +impl error::Error for Error { + fn description(&self) -> &str { + match *self { + Error::HttpError(ref err) => err.description(), + Error::JsonDecodeError(_, ref err) => err.description(), + _ => "NO DESCRIPTION POSSIBLE - use `Display.fmt()` instead" + } + } + + fn cause(&self) -> Option<&error::Error> { + match *self { + Error::HttpError(ref err) => err.cause(), + Error::JsonDecodeError(_, ref err) => err.cause(), + _ => None + } + } +} + +/// A universal result type used as return for all calls. +pub type Result = std::result::Result; + +/// 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 + 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 following macro invocation needs to be expanded, as `include!` +// doens't support external macros +// header!{ +// #[doc="The `X-Upload-Content-Type` header."] +// (XUploadContentType, "X-Upload-Content-Type") => [Mime] + +// xupload_content_type { +// test_header!( +// test1, +// vec![b"text/plain"], +// Some(HeaderField( +// vec![Mime(TopLevel::Text, SubLevel::Plain, Vec::new())] +// ))); + +// } +// } + +/// The `X-Upload-Content-Type` header. +/// +/// Generated via rustc --pretty expanded -Z unstable-options, and manually +/// processed to be more readable. +#[derive(PartialEq, Debug, Clone)] +pub struct XUploadContentType(pub Mime); + +impl ::std::ops::Deref for XUploadContentType { + type Target = Mime; + fn deref<'a>(&'a self) -> &'a Mime { &self.0 } +} +impl ::std::ops::DerefMut for XUploadContentType { + fn deref_mut<'a>(&'a mut self) -> &'a mut Mime { &mut self.0 } +} +impl Header for XUploadContentType { + fn header_name() -> &'static str { "X-Upload-Content-Type" } + fn parse_header(raw: &[Vec]) -> hyper::error::Result { + hyper::header::parsing::from_one_raw_str(raw).map(XUploadContentType) + } +} +impl HeaderFormat for XUploadContentType { + fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { + Display::fmt(&**self, f) + } +} +impl Display for XUploadContentType { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Display::fmt(&**self, f) + } +} + +#[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]) -> hyper::error::Result { + Err(hyper::error::Error::Method) + } +} + + +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]) -> hyper::error::Result { + if raw.len() > 0 { + let v = &raw[0]; + if let Ok(s) = std::str::from_utf8(v) { + const PREFIX: &'static str = "bytes "; + if s.starts_with(PREFIX) { + if let Ok(c) = ::from_str(&s[PREFIX.len()..]) { + return Ok(RangeResponseHeader(c)) + } + } + } + } + Err(hyper::error::Error::Method) + } +} + +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, 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, A> ResumableUploadHelper<'a, A> + where A: oauth2::GetToken { + + fn query_transfer_status(&mut self) -> std::result::Result> { + 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, None) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + return Err(Ok(r)) + } + }; + return Ok(h.0.last) + } + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + return Err(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() { + Ok(s) => s, + Err(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 + }; + + self.reader.seek(SeekFrom::Start(start)).unwrap(); + loop { + let request_size = match self.content_length - start { + rs if rs > chunk_size => chunk_size, + rs => rs + }; + + 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 + } + // workaround https://github.com/rust-lang/rust/issues/22252 + let res = 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(); + match res { + 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, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + } + return Some(Ok(res)) + }, + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + return Some(Err(err)) + } + } + } + } +} + +// Copy of src/rust/cli/cmn.rs +// TODO(ST): Allow sharing common code between program types +pub fn remove_json_null_values(value: &mut json::value::Value) { + match *value { + json::value::Value::Object(ref mut map) => { + let mut for_removal = Vec::new(); + + for (key, mut value) in map.iter_mut() { + if value.is_null() { + for_removal.push(key.clone()); + } else { + remove_json_null_values(&mut value); + } + } + + for key in &for_removal { + map.remove(key); + } + } + _ => {} + } +} diff --git a/gen/container1/src/lib.rs b/gen/container1/src/lib.rs new file mode 100644 index 0000000000..5735fcc814 --- /dev/null +++ b/gen/container1/src/lib.rs @@ -0,0 +1,186 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/api/lib.rs.mako' +// DO NOT EDIT ! + +//! This documentation was generated from *container* crate version *0.1.9+20150603*, where *20150603* is the exact revision of the *container:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +//! +//! Everything else about the *container* *v1* API can be found at the +//! [official documentation site](https://cloud.google.com/container-engine/). +//! The original source code is [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/container1). +//! # Features +//! +//! Handle the following *Resources* with ease from the central [hub](struct.Container.html) ... +//! +//! * projects +//! * [*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 clusters update*](struct.ProjectZoneClusterUpdateCall.html), [*zones get serverconfig*](struct.ProjectZoneGetServerconfigCall.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* +//! * creates [*Method Builders*](trait.MethodsBuilder.html) which in turn +//! allow access to individual [*Call Builders*](trait.CallBuilder.html) +//! * **[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* +//! +//! All *structures* are marked with applicable traits to further categorize them and ease browsing. +//! +//! Generally speaking, you can invoke *Activities* like this: +//! +//! ```Rust,ignore +//! let r = hub.resource().activity(...).doit() +//! ``` +//! +//! Or specifically ... +//! +//! ```ignore +//! let r = hub.projects().zones_clusters_update(...).doit() +//! 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 = "*" +//! ``` +//! +//! ## A complete example +//! +//! ```test_harness,no_run +//! extern crate hyper; +//! extern crate yup_oauth2 as oauth2; +//! extern crate google_container1 as container1; +//! use container1::UpdateClusterRequest; +//! use container1::{Result, Error}; +//! # #[test] fn egal() { +//! use std::default::Default; +//! use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +//! use container1::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); +//! // As the method needs a request, you would usually fill it with the desired information +//! // into the respective structure. Some of the parts shown here might not be applicable ! +//! // Values shown here are possibly random and not representative ! +//! let mut req = UpdateClusterRequest::default(); +//! +//! // You can configure optional parameters by calling 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_update(req, "projectId", "zone", "clusterId") +//! .doit(); +//! +//! match result { +//! Err(e) => match e { +//! // The Error enum provides details about what exactly happened. +//! // You can also just use its `Debug`, `Display` or `Error` traits +//! Error::HttpError(_) +//! |Error::MissingAPIKey +//! |Error::MissingToken(_) +//! |Error::Cancelled +//! |Error::UploadSizeLimitExceeded(_, _) +//! |Error::Failure(_) +//! |Error::BadRequest(_) +//! |Error::FieldClash(_) +//! |Error::JsonDecodeError(_, _) => println!("{}", e), +//! }, +//! Ok(res) => println!("Success: {:?}", res), +//! } +//! # } +//! ``` +//! ## 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 Downloads +//! 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 identifiable 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 moved +//! +//! 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 +//! +//! + +// 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)] + +include!(concat!(env!("OUT_DIR"), "/lib.rs")); \ No newline at end of file diff --git a/gen/container1/src/lib.rs.in b/gen/container1/src/lib.rs.in new file mode 100644 index 0000000000..3ccba60d6c --- /dev/null +++ b/gen/container1/src/lib.rs.in @@ -0,0 +1,2777 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/api/lib.rs.in.mako' +// DO NOT EDIT ! + +extern crate hyper; +extern crate serde; +extern crate serde_json; +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 serde_json as json; +use std::io; +use std::fs; +use std::thread::sleep_ms; + +pub use cmn::{MultiPartReader, ToParts, MethodInfo, Result, Error, CallBuilder, Hub, ReadSeek, Part, + ResponseResult, RequestValue, NestedType, Delegate, DefaultDelegate, MethodsBuilder, + Resource, ErrorResponse, remove_json_null_values}; + + +// ############## +// 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 AsRef for Scope { + fn as_ref(&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 as container1; +/// use container1::UpdateClusterRequest; +/// use container1::{Result, Error}; +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use container1::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); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req = UpdateClusterRequest::default(); +/// +/// // You can configure optional parameters by calling 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_update(req, "projectId", "zone", "clusterId") +/// .doit(); +/// +/// match result { +/// Err(e) => match e { +/// // The Error enum provides details about what exactly happened. +/// // You can also just use its `Debug`, `Display` or `Error` traits +/// Error::HttpError(_) +/// |Error::MissingAPIKey +/// |Error::MissingToken(_) +/// |Error::Cancelled +/// |Error::UploadSizeLimitExceeded(_, _) +/// |Error::Failure(_) +/// |Error::BadRequest(_) +/// |Error::FieldClash(_) +/// |Error::JsonDecodeError(_, _) => println!("{}", e), +/// }, +/// Ok(res) => println!("Success: {:?}", res), +/// } +/// # } +/// ``` +pub struct Container { + client: RefCell, + auth: RefCell, + _user_agent: String, +} + +impl<'a, C, A> Hub for Container {} + +impl<'a, C, A> Container + where 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.9".to_string(), + } + } + + pub fn projects(&'a self) -> ProjectMethods<'a, C, 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.9`. + /// + /// 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 ### +// ########## +/// ClusterUpdate describes an update to the cluster. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ClusterUpdate { + /// The Kubernetes version to change the nodes to (typically an upgrade). Use "-" to upgrade to the latest version supported by the server. + #[serde(rename="desiredNodeVersion")] + pub desired_node_version: Option, +} + +impl Part for ClusterUpdate {} + + +/// CreateClusterRequest creates a cluster. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where 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, Deserialize)] +pub struct CreateClusterRequest { + /// A [cluster resource](/container-engine/reference/rest/v1/projects.zones.clusters) + pub cluster: Option, +} + +impl RequestValue for CreateClusterRequest {} + + +/// UpdateClusterRequest updates a cluster. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where 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 update projects](struct.ProjectZoneClusterUpdateCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct UpdateClusterRequest { + /// A description of the update. + pub update: Option, +} + +impl RequestValue for UpdateClusterRequest {} + + +/// ListClustersResponse is the result of ListClustersRequest. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where 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, Serialize, Deserialize)] +pub struct ListClustersResponse { + /// A list of clusters in the project in the specified zone, or across all ones. + pub clusters: Option>, +} + +impl ResponseResult for ListClustersResponse {} + + +/// The authentication information for accessing the master endpoint. Authentication can be done using HTTP basic auth or using client certificates. +/// +/// 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 username to use for HTTP basic authentication when accessing the Kubernetes master endpoint. + pub username: Option, + /// The password to use for HTTP basic authentication when accessing the Kubernetes master endpoint. Because the master endpoint is open to the internet, you should create a strong password. + pub password: Option, + /// [Output only] Base64 encoded private key used by clients to authenticate to the cluster endpoint. + #[serde(rename="clientKey")] + pub client_key: Option, + /// [Output only] Base64 encoded public certificate used by clients to authenticate to the cluster endpoint. + #[serde(rename="clientCertificate")] + pub client_certificate: Option, + /// [Output only] Base64 encoded public certificate that is the root of trust for the cluster. + #[serde(rename="clusterCaCertificate")] + pub cluster_ca_certificate: Option, +} + +impl Part for MasterAuth {} + + +/// Container Engine Server 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*). +/// +/// * [zones get serverconfig projects](struct.ProjectZoneGetServerconfigCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ServerConfig { + /// What version this server deploys by default. + #[serde(rename="defaultClusterVersion")] + pub default_cluster_version: Option, + /// List of valid node upgrade target versions. + #[serde(rename="validNodeVersions")] + pub valid_node_versions: Option>, +} + +impl ResponseResult for ServerConfig {} + + +/// A Google Container Engine cluster. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where 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: Option, + /// [Output only] The size of the address space on each node for hosting containers. This is provisioned from within the container_ipv4_cidr range. + #[serde(rename="nodeIpv4CidrSize")] + pub node_ipv4_cidr_size: Option, + /// An optional description of this cluster. + pub description: Option, + /// [Output only] The current version of the node software components. If they are currently at different versions because they're in the process of being upgraded, this reflects the minimum version of any of them. + #[serde(rename="currentNodeVersion")] + pub current_node_version: Option, + /// [Output only] The current software version of the master endpoint. + #[serde(rename="currentMasterVersion")] + pub current_master_version: Option, + /// The authentication information for accessing the master. + #[serde(rename="masterAuth")] + pub master_auth: Option, + /// The number of nodes to create in this cluster. You must ensure that your Compute Engine [resource quota](/compute/docs/resource-quotas) is sufficient for this number of instances. You must also have available firewall and routes quota. + #[serde(rename="initialNodeCount")] + pub initial_node_count: Option, + /// The monitoring service that the cluster should write metrics to. Currently available options: * "monitoring.googleapis.com" - the Google Cloud Monitoring service * "none" - no metrics will be exported from the cluster * "" - default value; the default is "monitoring.googleapis.com" + #[serde(rename="monitoringService")] + pub monitoring_service: Option, + /// [Output only] The time the cluster was created, in [RFC3339](https://www.ietf.org/rfc/rfc3339.txt) text format. + #[serde(rename="createTime")] + pub create_time: Option, + /// The name of the Google Compute Engine [network](/compute/docs/networking#networks_1) to which the cluster is connected. If left unspecified, the "default" network will be used. + pub network: Option, + /// [Output only] The IP address of this cluster's Kubernetes master endpoint. 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: Option, + /// 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: Option, + /// The logging service that the cluster should write logs to. Currently available options: * "logging.googleapis.com" - the Google Cloud Logging service * "none" - no logs will be exported from the cluster * "" - default value; the default is "logging.googleapis.com" + #[serde(rename="loggingService")] + pub logging_service: Option, + /// [Output only] The resource URLs of [instance groups](/compute/docs/instance-groups/) associated with this cluster. + #[serde(rename="instanceGroupUrls")] + pub instance_group_urls: Option>, + /// [Output only] The software version of Kubernetes master and kubelets used in the cluster when it was first created. The version can be upgraded over time. + #[serde(rename="initialClusterVersion")] + pub initial_cluster_version: Option, + /// Parameters used in creating the cluster's nodes. See the descriptions of the child properties of `nodeConfig`. If unspecified, the defaults for all child properties are used. + #[serde(rename="nodeConfig")] + pub node_config: Option, + /// [Output only] Server-defined URL for the resource. + #[serde(rename="selfLink")] + pub self_link: Option, + /// The IP address range of the container pods in this cluster, in [CIDR](http://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing) notation (e.g. `10.96.0.0/14`). Leave blank to have one automatically chosen or specify a `/14` block in `10.0.0.0/8`. + #[serde(rename="clusterIpv4Cidr")] + pub cluster_ipv4_cidr: Option, + /// [Output only] The name of the Google Compute Engine [zone](/compute/docs/zones#available) in which the cluster resides. + pub zone: Option, + /// [Output only] Additional information about the current status of this cluster, if available. + #[serde(rename="statusMessage")] + pub status_message: Option, + /// [Output only] The IP address range of the Kubernetes services in this cluster, in [CIDR](http://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing) notation (e.g. `1.2.3.4/29`). Service addresses are typically put in the last /16 from the container CIDR. + #[serde(rename="servicesIpv4Cidr")] + pub services_ipv4_cidr: Option, +} + +impl ResponseResult for Cluster {} + + +/// Per-node parameters. +/// +/// 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 { + /// Size of the disk attached to each node, specified in GB. The smallest allowed disk size is 10GB. If unspecified, the default disk size is 100GB. + #[serde(rename="diskSizeGb")] + pub disk_size_gb: Option, + /// The name of a Google Compute Engine [machine type](/compute/docs/machine-types) (e.g. `n1-standard-1`). If unspecified, the default machine type is `n1-standard-1`. + #[serde(rename="machineType")] + pub machine_type: Option, + /// The set of Google API scopes to be made available on all of the node VMs under the "default" service account. The following scopes are recommended, but not required, and by default are not included: * `https://www.googleapis.com/auth/compute` is required for mounting persistent storage on your nodes. * `https://www.googleapis.com/auth/devstorage.read_only` is required for communicating with *gcr.io*. If unspecified, no scopes are added. + #[serde(rename="oauthScopes")] + pub oauth_scopes: Option>, +} + +impl Part for NodeConfig {} + + +/// 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 clusters update projects](struct.ProjectZoneClusterUpdateCall.html) (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, Serialize, Deserialize)] +pub struct Operation { + /// The current status of the operation. + pub status: Option, + /// The operation type. + #[serde(rename="operationType")] + pub operation_type: Option, + /// The server-assigned ID for the operation. + pub name: Option, + /// The name of the Google Compute Engine [zone](/compute/docs/zones#available) in which the operation is taking place. + pub zone: Option, + /// If an error has occurred, a textual description of the error. + #[serde(rename="statusMessage")] + pub status_message: Option, + /// Server-defined URL for the resource. + #[serde(rename="selfLink")] + pub self_link: Option, + /// Server-defined URL for the target of the operation. + #[serde(rename="targetLink")] + pub target_link: Option, +} + +impl ResponseResult for Operation {} + + +/// ListOperationsResponse is the result of ListOperationsRequest. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where 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, Serialize, Deserialize)] +pub struct ListOperationsResponse { + /// A list of operations in the project in the specified zone. + pub operations: Option>, +} + +impl ResponseResult for ListOperationsResponse {} + + + +// ################### +// 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 as container1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use container1::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 `zones_clusters_create(...)`, `zones_clusters_delete(...)`, `zones_clusters_get(...)`, `zones_clusters_list(...)`, `zones_clusters_update(...)`, `zones_get_serverconfig(...)`, `zones_operations_get(...)` and `zones_operations_list(...)` +/// // to build up your call. +/// let rb = hub.projects(); +/// # } +/// ``` +pub struct ProjectMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Container, +} + +impl<'a, C, A> MethodsBuilder for ProjectMethods<'a, C, A> {} + +impl<'a, C, A> ProjectMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Gets a specific cluster. + /// + /// # Arguments + /// + /// * `projectId` - The Google Developers Console [project ID or project number](https://developers.google.com/console/help/new/#projectnumber). + /// * `zone` - The name of the Google Compute Engine [zone](/compute/docs/zones#available) in which the cluster resides. + /// * `clusterId` - The name of the cluster to retrieve. + pub fn zones_clusters_get(&self, project_id: &str, zone: &str, cluster_id: &str) -> ProjectZoneClusterGetCall<'a, C, A> { + ProjectZoneClusterGetCall { + hub: self.hub, + _project_id: project_id.to_string(), + _zone: zone.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: + /// + /// Returns configuration info about the Container Engine service. + /// + /// # Arguments + /// + /// * `projectId` - The Google Developers Console [project ID or project number](https://developers.google.com/console/help/new/#projectnumber). + /// * `zone` - The name of the Google Compute Engine [zone](/compute/docs/zones#available) to return operations for, or "-" for all zones. + pub fn zones_get_serverconfig(&self, project_id: &str, zone: &str) -> ProjectZoneGetServerconfigCall<'a, C, A> { + ProjectZoneGetServerconfigCall { + hub: self.hub, + _project_id: project_id.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: + /// + /// Deletes the cluster, including the Kubernetes endpoint and all worker nodes. Firewalls and routes that were configured during cluster creation are also deleted. + /// + /// # Arguments + /// + /// * `projectId` - The Google Developers Console [project ID or project number](https://developers.google.com/console/help/new/#projectnumber). + /// * `zone` - The name of the Google Compute Engine [zone](/compute/docs/zones#available) in which the cluster resides. + /// * `clusterId` - The name of the cluster to delete. + pub fn zones_clusters_delete(&self, project_id: &str, zone: &str, cluster_id: &str) -> ProjectZoneClusterDeleteCall<'a, C, A> { + ProjectZoneClusterDeleteCall { + hub: self.hub, + _project_id: project_id.to_string(), + _zone: zone.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 in either the specified zone or all zones. + /// + /// # Arguments + /// + /// * `projectId` - The Google Developers Console [project ID or project number](https://developers.google.com/console/help/new/#projectnumber). + /// * `zone` - The name of the Google Compute Engine [zone](/compute/docs/zones#available) in which the cluster resides, or "-" for all zones. + pub fn zones_clusters_list(&self, project_id: &str, zone: &str) -> ProjectZoneClusterListCall<'a, C, A> { + ProjectZoneClusterListCall { + hub: self.hub, + _project_id: project_id.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: + /// + /// Lists all operations in a project in a specific zone or all zones. + /// + /// # Arguments + /// + /// * `projectId` - The Google Developers Console [project ID or project number](https://developers.google.com/console/help/new/#projectnumber). + /// * `zone` - The name of the Google Compute Engine [zone](/compute/docs/zones#available) to return operations for, or "-" for all zones. + pub fn zones_operations_list(&self, project_id: &str, zone: &str) -> ProjectZoneOperationListCall<'a, C, A> { + ProjectZoneOperationListCall { + hub: self.hub, + _project_id: project_id.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: + /// + /// Creates a cluster, consisting of the specified number and type of Google Compute Engine instances, plus a Kubernetes master endpoint. By default, the cluster is created in the project's [default network](/compute/docs/networking#networks_1). One firewall is added for the cluster. After cluster creation, the cluster creates routes for each node to allow the containers on that node to communicate with all other instances in the cluster. Finally, an entry is added to the project's global metadata indicating which CIDR range is being used by the cluster. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `projectId` - The Google Developers Console [project ID or project number](https://developers.google.com/console/help/new/#projectnumber). + /// * `zone` - The name of the Google Compute Engine [zone](/compute/docs/zones#available) in which the cluster resides. + pub fn zones_clusters_create(&self, request: CreateClusterRequest, project_id: &str, zone: &str) -> ProjectZoneClusterCreateCall<'a, C, A> { + ProjectZoneClusterCreateCall { + hub: self.hub, + _request: request, + _project_id: project_id.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: + /// + /// Update settings of a specific cluster. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `projectId` - The Google Developers Console [project ID or project number](https://developers.google.com/console/help/new/#projectnumber). + /// * `zone` - The name of the Google Compute Engine [zone](/compute/docs/zones#available) in which the cluster resides. + /// * `clusterId` - The name of the cluster to upgrade. + pub fn zones_clusters_update(&self, request: UpdateClusterRequest, project_id: &str, zone: &str, cluster_id: &str) -> ProjectZoneClusterUpdateCall<'a, C, A> { + ProjectZoneClusterUpdateCall { + hub: self.hub, + _request: request, + _project_id: project_id.to_string(), + _zone: zone.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: + /// + /// Gets the specified operation. + /// + /// # Arguments + /// + /// * `projectId` - The Google Developers Console [project ID or project number](https://developers.google.com/console/help/new/#projectnumber). + /// * `zone` - The name of the Google Compute Engine [zone](/compute/docs/zones#available) in which the cluster resides. + /// * `operationId` - The server-assigned `name` of the operation. + pub fn zones_operations_get(&self, project_id: &str, zone: &str, operation_id: &str) -> ProjectZoneOperationGetCall<'a, C, A> { + ProjectZoneOperationGetCall { + hub: self.hub, + _project_id: project_id.to_string(), + _zone: zone.to_string(), + _operation_id: operation_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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_container1 as container1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use container1::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", "zone", "clusterId") +/// .doit(); +/// # } +/// ``` +pub struct ProjectZoneClusterGetCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Container, + _project_id: String, + _zone: String, + _cluster_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ProjectZoneClusterGetCall<'a, C, A> {} + +impl<'a, C, A> ProjectZoneClusterGetCall<'a, C, A> where 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(("zone", self._zone.to_string())); + params.push(("clusterId", self._cluster_id.to_string())); + for &field in ["alt", "projectId", "zone", "clusterId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://container.googleapis.com/v1/projects/{projectId}/zones/{zone}/clusters/{clusterId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{projectId}", "projectId"), ("{zone}", "zone"), ("{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 ["clusterId", "zone", "projectId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The Google Developers Console [project ID or project number](https://developers.google.com/console/help/new/#projectnumber). + /// + /// 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. + pub fn project_id(mut self, new_value: &str) -> ProjectZoneClusterGetCall<'a, C, A> { + self._project_id = new_value.to_string(); + self + } + /// The name of the Google Compute Engine [zone](/compute/docs/zones#available) in which the cluster resides. + /// + /// 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) -> ProjectZoneClusterGetCall<'a, C, A> { + self._zone = new_value.to_string(); + self + } + /// The name of the cluster to retrieve. + /// + /// 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. + pub fn cluster_id(mut self, new_value: &str) -> ProjectZoneClusterGetCall<'a, C, A> { + self._cluster_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectZoneClusterGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> ProjectZoneClusterGetCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Returns configuration info about the Container Engine service. +/// +/// A builder for the *zones.getServerconfig* method supported by a *project* resource. +/// It is not used directly, but through a `ProjectMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_container1 as container1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use container1::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_get_serverconfig("projectId", "zone") +/// .doit(); +/// # } +/// ``` +pub struct ProjectZoneGetServerconfigCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Container, + _project_id: String, + _zone: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ProjectZoneGetServerconfigCall<'a, C, A> {} + +impl<'a, C, A> ProjectZoneGetServerconfigCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ServerConfig)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.getServerconfig", + 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(("zone", self._zone.to_string())); + for &field in ["alt", "projectId", "zone"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://container.googleapis.com/v1/projects/{projectId}/zones/{zone}/serverconfig".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{projectId}", "projectId"), ("{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 ["zone", "projectId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The Google Developers Console [project ID or project number](https://developers.google.com/console/help/new/#projectnumber). + /// + /// 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. + pub fn project_id(mut self, new_value: &str) -> ProjectZoneGetServerconfigCall<'a, C, A> { + self._project_id = new_value.to_string(); + self + } + /// The name of the Google Compute Engine [zone](/compute/docs/zones#available) to return operations for, or "-" for all zones. + /// + /// 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) -> ProjectZoneGetServerconfigCall<'a, C, A> { + self._zone = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectZoneGetServerconfigCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> ProjectZoneGetServerconfigCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProjectZoneGetServerconfigCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Deletes the cluster, including the Kubernetes endpoint and all worker nodes. Firewalls and routes that were configured during 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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_container1 as container1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use container1::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", "zone", "clusterId") +/// .doit(); +/// # } +/// ``` +pub struct ProjectZoneClusterDeleteCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Container, + _project_id: String, + _zone: String, + _cluster_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ProjectZoneClusterDeleteCall<'a, C, A> {} + +impl<'a, C, A> ProjectZoneClusterDeleteCall<'a, C, A> where 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(("zone", self._zone.to_string())); + params.push(("clusterId", self._cluster_id.to_string())); + for &field in ["alt", "projectId", "zone", "clusterId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://container.googleapis.com/v1/projects/{projectId}/zones/{zone}/clusters/{clusterId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{projectId}", "projectId"), ("{zone}", "zone"), ("{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 ["clusterId", "zone", "projectId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The Google Developers Console [project ID or project number](https://developers.google.com/console/help/new/#projectnumber). + /// + /// 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. + pub fn project_id(mut self, new_value: &str) -> ProjectZoneClusterDeleteCall<'a, C, A> { + self._project_id = new_value.to_string(); + self + } + /// The name of the Google Compute Engine [zone](/compute/docs/zones#available) in which the cluster resides. + /// + /// 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) -> ProjectZoneClusterDeleteCall<'a, C, A> { + self._zone = new_value.to_string(); + self + } + /// The name of the cluster to delete. + /// + /// 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. + pub fn cluster_id(mut self, new_value: &str) -> ProjectZoneClusterDeleteCall<'a, C, A> { + self._cluster_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectZoneClusterDeleteCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> ProjectZoneClusterDeleteCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Lists all clusters owned by a project in either the specified zone or all zones. +/// +/// A builder for the *zones.clusters.list* method supported by a *project* resource. +/// It is not used directly, but through a `ProjectMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_container1 as container1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use container1::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", "zone") +/// .doit(); +/// # } +/// ``` +pub struct ProjectZoneClusterListCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Container, + _project_id: String, + _zone: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ProjectZoneClusterListCall<'a, C, A> {} + +impl<'a, C, A> ProjectZoneClusterListCall<'a, C, A> where 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(("zone", self._zone.to_string())); + for &field in ["alt", "projectId", "zone"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://container.googleapis.com/v1/projects/{projectId}/zones/{zone}/clusters".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{projectId}", "projectId"), ("{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 ["zone", "projectId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The Google Developers Console [project ID or project number](https://developers.google.com/console/help/new/#projectnumber). + /// + /// 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. + pub fn project_id(mut self, new_value: &str) -> ProjectZoneClusterListCall<'a, C, A> { + self._project_id = new_value.to_string(); + self + } + /// The name of the Google Compute Engine [zone](/compute/docs/zones#available) in which the cluster resides, or "-" for all zones. + /// + /// 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) -> ProjectZoneClusterListCall<'a, C, A> { + self._zone = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectZoneClusterListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> ProjectZoneClusterListCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Lists all operations in a project in a specific zone or all zones. +/// +/// A builder for the *zones.operations.list* method supported by a *project* resource. +/// It is not used directly, but through a `ProjectMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_container1 as container1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use container1::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", "zone") +/// .doit(); +/// # } +/// ``` +pub struct ProjectZoneOperationListCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Container, + _project_id: String, + _zone: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ProjectZoneOperationListCall<'a, C, A> {} + +impl<'a, C, A> ProjectZoneOperationListCall<'a, C, A> where 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(("zone", self._zone.to_string())); + for &field in ["alt", "projectId", "zone"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://container.googleapis.com/v1/projects/{projectId}/zones/{zone}/operations".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{projectId}", "projectId"), ("{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 ["zone", "projectId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The Google Developers Console [project ID or project number](https://developers.google.com/console/help/new/#projectnumber). + /// + /// 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. + pub fn project_id(mut self, new_value: &str) -> ProjectZoneOperationListCall<'a, C, A> { + self._project_id = new_value.to_string(); + self + } + /// The name of the Google Compute Engine [zone](/compute/docs/zones#available) to return operations for, or "-" for all zones. + /// + /// 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) -> ProjectZoneOperationListCall<'a, C, A> { + self._zone = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectZoneOperationListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> ProjectZoneOperationListCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Creates a cluster, consisting of the specified number and type of Google Compute Engine instances, plus a Kubernetes master endpoint. By default, the cluster is created in the project's [default network](/compute/docs/networking#networks_1). One firewall is added for the cluster. After cluster creation, the cluster creates routes for each node to allow the containers on that node to communicate with all other instances in the cluster. Finally, an entry is added to the project's global metadata indicating which CIDR range is being used by the cluster. +/// +/// A builder for the *zones.clusters.create* method supported by a *project* resource. +/// It is not used directly, but through a `ProjectMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_container1 as container1; +/// use container1::CreateClusterRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use container1::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(); +/// +/// // You can configure optional parameters by calling 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", "zone") +/// .doit(); +/// # } +/// ``` +pub struct ProjectZoneClusterCreateCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Container, + _request: CreateClusterRequest, + _project_id: String, + _zone: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ProjectZoneClusterCreateCall<'a, C, A> {} + +impl<'a, C, A> ProjectZoneClusterCreateCall<'a, C, A> where 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(("zone", self._zone.to_string())); + for &field in ["alt", "projectId", "zone"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://container.googleapis.com/v1/projects/{projectId}/zones/{zone}/clusters".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{projectId}", "projectId"), ("{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 ["zone", "projectId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// The Google Developers Console [project ID or project number](https://developers.google.com/console/help/new/#projectnumber). + /// + /// 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. + pub fn project_id(mut self, new_value: &str) -> ProjectZoneClusterCreateCall<'a, C, A> { + self._project_id = new_value.to_string(); + self + } + /// The name of the Google Compute Engine [zone](/compute/docs/zones#available) in which the cluster resides. + /// + /// 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) -> ProjectZoneClusterCreateCall<'a, C, A> { + self._zone = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectZoneClusterCreateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> ProjectZoneClusterCreateCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Update settings of a specific cluster. +/// +/// A builder for the *zones.clusters.update* method supported by a *project* resource. +/// It is not used directly, but through a `ProjectMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_container1 as container1; +/// use container1::UpdateClusterRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use container1::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 = UpdateClusterRequest::default(); +/// +/// // You can configure optional parameters by calling 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_update(req, "projectId", "zone", "clusterId") +/// .doit(); +/// # } +/// ``` +pub struct ProjectZoneClusterUpdateCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Container, + _request: UpdateClusterRequest, + _project_id: String, + _zone: String, + _cluster_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ProjectZoneClusterUpdateCall<'a, C, A> {} + +impl<'a, C, A> ProjectZoneClusterUpdateCall<'a, C, A> where 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.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(("zone", self._zone.to_string())); + params.push(("clusterId", self._cluster_id.to_string())); + for &field in ["alt", "projectId", "zone", "clusterId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://container.googleapis.com/v1/projects/{projectId}/zones/{zone}/clusters/{clusterId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{projectId}", "projectId"), ("{zone}", "zone"), ("{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 ["clusterId", "zone", "projectId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: UpdateClusterRequest) -> ProjectZoneClusterUpdateCall<'a, C, A> { + self._request = new_value; + self + } + /// The Google Developers Console [project ID or project number](https://developers.google.com/console/help/new/#projectnumber). + /// + /// 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. + pub fn project_id(mut self, new_value: &str) -> ProjectZoneClusterUpdateCall<'a, C, A> { + self._project_id = new_value.to_string(); + self + } + /// The name of the Google Compute Engine [zone](/compute/docs/zones#available) in which the cluster resides. + /// + /// 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) -> ProjectZoneClusterUpdateCall<'a, C, A> { + self._zone = new_value.to_string(); + self + } + /// The name of the cluster to upgrade. + /// + /// 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. + pub fn cluster_id(mut self, new_value: &str) -> ProjectZoneClusterUpdateCall<'a, C, A> { + self._cluster_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectZoneClusterUpdateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> ProjectZoneClusterUpdateCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProjectZoneClusterUpdateCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_container1 as container1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use container1::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", "zone", "operationId") +/// .doit(); +/// # } +/// ``` +pub struct ProjectZoneOperationGetCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Container, + _project_id: String, + _zone: String, + _operation_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ProjectZoneOperationGetCall<'a, C, A> {} + +impl<'a, C, A> ProjectZoneOperationGetCall<'a, C, A> where 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(("zone", self._zone.to_string())); + params.push(("operationId", self._operation_id.to_string())); + for &field in ["alt", "projectId", "zone", "operationId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://container.googleapis.com/v1/projects/{projectId}/zones/{zone}/operations/{operationId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{projectId}", "projectId"), ("{zone}", "zone"), ("{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 ["operationId", "zone", "projectId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The Google Developers Console [project ID or project number](https://developers.google.com/console/help/new/#projectnumber). + /// + /// 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. + pub fn project_id(mut self, new_value: &str) -> ProjectZoneOperationGetCall<'a, C, A> { + self._project_id = new_value.to_string(); + self + } + /// The name of the Google Compute Engine [zone](/compute/docs/zones#available) in which the cluster resides. + /// + /// 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) -> ProjectZoneOperationGetCall<'a, C, A> { + self._zone = new_value.to_string(); + self + } + /// The server-assigned `name` of the operation. + /// + /// 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. + pub fn operation_id(mut self, new_value: &str) -> ProjectZoneOperationGetCall<'a, C, A> { + self._operation_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectZoneOperationGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> ProjectZoneOperationGetCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + diff --git a/gen/container1_beta1-cli/Cargo.toml b/gen/container1_beta1-cli/Cargo.toml index fc044a393b..a1e6dac3a7 100644 --- a/gen/container1_beta1-cli/Cargo.toml +++ b/gen/container1_beta1-cli/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-container1_beta1-cli" -version = "0.3.2+20150713" +version = "0.3.2+20151005" 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-cli" diff --git a/gen/container1_beta1-cli/README.md b/gen/container1_beta1-cli/README.md index 937c71ead6..2f14031339 100644 --- a/gen/container1_beta1-cli/README.md +++ b/gen/container1_beta1-cli/README.md @@ -24,7 +24,7 @@ Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/ma # Usage -This documentation was generated from the *container* API at revision *20150713*. The CLI is at version *0.3.2*. +This documentation was generated from the *container* API at revision *20151005*. The CLI is at version *0.3.2*. ```bash container1-beta1 [options] diff --git a/gen/container1_beta1-cli/mkdocs.yml b/gen/container1_beta1-cli/mkdocs.yml index a774fe9e89..5b14e25879 100644 --- a/gen/container1_beta1-cli/mkdocs.yml +++ b/gen/container1_beta1-cli/mkdocs.yml @@ -1,4 +1,4 @@ -site_name: container v0.3.2+20150713 +site_name: container v0.3.2+20151005 site_url: http://byron.github.io/google-apis-rs/google-container1_beta1-cli site_description: Write integrating applications with bcore diff --git a/gen/container1_beta1-cli/src/main.rs b/gen/container1_beta1-cli/src/main.rs index 3a49f8fb7d..caaee9cddf 100644 --- a/gen/container1_beta1-cli/src/main.rs +++ b/gen/container1_beta1-cli/src/main.rs @@ -888,7 +888,7 @@ fn main() { let mut app = App::new("container1-beta1") .author("Sebastian Thiel ") - .version("0.3.2+20150713") + .version("0.3.2+20151005") .about("The Google Container Engine API is used for building and managing container based applications, powered by the open source Kubernetes technology.") .after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_container1_beta1_cli") .arg(Arg::with_name("url") diff --git a/gen/container1_beta1/Cargo.toml b/gen/container1_beta1/Cargo.toml index bc7d13f14a..455adcec97 100644 --- a/gen/container1_beta1/Cargo.toml +++ b/gen/container1_beta1/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-container1_beta1" -version = "0.1.9+20150713" +version = "0.1.9+20151005" 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" diff --git a/gen/container1_beta1/README.md b/gen/container1_beta1/README.md index 3462b906be..d38086da6a 100644 --- a/gen/container1_beta1/README.md +++ b/gen/container1_beta1/README.md @@ -5,7 +5,7 @@ DO NOT EDIT ! --> 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.9+20150713*, where *20150713* is the exact revision of the *container:v1beta1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +This documentation was generated from *container* crate version *0.1.9+20151005*, where *20151005* is the exact revision of the *container:v1beta1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. Everything else about the *container* *v1_beta1* API can be found at the [official documentation site](https://cloud.google.com/container-engine/docs/v1beta1/). diff --git a/gen/container1_beta1/src/lib.rs b/gen/container1_beta1/src/lib.rs index f63399fc27..b60d308489 100644 --- a/gen/container1_beta1/src/lib.rs +++ b/gen/container1_beta1/src/lib.rs @@ -2,7 +2,7 @@ // This file was generated automatically from 'src/mako/api/lib.rs.mako' // DO NOT EDIT ! -//! This documentation was generated from *container* crate version *0.1.9+20150713*, where *20150713* is the exact revision of the *container:v1beta1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +//! This documentation was generated from *container* crate version *0.1.9+20151005*, where *20151005* is the exact revision of the *container:v1beta1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. //! //! Everything else about the *container* *v1_beta1* API can be found at the //! [official documentation site](https://cloud.google.com/container-engine/docs/v1beta1/). diff --git a/gen/container1_beta1/src/lib.rs.in b/gen/container1_beta1/src/lib.rs.in index e0d4981e12..eabdc31d7f 100644 --- a/gen/container1_beta1/src/lib.rs.in +++ b/gen/container1_beta1/src/lib.rs.in @@ -243,7 +243,7 @@ impl Part for MasterAuth {} pub struct Cluster { /// [Output only] The current status of this cluster. pub status: Option, - /// The IP address range of the container pods in this cluster, in CIDR notation (e.g. 10.96.0.0/14). Leave blank to have one automatically chosen or specify a /14 block in 10.0.0.0/8 or 172.16.0.0/12. + /// The IP address range of the container pods in this cluster, in CIDR notation (e.g. 10.96.0.0/14). Leave blank to have one automatically chosen or specify a /14 block in 10.0.0.0/8. #[serde(rename="containerIpv4Cidr")] pub container_ipv4_cidr: Option, /// An optional description of this cluster. diff --git a/gen/content2-cli/Cargo.toml b/gen/content2-cli/Cargo.toml index 6d93de1438..d9f73d4b2f 100644 --- a/gen/content2-cli/Cargo.toml +++ b/gen/content2-cli/Cargo.toml @@ -4,11 +4,11 @@ [package] name = "google-content2-cli" -version = "0.3.2+20150710" +version = "0.3.2+20151002" 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-cli" -homepage = "https://developers.google.com/shopping-content/v2/" +homepage = "https://developers.google.com/shopping-content" documentation = "http://byron.github.io/google-apis-rs/google_content2_cli" license = "MIT" keywords = ["content", "google", "cli"] diff --git a/gen/content2-cli/README.md b/gen/content2-cli/README.md index 036f83df98..068e6f6b93 100644 --- a/gen/content2-cli/README.md +++ b/gen/content2-cli/README.md @@ -11,7 +11,7 @@ capabilities. Errors will be printed to standard error, and cause the program's If data-structures are requested, these will be returned as pretty-printed JSON, to be useful as input to other tools. Everything else about the *Shopping Content* API can be found at the -[official documentation site](https://developers.google.com/shopping-content/v2/). +[official documentation site](https://developers.google.com/shopping-content). # Downloads @@ -24,7 +24,7 @@ Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/ma # Usage -This documentation was generated from the *Shopping Content* API at revision *20150710*. The CLI is at version *0.3.2*. +This documentation was generated from the *Shopping Content* API at revision *20151002*. The CLI is at version *0.3.2*. ```bash content2 [options] @@ -68,6 +68,22 @@ content2 [options] inventory custombatch (-r )... [-p ]... [-o ] set (-r )... [-p ]... [-o ] + orders + acknowledge (-r )... [-p ]... [-o ] + advancetestorder [-p ]... [-o ] + cancel (-r )... [-p ]... [-o ] + cancellineitem (-r )... [-p ]... [-o ] + createtestorder (-r )... [-p ]... [-o ] + custombatch (-r )... [-p ]... [-o ] + get [-p ]... [-o ] + getbymerchantorderid [-p ]... [-o ] + gettestordertemplate [-p ]... [-o ] + list [-p ]... [-o ] + refund (-r )... [-p ]... [-o ] + returnlineitem (-r )... [-p ]... [-o ] + shiplineitems (-r )... [-p ]... [-o ] + updatemerchantorderid (-r )... [-p ]... [-o ] + updateshipment (-r )... [-p ]... [-o ] products custombatch (-r )... [-p ]... [-o ] delete [-p ]... diff --git a/gen/content2-cli/mkdocs.yml b/gen/content2-cli/mkdocs.yml index 92c408b1ad..27a480ccb5 100644 --- a/gen/content2-cli/mkdocs.yml +++ b/gen/content2-cli/mkdocs.yml @@ -1,4 +1,4 @@ -site_name: Shopping Content v0.3.2+20150710 +site_name: Shopping Content v0.3.2+20151002 site_url: http://byron.github.io/google-apis-rs/google-content2-cli site_description: Write integrating applications with bcore @@ -42,6 +42,21 @@ pages: - ['datafeedstatuses_list.md', 'Datafeedstatuses', 'List'] - ['inventory_custombatch.md', 'Inventory', 'Custombatch'] - ['inventory_set.md', 'Inventory', 'Set'] +- ['orders_acknowledge.md', 'Orders', 'Acknowledge'] +- ['orders_advancetestorder.md', 'Orders', 'Advancetestorder'] +- ['orders_cancel.md', 'Orders', 'Cancel'] +- ['orders_cancellineitem.md', 'Orders', 'Cancellineitem'] +- ['orders_createtestorder.md', 'Orders', 'Createtestorder'] +- ['orders_custombatch.md', 'Orders', 'Custombatch'] +- ['orders_get.md', 'Orders', 'Get'] +- ['orders_getbymerchantorderid.md', 'Orders', 'Getbymerchantorderid'] +- ['orders_gettestordertemplate.md', 'Orders', 'Gettestordertemplate'] +- ['orders_list.md', 'Orders', 'List'] +- ['orders_refund.md', 'Orders', 'Refund'] +- ['orders_returnlineitem.md', 'Orders', 'Returnlineitem'] +- ['orders_shiplineitems.md', 'Orders', 'Shiplineitems'] +- ['orders_updatemerchantorderid.md', 'Orders', 'Updatemerchantorderid'] +- ['orders_updateshipment.md', 'Orders', 'Updateshipment'] - ['products_custombatch.md', 'Products', 'Custombatch'] - ['products_delete.md', 'Products', 'Delete'] - ['products_get.md', 'Products', 'Get'] diff --git a/gen/content2-cli/src/main.rs b/gen/content2-cli/src/main.rs index 8727c0eed1..b3ac05dd53 100644 --- a/gen/content2-cli/src/main.rs +++ b/gen/content2-cli/src/main.rs @@ -2459,12 +2459,13 @@ impl<'n, 'a> Engine<'n, 'a> { "sale-price-effective-date" => Some(("salePriceEffectiveDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "price.currency" => Some(("price.currency", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "price.value" => Some(("price.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "sell-on-google-quantity" => Some(("sellOnGoogleQuantity", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), "sale-price.currency" => Some(("salePrice.currency", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "sale-price.value" => Some(("salePrice.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "availability" => Some(("availability", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "quantity" => Some(("quantity", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), _ => { - let suggestion = FieldCursor::did_you_mean(key, &vec!["availability", "currency", "price", "quantity", "sale-price", "sale-price-effective-date", "value"]); + let suggestion = FieldCursor::did_you_mean(key, &vec!["availability", "currency", "price", "quantity", "sale-price", "sale-price-effective-date", "sell-on-google-quantity", "value"]); err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); None } @@ -2528,6 +2529,1174 @@ impl<'n, 'a> Engine<'n, 'a> { } } + fn _orders_acknowledge(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "operation-id" => Some(("operationId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["operation-id"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::OrdersAcknowledgeRequest = json::value::from_value(object).unwrap(); + let mut call = self.hub.orders().acknowledge(request, opt.value_of("merchant-id").unwrap_or(""), opt.value_of("order-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _orders_advancetestorder(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.orders().advancetestorder(opt.value_of("merchant-id").unwrap_or(""), opt.value_of("order-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _orders_cancel(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "reason" => Some(("reason", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "reason-text" => Some(("reasonText", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "operation-id" => Some(("operationId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["operation-id", "reason", "reason-text"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::OrdersCancelRequest = json::value::from_value(object).unwrap(); + let mut call = self.hub.orders().cancel(request, opt.value_of("merchant-id").unwrap_or(""), opt.value_of("order-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _orders_cancellineitem(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "quantity" => Some(("quantity", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "reason" => Some(("reason", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "reason-text" => Some(("reasonText", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "line-item-id" => Some(("lineItemId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "operation-id" => Some(("operationId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["line-item-id", "operation-id", "quantity", "reason", "reason-text"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::OrdersCancelLineItemRequest = json::value::from_value(object).unwrap(); + let mut call = self.hub.orders().cancellineitem(request, opt.value_of("merchant-id").unwrap_or(""), opt.value_of("order-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _orders_createtestorder(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "test-order.customer.explicit-marketing-preference" => Some(("testOrder.customer.explicitMarketingPreference", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "test-order.customer.full-name" => Some(("testOrder.customer.fullName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "test-order.customer.email" => Some(("testOrder.customer.email", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "test-order.kind" => Some(("testOrder.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "test-order.predefined-delivery-address" => Some(("testOrder.predefinedDeliveryAddress", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "test-order.shipping-cost.currency" => Some(("testOrder.shippingCost.currency", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "test-order.shipping-cost.value" => Some(("testOrder.shippingCost.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "test-order.shipping-option" => Some(("testOrder.shippingOption", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "test-order.shipping-cost-tax.currency" => Some(("testOrder.shippingCostTax.currency", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "test-order.shipping-cost-tax.value" => Some(("testOrder.shippingCostTax.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "test-order.payment-method.expiration-month" => Some(("testOrder.paymentMethod.expirationMonth", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "test-order.payment-method.type" => Some(("testOrder.paymentMethod.type", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "test-order.payment-method.expiration-year" => Some(("testOrder.paymentMethod.expirationYear", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "test-order.payment-method.last-four-digits" => Some(("testOrder.paymentMethod.lastFourDigits", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "test-order.payment-method.predefined-billing-address" => Some(("testOrder.paymentMethod.predefinedBillingAddress", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "template-name" => Some(("templateName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["currency", "customer", "email", "expiration-month", "expiration-year", "explicit-marketing-preference", "full-name", "kind", "last-four-digits", "payment-method", "predefined-billing-address", "predefined-delivery-address", "shipping-cost", "shipping-cost-tax", "shipping-option", "template-name", "test-order", "type", "value"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::OrdersCreateTestOrderRequest = json::value::from_value(object).unwrap(); + let mut call = self.hub.orders().createtestorder(request, opt.value_of("merchant-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _orders_custombatch(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec![]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::OrdersCustomBatchRequest = json::value::from_value(object).unwrap(); + let mut call = self.hub.orders().custombatch(request); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _orders_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.orders().get(opt.value_of("merchant-id").unwrap_or(""), opt.value_of("order-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _orders_getbymerchantorderid(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.orders().getbymerchantorderid(opt.value_of("merchant-id").unwrap_or(""), opt.value_of("merchant-order-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _orders_gettestordertemplate(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.orders().gettestordertemplate(opt.value_of("merchant-id").unwrap_or(""), opt.value_of("template-name").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _orders_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.orders().list(opt.value_of("merchant-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "statuses" => { + call = call.add_statuses(value.unwrap_or("")); + }, + "placed-date-start" => { + call = call.placed_date_start(value.unwrap_or("")); + }, + "placed-date-end" => { + call = call.placed_date_end(value.unwrap_or("")); + }, + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "order-by" => { + call = call.order_by(value.unwrap_or("")); + }, + "max-results" => { + call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer")); + }, + "acknowledged" => { + call = call.acknowledged(arg_from_str(value.unwrap_or("false"), err, "acknowledged", "boolean")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["order-by", "placed-date-end", "acknowledged", "max-results", "page-token", "placed-date-start", "statuses"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _orders_refund(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "amount.currency" => Some(("amount.currency", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "amount.value" => Some(("amount.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "reason-text" => Some(("reasonText", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "reason" => Some(("reason", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "operation-id" => Some(("operationId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["amount", "currency", "operation-id", "reason", "reason-text", "value"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::OrdersRefundRequest = json::value::from_value(object).unwrap(); + let mut call = self.hub.orders().refund(request, opt.value_of("merchant-id").unwrap_or(""), opt.value_of("order-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _orders_returnlineitem(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "quantity" => Some(("quantity", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "reason" => Some(("reason", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "reason-text" => Some(("reasonText", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "line-item-id" => Some(("lineItemId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "operation-id" => Some(("operationId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["line-item-id", "operation-id", "quantity", "reason", "reason-text"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::OrdersReturnLineItemRequest = json::value::from_value(object).unwrap(); + let mut call = self.hub.orders().returnlineitem(request, opt.value_of("merchant-id").unwrap_or(""), opt.value_of("order-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _orders_shiplineitems(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "shipment-id" => Some(("shipmentId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "carrier" => Some(("carrier", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "tracking-id" => Some(("trackingId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "operation-id" => Some(("operationId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["carrier", "operation-id", "shipment-id", "tracking-id"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::OrdersShipLineItemsRequest = json::value::from_value(object).unwrap(); + let mut call = self.hub.orders().shiplineitems(request, opt.value_of("merchant-id").unwrap_or(""), opt.value_of("order-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _orders_updatemerchantorderid(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "merchant-order-id" => Some(("merchantOrderId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "operation-id" => Some(("operationId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["merchant-order-id", "operation-id"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::OrdersUpdateMerchantOrderIdRequest = json::value::from_value(object).unwrap(); + let mut call = self.hub.orders().updatemerchantorderid(request, opt.value_of("merchant-id").unwrap_or(""), opt.value_of("order-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _orders_updateshipment(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "status" => Some(("status", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "shipment-id" => Some(("shipmentId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "carrier" => Some(("carrier", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "tracking-id" => Some(("trackingId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "operation-id" => Some(("operationId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["carrier", "operation-id", "shipment-id", "status", "tracking-id"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::OrdersUpdateShipmentRequest = json::value::from_value(object).unwrap(); + let mut call = self.hub.orders().updateshipment(request, opt.value_of("merchant-id").unwrap_or(""), opt.value_of("order-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + fn _products_custombatch(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) -> Result<(), DoitError> { @@ -2781,6 +3950,7 @@ impl<'n, 'a> Engine<'n, 'a> { "availability-date" => Some(("availabilityDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "shipping-length.value" => Some(("shippingLength.value", JsonTypeInfo { jtype: JsonType::Float, ctype: ComplexType::Pod })), "shipping-length.unit" => Some(("shippingLength.unit", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "sell-on-google-quantity" => Some(("sellOnGoogleQuantity", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "link" => Some(("link", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "adult" => Some(("adult", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), "display-ads-link" => Some(("displayAdsLink", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), @@ -2814,7 +3984,7 @@ impl<'n, 'a> Engine<'n, 'a> { "age-group" => Some(("ageGroup", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "adwords-redirect" => Some(("adwordsRedirect", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), _ => { - let suggestion = FieldCursor::did_you_mean(key, &vec!["additional-image-links", "adult", "adwords-grouping", "adwords-labels", "adwords-redirect", "age-group", "amount", "availability", "availability-date", "brand", "channel", "color", "condition", "content-language", "currency", "custom-label0", "custom-label1", "custom-label2", "custom-label3", "custom-label4", "description", "display-ads-id", "display-ads-link", "display-ads-similar-ids", "display-ads-title", "display-ads-value", "energy-efficiency-class", "expiration-date", "gender", "google-product-category", "gtin", "id", "identifier-exists", "image-link", "installment", "is-bundle", "item-group-id", "kind", "link", "loyalty-points", "material", "mobile-link", "months", "mpn", "multipack", "name", "offer-id", "online-only", "pattern", "points-value", "price", "product-type", "ratio", "sale-price", "sale-price-effective-date", "shipping-height", "shipping-label", "shipping-length", "shipping-weight", "shipping-width", "size-system", "size-type", "sizes", "target-country", "title", "unit", "unit-pricing-base-measure", "unit-pricing-measure", "validated-destinations", "value"]); + let suggestion = FieldCursor::did_you_mean(key, &vec!["additional-image-links", "adult", "adwords-grouping", "adwords-labels", "adwords-redirect", "age-group", "amount", "availability", "availability-date", "brand", "channel", "color", "condition", "content-language", "currency", "custom-label0", "custom-label1", "custom-label2", "custom-label3", "custom-label4", "description", "display-ads-id", "display-ads-link", "display-ads-similar-ids", "display-ads-title", "display-ads-value", "energy-efficiency-class", "expiration-date", "gender", "google-product-category", "gtin", "id", "identifier-exists", "image-link", "installment", "is-bundle", "item-group-id", "kind", "link", "loyalty-points", "material", "mobile-link", "months", "mpn", "multipack", "name", "offer-id", "online-only", "pattern", "points-value", "price", "product-type", "ratio", "sale-price", "sale-price-effective-date", "sell-on-google-quantity", "shipping-height", "shipping-label", "shipping-length", "shipping-weight", "shipping-width", "size-system", "size-type", "sizes", "target-country", "title", "unit", "unit-pricing-base-measure", "unit-pricing-measure", "validated-destinations", "value"]); err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); None } @@ -3292,6 +4462,59 @@ impl<'n, 'a> Engine<'n, 'a> { } } }, + ("orders", Some(opt)) => { + match opt.subcommand() { + ("acknowledge", Some(opt)) => { + call_result = self._orders_acknowledge(opt, dry_run, &mut err); + }, + ("advancetestorder", Some(opt)) => { + call_result = self._orders_advancetestorder(opt, dry_run, &mut err); + }, + ("cancel", Some(opt)) => { + call_result = self._orders_cancel(opt, dry_run, &mut err); + }, + ("cancellineitem", Some(opt)) => { + call_result = self._orders_cancellineitem(opt, dry_run, &mut err); + }, + ("createtestorder", Some(opt)) => { + call_result = self._orders_createtestorder(opt, dry_run, &mut err); + }, + ("custombatch", Some(opt)) => { + call_result = self._orders_custombatch(opt, dry_run, &mut err); + }, + ("get", Some(opt)) => { + call_result = self._orders_get(opt, dry_run, &mut err); + }, + ("getbymerchantorderid", Some(opt)) => { + call_result = self._orders_getbymerchantorderid(opt, dry_run, &mut err); + }, + ("gettestordertemplate", Some(opt)) => { + call_result = self._orders_gettestordertemplate(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._orders_list(opt, dry_run, &mut err); + }, + ("refund", Some(opt)) => { + call_result = self._orders_refund(opt, dry_run, &mut err); + }, + ("returnlineitem", Some(opt)) => { + call_result = self._orders_returnlineitem(opt, dry_run, &mut err); + }, + ("shiplineitems", Some(opt)) => { + call_result = self._orders_shiplineitems(opt, dry_run, &mut err); + }, + ("updatemerchantorderid", Some(opt)) => { + call_result = self._orders_updatemerchantorderid(opt, dry_run, &mut err); + }, + ("updateshipment", Some(opt)) => { + call_result = self._orders_updateshipment(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("orders".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, ("products", Some(opt)) => { match opt.subcommand() { ("custombatch", Some(opt)) => { @@ -4254,7 +5477,7 @@ fn main() { ("inventory", "methods: 'custombatch' and 'set'", vec![ ("custombatch", - Some(r##"Updates price and availability for multiple products or stores in a single request."##), + Some(r##"Updates price and availability for multiple products or stores in a single request. This operation does not update the expiration date of the products."##), "Details at http://byron.github.io/google-apis-rs/google_content2_cli/inventory_custombatch", vec![ (Some(r##"kv"##), @@ -4276,7 +5499,7 @@ fn main() { Some(false)), ]), ("set", - Some(r##"Updates price and availability of a product in your Merchant Center account."##), + Some(r##"Updates price and availability of a product in your Merchant Center account. This operation does not update the expiration date of the product."##), "Details at http://byron.github.io/google-apis-rs/google_content2_cli/inventory_set", vec![ (Some(r##"merchant-id"##), @@ -4317,6 +5540,465 @@ fn main() { ]), ]), + ("orders", "methods: 'acknowledge', 'advancetestorder', 'cancel', 'cancellineitem', 'createtestorder', 'custombatch', 'get', 'getbymerchantorderid', 'gettestordertemplate', 'list', 'refund', 'returnlineitem', 'shiplineitems', 'updatemerchantorderid' and 'updateshipment'", vec![ + ("acknowledge", + Some(r##"Marks an order as acknowledged."##), + "Details at http://byron.github.io/google-apis-rs/google_content2_cli/orders_acknowledge", + vec![ + (Some(r##"merchant-id"##), + None, + Some(r##"The ID of the managing account."##), + Some(true), + Some(false)), + + (Some(r##"order-id"##), + None, + Some(r##"The ID of the order."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("advancetestorder", + Some(r##"Sandbox only. Moves a test order from state "inProgress" to state "pendingShipment"."##), + "Details at http://byron.github.io/google-apis-rs/google_content2_cli/orders_advancetestorder", + vec![ + (Some(r##"merchant-id"##), + None, + Some(r##"The ID of the managing account."##), + Some(true), + Some(false)), + + (Some(r##"order-id"##), + None, + Some(r##"The ID of the test order to modify."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("cancel", + Some(r##"Cancels all line items in an order."##), + "Details at http://byron.github.io/google-apis-rs/google_content2_cli/orders_cancel", + vec![ + (Some(r##"merchant-id"##), + None, + Some(r##"The ID of the managing account."##), + Some(true), + Some(false)), + + (Some(r##"order-id"##), + None, + Some(r##"The ID of the order to cancel."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("cancellineitem", + Some(r##"Cancels a line item."##), + "Details at http://byron.github.io/google-apis-rs/google_content2_cli/orders_cancellineitem", + vec![ + (Some(r##"merchant-id"##), + None, + Some(r##"The ID of the managing account."##), + Some(true), + Some(false)), + + (Some(r##"order-id"##), + None, + Some(r##"The ID of the order."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("createtestorder", + Some(r##"Sandbox only. Creates a test order."##), + "Details at http://byron.github.io/google-apis-rs/google_content2_cli/orders_createtestorder", + vec![ + (Some(r##"merchant-id"##), + None, + Some(r##"The ID of the managing account."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("custombatch", + Some(r##"Retrieves or modifies multiple orders in a single request."##), + "Details at http://byron.github.io/google-apis-rs/google_content2_cli/orders_custombatch", + vec![ + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("get", + Some(r##"Retrieves an order from your Merchant Center account."##), + "Details at http://byron.github.io/google-apis-rs/google_content2_cli/orders_get", + vec![ + (Some(r##"merchant-id"##), + None, + Some(r##"The ID of the managing account."##), + Some(true), + Some(false)), + + (Some(r##"order-id"##), + None, + Some(r##"The ID of the order."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("getbymerchantorderid", + Some(r##"Retrieves an order using merchant order id."##), + "Details at http://byron.github.io/google-apis-rs/google_content2_cli/orders_getbymerchantorderid", + vec![ + (Some(r##"merchant-id"##), + None, + Some(r##"The ID of the managing account."##), + Some(true), + Some(false)), + + (Some(r##"merchant-order-id"##), + None, + Some(r##"The merchant order id to be looked for."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("gettestordertemplate", + Some(r##"Sandbox only. Retrieves an order template that can be used to quickly create a new order in sandbox."##), + "Details at http://byron.github.io/google-apis-rs/google_content2_cli/orders_gettestordertemplate", + vec![ + (Some(r##"merchant-id"##), + None, + Some(r##"The ID of the managing account."##), + Some(true), + Some(false)), + + (Some(r##"template-name"##), + None, + Some(r##"The name of the template to retrieve."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Lists the orders in your Merchant Center account."##), + "Details at http://byron.github.io/google-apis-rs/google_content2_cli/orders_list", + vec![ + (Some(r##"merchant-id"##), + None, + Some(r##"The ID of the managing account."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("refund", + Some(r##"Refund a portion of the order, up to the full amount paid."##), + "Details at http://byron.github.io/google-apis-rs/google_content2_cli/orders_refund", + vec![ + (Some(r##"merchant-id"##), + None, + Some(r##"The ID of the managing account."##), + Some(true), + Some(false)), + + (Some(r##"order-id"##), + None, + Some(r##"The ID of the order to refund."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("returnlineitem", + Some(r##"Returns a line item."##), + "Details at http://byron.github.io/google-apis-rs/google_content2_cli/orders_returnlineitem", + vec![ + (Some(r##"merchant-id"##), + None, + Some(r##"The ID of the managing account."##), + Some(true), + Some(false)), + + (Some(r##"order-id"##), + None, + Some(r##"The ID of the order."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("shiplineitems", + Some(r##"Marks line item(s) as shipped."##), + "Details at http://byron.github.io/google-apis-rs/google_content2_cli/orders_shiplineitems", + vec![ + (Some(r##"merchant-id"##), + None, + Some(r##"The ID of the managing account."##), + Some(true), + Some(false)), + + (Some(r##"order-id"##), + None, + Some(r##"The ID of the order."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("updatemerchantorderid", + Some(r##"Updates the merchant order ID for a given order."##), + "Details at http://byron.github.io/google-apis-rs/google_content2_cli/orders_updatemerchantorderid", + vec![ + (Some(r##"merchant-id"##), + None, + Some(r##"The ID of the managing account."##), + Some(true), + Some(false)), + + (Some(r##"order-id"##), + None, + Some(r##"The ID of the order."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("updateshipment", + Some(r##"Updates a shipment's status, carrier, and/or tracking ID."##), + "Details at http://byron.github.io/google-apis-rs/google_content2_cli/orders_updateshipment", + vec![ + (Some(r##"merchant-id"##), + None, + Some(r##"The ID of the managing account."##), + Some(true), + Some(false)), + + (Some(r##"order-id"##), + None, + Some(r##"The ID of the order."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + ("products", "methods: 'custombatch', 'delete', 'get', 'insert' and 'list'", vec![ ("custombatch", Some(r##"Retrieves, inserts, and deletes multiple products in a single request."##), @@ -4521,7 +6203,7 @@ fn main() { let mut app = App::new("content2") .author("Sebastian Thiel ") - .version("0.3.2+20150710") + .version("0.3.2+20151002") .about("Manage product items, inventory, and Merchant Center accounts for Google Shopping.") .after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_content2_cli") .arg(Arg::with_name("url") diff --git a/gen/content2/Cargo.toml b/gen/content2/Cargo.toml index c653b3ebf2..158969b044 100644 --- a/gen/content2/Cargo.toml +++ b/gen/content2/Cargo.toml @@ -4,11 +4,11 @@ [package] name = "google-content2" -version = "0.1.9+20150710" +version = "0.1.9+20151002" 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/" +homepage = "https://developers.google.com/shopping-content" documentation = "http://byron.github.io/google-apis-rs/google_content2" license = "MIT" keywords = ["content", "google", "protocol", "web", "api"] diff --git a/gen/content2/README.md b/gen/content2/README.md index c6eb38eae4..528f9f211b 100644 --- a/gen/content2/README.md +++ b/gen/content2/README.md @@ -5,10 +5,10 @@ DO NOT EDIT ! --> 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.9+20150710*, where *20150710* is the exact revision of the *content:v2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +This documentation was generated from *Shopping Content* crate version *0.1.9+20151002*, where *20151002* is the exact revision of the *content:v2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. Everything else about the *Shopping Content* *v2* API can be found at the -[official documentation site](https://developers.google.com/shopping-content/v2/). +[official documentation site](https://developers.google.com/shopping-content). # Features Handle the following *Resources* with ease from the central [hub](http://byron.github.io/google-apis-rs/google_content2/struct.ShoppingContent.html) ... @@ -27,6 +27,8 @@ Handle the following *Resources* with ease from the central [hub](http://byron.g * [*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) +* [orders](http://byron.github.io/google-apis-rs/google_content2/struct.Order.html) + * [*acknowledge*](http://byron.github.io/google-apis-rs/google_content2/struct.OrderAcknowledgeCall.html), [*advancetestorder*](http://byron.github.io/google-apis-rs/google_content2/struct.OrderAdvancetestorderCall.html), [*cancel*](http://byron.github.io/google-apis-rs/google_content2/struct.OrderCancelCall.html), [*cancellineitem*](http://byron.github.io/google-apis-rs/google_content2/struct.OrderCancellineitemCall.html), [*createtestorder*](http://byron.github.io/google-apis-rs/google_content2/struct.OrderCreatetestorderCall.html), [*custombatch*](http://byron.github.io/google-apis-rs/google_content2/struct.OrderCustombatchCall.html), [*get*](http://byron.github.io/google-apis-rs/google_content2/struct.OrderGetCall.html), [*getbymerchantorderid*](http://byron.github.io/google-apis-rs/google_content2/struct.OrderGetbymerchantorderidCall.html), [*gettestordertemplate*](http://byron.github.io/google-apis-rs/google_content2/struct.OrderGettestordertemplateCall.html), [*list*](http://byron.github.io/google-apis-rs/google_content2/struct.OrderListCall.html), [*refund*](http://byron.github.io/google-apis-rs/google_content2/struct.OrderRefundCall.html), [*returnlineitem*](http://byron.github.io/google-apis-rs/google_content2/struct.OrderReturnlineitemCall.html), [*shiplineitems*](http://byron.github.io/google-apis-rs/google_content2/struct.OrderShiplineitemCall.html), [*updatemerchantorderid*](http://byron.github.io/google-apis-rs/google_content2/struct.OrderUpdatemerchantorderidCall.html) and [*updateshipment*](http://byron.github.io/google-apis-rs/google_content2/struct.OrderUpdateshipmentCall.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 @@ -63,14 +65,21 @@ 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() +let r = hub.orders().get(...).doit() +let r = hub.orders().list(...).doit() +let r = hub.orders().updateshipment(...).doit() +let r = hub.orders().advancetestorder(...).doit() +let r = hub.orders().updatemerchantorderid(...).doit() +let r = hub.orders().returnlineitem(...).doit() +let r = hub.orders().gettestordertemplate(...).doit() +let r = hub.orders().createtestorder(...).doit() +let r = hub.orders().refund(...).doit() +let r = hub.orders().custombatch(...).doit() +let r = hub.orders().cancellineitem(...).doit() +let r = hub.orders().getbymerchantorderid(...).doit() +let r = hub.orders().acknowledge(...).doit() +let r = hub.orders().cancel(...).doit() +let r = hub.orders().shiplineitems(...).doit() ``` The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` @@ -95,7 +104,6 @@ google-content2 = "*" extern crate hyper; extern crate yup_oauth2 as oauth2; extern crate google_content2 as content2; -use content2::Account; use content2::{Result, Error}; use std::default::Default; use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; @@ -113,16 +121,17 @@ 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(); - // You can configure optional parameters by calling 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") - .dry_run(false) +let result = hub.orders().list("merchantId") + .add_statuses("sit") + .placed_date_start("Stet") + .placed_date_end("sed") + .page_token("et") + .order_by("dolores") + .max_results(38) + .acknowledged(true) .doit(); match result { diff --git a/gen/content2/src/lib.rs b/gen/content2/src/lib.rs index c89043f9a3..6c740f23aa 100644 --- a/gen/content2/src/lib.rs +++ b/gen/content2/src/lib.rs @@ -2,10 +2,10 @@ // This file was generated automatically from 'src/mako/api/lib.rs.mako' // DO NOT EDIT ! -//! This documentation was generated from *Shopping Content* crate version *0.1.9+20150710*, where *20150710* is the exact revision of the *content:v2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +//! This documentation was generated from *Shopping Content* crate version *0.1.9+20151002*, where *20151002* is the exact revision of the *content:v2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. //! //! Everything else about the *Shopping Content* *v2* API can be found at the -//! [official documentation site](https://developers.google.com/shopping-content/v2/). +//! [official documentation site](https://developers.google.com/shopping-content). //! The original source code is [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/content2). //! # Features //! @@ -25,6 +25,8 @@ //! * [*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) +//! * [orders](struct.Order.html) +//! * [*acknowledge*](struct.OrderAcknowledgeCall.html), [*advancetestorder*](struct.OrderAdvancetestorderCall.html), [*cancel*](struct.OrderCancelCall.html), [*cancellineitem*](struct.OrderCancellineitemCall.html), [*createtestorder*](struct.OrderCreatetestorderCall.html), [*custombatch*](struct.OrderCustombatchCall.html), [*get*](struct.OrderGetCall.html), [*getbymerchantorderid*](struct.OrderGetbymerchantorderidCall.html), [*gettestordertemplate*](struct.OrderGettestordertemplateCall.html), [*list*](struct.OrderListCall.html), [*refund*](struct.OrderRefundCall.html), [*returnlineitem*](struct.OrderReturnlineitemCall.html), [*shiplineitems*](struct.OrderShiplineitemCall.html), [*updatemerchantorderid*](struct.OrderUpdatemerchantorderidCall.html) and [*updateshipment*](struct.OrderUpdateshipmentCall.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 @@ -63,14 +65,21 @@ //! 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() +//! let r = hub.orders().get(...).doit() +//! let r = hub.orders().list(...).doit() +//! let r = hub.orders().updateshipment(...).doit() +//! let r = hub.orders().advancetestorder(...).doit() +//! let r = hub.orders().updatemerchantorderid(...).doit() +//! let r = hub.orders().returnlineitem(...).doit() +//! let r = hub.orders().gettestordertemplate(...).doit() +//! let r = hub.orders().createtestorder(...).doit() +//! let r = hub.orders().refund(...).doit() +//! let r = hub.orders().custombatch(...).doit() +//! let r = hub.orders().cancellineitem(...).doit() +//! let r = hub.orders().getbymerchantorderid(...).doit() +//! let r = hub.orders().acknowledge(...).doit() +//! let r = hub.orders().cancel(...).doit() +//! let r = hub.orders().shiplineitems(...).doit() //! ``` //! //! The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` @@ -95,7 +104,6 @@ //! extern crate hyper; //! extern crate yup_oauth2 as oauth2; //! extern crate google_content2 as content2; -//! use content2::Account; //! use content2::{Result, Error}; //! # #[test] fn egal() { //! use std::default::Default; @@ -114,16 +122,17 @@ //! 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(); -//! //! // You can configure optional parameters by calling 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") -//! .dry_run(false) +//! let result = hub.orders().list("merchantId") +//! .add_statuses("ea") +//! .placed_date_start("et") +//! .placed_date_end("dolor") +//! .page_token("diam") +//! .order_by("kasd") +//! .max_results(14) +//! .acknowledged(true) //! .doit(); //! //! match result { diff --git a/gen/content2/src/lib.rs.in b/gen/content2/src/lib.rs.in index 05f632f57a..091ac6326d 100644 --- a/gen/content2/src/lib.rs.in +++ b/gen/content2/src/lib.rs.in @@ -69,7 +69,6 @@ impl Default for Scope { /// extern crate hyper; /// extern crate yup_oauth2 as oauth2; /// extern crate google_content2 as content2; -/// use content2::Account; /// use content2::{Result, Error}; /// # #[test] fn egal() { /// use std::default::Default; @@ -88,16 +87,17 @@ impl Default for Scope { /// 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(); -/// /// // You can configure optional parameters by calling 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") -/// .dry_run(true) +/// let result = hub.orders().list("merchantId") +/// .add_statuses("justo") +/// .placed_date_start("amet.") +/// .placed_date_end("erat") +/// .page_token("labore") +/// .order_by("sea") +/// .max_results(11) +/// .acknowledged(true) /// .doit(); /// /// match result { @@ -158,6 +158,9 @@ impl<'a, C, A> ShoppingContent pub fn inventory(&'a self) -> InventoryMethods<'a, C, A> { InventoryMethods { hub: &self } } + pub fn orders(&'a self) -> OrderMethods<'a, C, A> { + OrderMethods { hub: &self } + } pub fn products(&'a self) -> ProductMethods<'a, C, A> { ProductMethods { hub: &self } } @@ -180,6 +183,27 @@ impl<'a, C, A> ShoppingContent // ############ // 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, Deserialize)] +pub struct OrdersCustomBatchRequestEntryUpdateShipment { + /// New status for the shipment. Not updated if missing. + pub status: Option, + /// The carrier handling the shipment. Not updated if missing. + pub carrier: Option, + /// The tracking id for the shipment. Not updated if missing. + #[serde(rename="trackingId")] + pub tracking_id: Option, + /// The ID of the shipment. + #[serde(rename="shipmentId")] + pub shipment_id: Option, +} + +impl Part for OrdersCustomBatchRequestEntryUpdateShipment {} + + /// 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. @@ -197,25 +221,6 @@ pub struct Errors { impl Part for Errors {} -/// 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 ProductAspect { - /// Whether the aspect is required, excluded or should be validated. - pub intention: Option, - /// The name of the aspect. - #[serde(rename="aspectName")] - pub aspect_name: Option, - /// The name of the destination. Leave out to apply to all destinations. - #[serde(rename="destinationName")] - pub destination_name: Option, -} - -impl Part for ProductAspect {} - - /// 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. @@ -243,57 +248,23 @@ impl Part for ProductsCustomBatchResponseEntry {} /// This type is used in activities, which are methods you may call on this type or where 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) +/// * [refund orders](struct.OrderRefundCall.html) (request) /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] -pub struct AccounttaxCustomBatchResponse { - /// Identifies what kind of resource this is. Value: the fixed string "content#accounttaxCustomBatchResponse". - pub kind: Option, - /// The result of the execution of the batch requests. - pub entries: Option>, +pub struct OrdersRefundRequest { + /// The amount that is refunded. + pub amount: Option, + /// The explanation of the reason. + #[serde(rename="reasonText")] + pub reason_text: Option, + /// The reason for the refund. + pub reason: Option, + /// The ID of the operation. Unique across all operations for a given order. + #[serde(rename="operationId")] + pub operation_id: Option, } -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, Serialize, Deserialize)] -pub struct AccountshippingCustomBatchResponse { - /// Identifies what kind of resource this is. Value: the fixed string "content#accountshippingCustomBatchResponse". - pub kind: Option, - /// The result of the execution of the batch requests. - pub entries: Option>, -} - -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, Serialize, Deserialize)] -pub struct InventoryCustomBatchResponse { - /// Identifies what kind of resource this is. Value: the fixed string "content#inventoryCustomBatchResponse". - pub kind: Option, - /// The result of the execution of the batch requests. - pub entries: Option>, -} - -impl ResponseResult for InventoryCustomBatchResponse {} +impl RequestValue for OrdersRefundRequest {} /// There is no detailed description. @@ -312,85 +283,6 @@ pub struct AccountUser { 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: Option, - /// 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: Option, -} - -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, Deserialize)] -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, Serialize, Deserialize)] -pub struct DatafeedsCustomBatchResponse { - /// Identifies what kind of resource this is. Value: the fixed string "content#datafeedsCustomBatchResponse". - pub kind: Option, - /// The result of the execution of the batch requests. - pub entries: Option>, -} - -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(rename="postalCodeRanges")] - pub postal_code_ranges: Option>, - /// The country in which this location group is, represented as ISO 3166-1 Alpha-2 code. - pub country: Option, - /// A location ID (also called criteria ID) representing administrative areas, smaller country subdivisions (counties), or cities. - #[serde(rename="locationIds")] - pub location_ids: Option>, - /// The name of the location group. - pub name: Option, - /// 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(rename="postalCodes")] - pub postal_codes: Option>, -} - -impl Part for AccountShippingLocationGroup {} - - /// There is no detailed description. /// /// # Activities @@ -449,130 +341,71 @@ pub struct ProductStatus { 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. +/// 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 DatafeedFetchSchedule { - /// An optional user name for fetch_url. - pub username: Option, - /// An optional password for fetch_url. - pub password: Option, - /// The day of the week the feed file should be fetched. - pub weekday: Option, - /// The hour of the day the feed file should be fetched (0-24). - pub hour: Option, - /// Time zone used for schedule. UTC by default. E.g., "America/Los_Angeles". - #[serde(rename="timeZone")] - pub time_zone: Option, - /// 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(rename="fetchUrl")] - pub fetch_url: Option, - /// The day of the month the feed file should be fetched (1-31). - #[serde(rename="dayOfMonth")] - pub day_of_month: Option, +pub struct TestOrderCustomer { + /// If set, this indicates the user had a choice to opt in or out of providing marketing rights to the merchant. If unset, this indicates the user has already made this choice in a previous purchase, and was thus not shown the marketing right opt in/out checkbox during the Purchases on Google checkout flow. Optional. + #[serde(rename="explicitMarketingPreference")] + pub explicit_marketing_preference: Option, + /// Full name of the customer. + #[serde(rename="fullName")] + pub full_name: Option, + /// Email address of the customer. + pub email: Option, } -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, Serialize, Deserialize)] -pub struct DatafeedStatus { - /// Identifies what kind of resource this is. Value: the fixed string "content#datafeedStatus". - pub kind: Option, - /// The list of errors occurring in the feed. - pub errors: Option>, - /// The list of errors occurring in the feed. - pub warnings: Option>, - /// The number of items in the feed that were processed. - #[serde(rename="itemsTotal")] - pub items_total: Option, - /// The processing status of the feed. - #[serde(rename="processingStatus")] - pub processing_status: Option, - /// The last date at which the feed was uploaded. - #[serde(rename="lastUploadDate")] - pub last_upload_date: Option, - /// The number of items in the feed that were valid. - #[serde(rename="itemsValid")] - pub items_valid: Option, - /// The ID of the feed for which the status is reported. - #[serde(rename="datafeedId")] - pub datafeed_id: Option, -} - -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, Deserialize)] -pub struct DatafeedstatusesCustomBatchRequestEntry { - /// An entry ID, unique within the batch request. - #[serde(rename="batchId")] - pub batch_id: Option, - /// The ID of the data feed to get or delete. - #[serde(rename="datafeedId")] - pub datafeed_id: Option, - /// The ID of the managing account. - #[serde(rename="merchantId")] - pub merchant_id: Option, - /// no description provided - pub method: Option, -} - -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, Serialize, Deserialize)] -pub struct AccounttaxCustomBatchResponseEntry { - /// The ID of the request entry this entry responds to. - #[serde(rename="batchId")] - pub batch_id: Option, - /// The retrieved or updated account tax settings. - #[serde(rename="accountTax")] - pub account_tax: Option, - /// A list of errors defined if and only if the request failed. - pub errors: Option, - /// Identifies what kind of resource this is. Value: the fixed string "content#accounttaxCustomBatchResponseEntry". - pub kind: Option, -} - -impl Part for AccounttaxCustomBatchResponseEntry {} +impl Part for TestOrderCustomer {} /// 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) +/// This type is not used in any activity, and only used as *part* of another schema. /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] -pub struct AccountstatusesCustomBatchRequest { - /// The request entries to be processed in the batch. - pub entries: Option>, +pub struct OrderLineItemProduct { + /// The CLDR territory code of the target country of the product. + #[serde(rename="targetCountry")] + pub target_country: Option, + /// URL to the cached image shown to the user when order was placed. + #[serde(rename="shownImage")] + pub shown_image: Option, + /// The two-letter ISO 639-1 language code for the item. + #[serde(rename="contentLanguage")] + pub content_language: Option, + /// The title of the product. + pub title: Option, + /// Manufacturer Part Number (MPN) of the item. + pub mpn: Option, + /// Variant attributes for the item. These are dimensions of the product, such as color, gender, material, pattern, and size. You can find a comprehensive list of variant attributes here. + #[serde(rename="variantAttributes")] + pub variant_attributes: Option>, + /// Brand of the item. + pub brand: Option, + /// URL of an image of the item. + #[serde(rename="imageLink")] + pub image_link: Option, + /// An identifier of the item. + #[serde(rename="offerId")] + pub offer_id: Option, + /// The REST id of the product. + pub id: Option, + /// Shared identifier for all variants of the same product. + #[serde(rename="itemGroupId")] + pub item_group_id: Option, + /// Global Trade Item Number (GTIN) of the item. + pub gtin: Option, + /// Condition or state of the item. + pub condition: Option, + /// Price of the item. + pub price: Option, + /// The item's channel (online or local). + pub channel: Option, } -impl RequestValue for AccountstatusesCustomBatchRequest {} +impl Part for OrderLineItemProduct {} /// Building block of the cost calculation decision tree. @@ -647,52 +480,22 @@ impl ResponseResult for Account {} /// There is no detailed description. /// -/// This type is not used in any activity, and only used as *part* of another schema. +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [getbymerchantorderid orders](struct.OrderGetbymerchantorderidCall.html) (response) /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] -pub struct AccountIdentifier { - /// The aggregator ID, set for aggregators and subaccounts (in that case, it represents the aggregator of the subaccount). - #[serde(rename="aggregatorId")] - pub aggregator_id: Option, - /// The merchant account ID, set for individual accounts and subaccounts. - #[serde(rename="merchantId")] - pub merchant_id: Option, -} - -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, Serialize, Deserialize)] -pub struct InventoryCustomBatchResponseEntry { - /// The ID of the request entry this entry responds to. - #[serde(rename="batchId")] - pub batch_id: Option, - /// Identifies what kind of resource this is. Value: the fixed string "content#inventoryCustomBatchResponseEntry". +pub struct OrdersGetByMerchantOrderIdResponse { + /// Identifies what kind of resource this is. Value: the fixed string "content#ordersGetByMerchantOrderIdResponse". pub kind: Option, - /// A list of errors defined if and only if the request failed. - pub errors: Option, + /// The requested order. + pub order: Option, } -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: Option>, - /// The name of the group. Underscores will be replaced by spaces upon insertion. - pub name: Option, -} - -impl Part for ProductCustomGroup {} +impl ResponseResult for OrdersGetByMerchantOrderIdResponse {} /// There is no detailed description. @@ -714,23 +517,1192 @@ pub struct ProductShippingDimension { impl Part for ProductShippingDimension {} -/// A batch entry encoding a single non-batch accountstatuses response. +/// 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 orders](struct.OrderListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct OrdersListResponse { + /// The token for the retrieval of the next page of orders. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// Identifies what kind of resource this is. Value: the fixed string "content#ordersListResponse". + pub kind: Option, + /// no description provided + pub resources: Option>, +} + +impl ResponseResult for OrdersListResponse {} + + +/// 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 AccountstatusesCustomBatchResponseEntry { +pub struct OrderShipmentLineItemShipment { + /// The id of the line item that is shipped. + #[serde(rename="lineItemId")] + pub line_item_id: Option, + /// The quantity that is shipped. + pub quantity: Option, +} + +impl Part for OrderShipmentLineItemShipment {} + + +/// 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, Serialize, Deserialize)] +pub struct AccounttaxListResponse { + /// The token for the retrieval of the next page of account tax settings. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// Identifies what kind of resource this is. Value: the fixed string "content#accounttaxListResponse". + pub kind: Option, + /// no description provided + pub resources: Option>, +} + +impl ResponseResult for AccounttaxListResponse {} + + +/// 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(rename="locationId")] + pub location_id: Option, + /// A free-form description of the service class or delivery speed. + pub service: Option, + /// 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(rename="postalCode")] + pub postal_code: Option, + /// The CLDR territory code of the country to which an item will ship. + pub country: Option, + /// Fixed shipping price, represented as a number. + pub price: Option, + /// The geographic region to which a shipping rate applies (e.g. zip code). + pub region: Option, + /// The location where the shipping is applicable, represented by a location group name. + #[serde(rename="locationGroupName")] + pub location_group_name: Option, +} + +impl Part for ProductShipping {} + + +/// 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 OrdersCustomBatchRequestEntry { + /// The ID of the order. Required for all methods beside getByMerchantOrderId. + #[serde(rename="orderId")] + pub order_id: Option, + /// An entry ID, unique within the batch request. + #[serde(rename="batchId")] + pub batch_id: Option, + /// Required for shipLineItems method. + #[serde(rename="shipLineItems")] + pub ship_line_items: Option, + /// Required for updateShipment method. + #[serde(rename="updateShipment")] + pub update_shipment: Option, + /// The ID of the managing account. + #[serde(rename="merchantId")] + pub merchant_id: Option, + /// The merchant order id. Required for updateMerchantOrderId and getByMerchantOrderId methods. + #[serde(rename="merchantOrderId")] + pub merchant_order_id: Option, + /// Required for cancelLineItem method. + #[serde(rename="cancelLineItem")] + pub cancel_line_item: Option, + /// Required for refund method. + pub refund: Option, + /// Required for cancel method. + pub cancel: Option, + /// The ID of the operation. Unique across all operations for a given order. Required for all methods beside get and getByMerchantOrderId. + #[serde(rename="operationId")] + pub operation_id: Option, + /// The method to apply. + pub method: Option, + /// Required for returnLineItem method. + #[serde(rename="returnLineItem")] + pub return_line_item: Option, +} + +impl Part for OrdersCustomBatchRequestEntry {} + + +/// 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, Deserialize)] +pub struct ProductsCustomBatchRequestEntry { + /// An entry ID, unique within the batch request. + #[serde(rename="batchId")] + pub batch_id: Option, + /// The product to insert. Only required if the method is insert. + pub product: Option, + /// The ID of the managing account. + #[serde(rename="merchantId")] + pub merchant_id: Option, + /// no description provided + pub method: Option, + /// The ID of the product to get or delete. Only defined if the method is get or delete. + #[serde(rename="productId")] + pub product_id: Option, +} + +impl Part for ProductsCustomBatchRequestEntry {} + + +/// 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 OrdersCustomBatchRequestEntryRefund { + /// The amount that is refunded. + pub amount: Option, + /// The explanation of the reason. + #[serde(rename="reasonText")] + pub reason_text: Option, + /// The reason for the refund. + pub reason: Option, +} + +impl Part for OrdersCustomBatchRequestEntryRefund {} + + +/// 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, Deserialize)] +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, Serialize, Deserialize)] +pub struct ProductstatusesCustomBatchResponse { + /// Identifies what kind of resource this is. Value: the fixed string "content#productstatusesCustomBatchResponse". + pub kind: Option, + /// The result of the execution of the batch requests. + pub entries: Option>, +} + +impl ResponseResult for ProductstatusesCustomBatchResponse {} + + +/// 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: Option, + /// The last (inclusive) postal code or prefix of the range. + pub end: Option, +} + +impl Part for AccountShippingPostalCodeRange {} + + +/// 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 TestOrderPaymentMethod { + /// The card expiration month (January = 1, February = 2 etc.). + #[serde(rename="expirationMonth")] + pub expiration_month: Option, + /// The last four digits of the card number. + #[serde(rename="lastFourDigits")] + pub last_four_digits: Option, + /// The card expiration year (4-digit, e.g. 2015). + #[serde(rename="expirationYear")] + pub expiration_year: Option, + /// The type of instrument. Note that real orders might have different values than the four values accepted by createTestOrder. + #[serde(rename="type")] + pub type_: Option, + /// The billing address. + #[serde(rename="predefinedBillingAddress")] + pub predefined_billing_address: Option, +} + +impl Part for TestOrderPaymentMethod {} + + +/// 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*). +/// +/// * [createtestorder orders](struct.OrderCreatetestorderCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct OrdersCreateTestOrderRequest { + /// The test order to create. + #[serde(rename="testOrder")] + pub test_order: Option, + /// The test order template to use. Specify as an alternative to testOrder as a shortcut for retrieving a template and then creating an order using that template. + #[serde(rename="templateName")] + pub template_name: Option, +} + +impl RequestValue for OrdersCreateTestOrderRequest {} + + +/// 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 OrderReturn { + /// Quantity that is returned. + pub quantity: Option, + /// The reason for the return. + pub reason: Option, + /// Date on which the item has been created, in ISO 8601 format. + #[serde(rename="creationDate")] + pub creation_date: Option, + /// The actor that created the refund. + pub actor: Option, + /// The explanation of the reason. + #[serde(rename="reasonText")] + pub reason_text: Option, +} + +impl Part for OrderReturn {} + + +/// 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: Option, + /// The numeric id of a location that the tax rate applies to as defined in the AdWords API. + #[serde(rename="locationId")] + pub location_id: Option, + /// 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(rename="postalCode")] + pub postal_code: Option, + /// The country within which the item is taxed, specified as a CLDR territory code. + pub country: Option, + /// The geographic region to which the tax rate applies. + pub region: Option, + /// Set to true if tax is charged on shipping. + #[serde(rename="taxShip")] + pub tax_ship: Option, +} + +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, Serialize, Deserialize)] +pub struct DatafeedstatusesCustomBatchResponse { + /// Identifies what kind of resource this is. Value: the fixed string "content#datafeedstatusesCustomBatchResponse". + pub kind: Option, + /// The result of the execution of the batch requests. + pub entries: Option>, +} + +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, Deserialize)] +pub struct AccountsCustomBatchRequestEntry { + /// An entry ID, unique within the batch request. + #[serde(rename="batchId")] + pub batch_id: Option, + /// The account to create or update. Only defined if the method is insert or update. + pub account: Option, + /// The ID of the account to get or delete. Only defined if the method is get or delete. + #[serde(rename="accountId")] + pub account_id: Option, + /// The ID of the managing account. + #[serde(rename="merchantId")] + pub merchant_id: Option, + /// no description provided + pub method: Option, +} + +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*). +/// +/// * [list datafeedstatuses](struct.DatafeedstatuseListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct DatafeedstatusesListResponse { + /// The token for the retrieval of the next page of datafeed statuses. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// Identifies what kind of resource this is. Value: the fixed string "content#datafeedstatusesListResponse". + pub kind: Option, + /// no description provided + pub resources: Option>, +} + +impl ResponseResult for DatafeedstatusesListResponse {} + + +/// 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, Serialize, Deserialize)] +pub struct AccountstatusesCustomBatchResponse { + /// Identifies what kind of resource this is. Value: the fixed string "content#accountstatusesCustomBatchResponse". + pub kind: Option, + /// The result of the execution of the batch requests. + pub entries: Option>, +} + +impl ResponseResult for AccountstatusesCustomBatchResponse {} + + +/// 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: Option, + /// The number of installments the buyer has to pay. + pub months: Option, +} + +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, Serialize, Deserialize)] +pub struct DatafeedstatusesCustomBatchResponseEntry { /// The ID of the request entry this entry responds to. #[serde(rename="batchId")] pub batch_id: Option, /// A list of errors defined if and only if the request failed. pub errors: Option, - /// The requested account status. Defined if and only if the request was successful. - #[serde(rename="accountStatus")] - pub account_status: Option, + /// The requested data feed status. Defined if and only if the request was successful. + #[serde(rename="datafeedStatus")] + pub datafeed_status: Option, } -impl Part for AccountstatusesCustomBatchResponseEntry {} +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, Deserialize)] +pub struct Inventory { + /// The quantity of the product that is reserved for sell-on-google ads. Supported only for online products. + #[serde(rename="sellOnGoogleQuantity")] + pub sell_on_google_quantity: Option, + /// Identifies what kind of resource this is. Value: the fixed string "content#inventory". + pub kind: Option, + /// The sale price of the product. Mandatory if sale_price_effective_date is defined. + #[serde(rename="salePrice")] + pub sale_price: Option, + /// 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(rename="salePriceEffectiveDate")] + pub sale_price_effective_date: Option, + /// The price of the product. + pub price: Option, + /// The availability of the product. + pub availability: Option, + /// The quantity of the product. Must be equal to or greater than zero. Supported only for local products. + pub quantity: Option, +} + +impl Part for Inventory {} + + +/// 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*). +/// +/// * [shiplineitems orders](struct.OrderShiplineitemCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct OrdersShipLineItemsRequest { + /// The ID of the operation. Unique across all operations for a given order. + #[serde(rename="operationId")] + pub operation_id: Option, + /// Line items to ship. + #[serde(rename="lineItems")] + pub line_items: Option>, + /// The carrier handling the shipment. + pub carrier: Option, + /// The tracking id for the shipment. + #[serde(rename="trackingId")] + pub tracking_id: Option, + /// The ID of the shipment. + #[serde(rename="shipmentId")] + pub shipment_id: Option, +} + +impl RequestValue for OrdersShipLineItemsRequest {} + + +/// 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: Option>, + /// The sale country for which this table is valid, represented as a CLDR territory code. + #[serde(rename="saleCountry")] + pub sale_country: Option, + /// The name of the rate table. + pub name: Option, +} + +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, Serialize, Deserialize)] +pub struct ProductStatusDestinationStatus { + /// The destination's approval status. + #[serde(rename="approvalStatus")] + pub approval_status: Option, + /// The name of the destination + pub destination: Option, + /// Whether the destination is required, excluded, selected by default or should be validated. + pub intention: Option, +} + +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, Deserialize)] +pub struct AccounttaxCustomBatchRequest { + /// The request entries to be processed in the batch. + pub entries: Option>, +} + +impl RequestValue for AccounttaxCustomBatchRequest {} + + +/// 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*). +/// +/// * [updatemerchantorderid orders](struct.OrderUpdatemerchantorderidCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct OrdersUpdateMerchantOrderIdResponse { + /// Identifies what kind of resource this is. Value: the fixed string "content#ordersUpdateMerchantOrderIdResponse". + pub kind: Option, + /// The status of the execution. + #[serde(rename="executionStatus")] + pub execution_status: Option, +} + +impl ResponseResult for OrdersUpdateMerchantOrderIdResponse {} + + +/// 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, Serialize, Deserialize)] +pub struct DatafeedStatusError { + /// The number of occurrences of the error in the feed. + pub count: Option, + /// The error message, e.g., "Invalid price". + pub message: Option, + /// The code of the error, e.g., "validation/invalid_value". + pub code: Option, + /// A list of example occurrences of the error, grouped by product. + pub examples: Option>, +} + +impl Part for DatafeedStatusError {} + + +/// 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*). +/// +/// * [cancellineitem orders](struct.OrderCancellineitemCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct OrdersCancelLineItemResponse { + /// Identifies what kind of resource this is. Value: the fixed string "content#ordersCancelLineItemResponse". + pub kind: Option, + /// The status of the execution. + #[serde(rename="executionStatus")] + pub execution_status: Option, +} + +impl ResponseResult for OrdersCancelLineItemResponse {} + + +/// 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*). +/// +/// * [shiplineitems orders](struct.OrderShiplineitemCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct OrdersShipLineItemsResponse { + /// Identifies what kind of resource this is. Value: the fixed string "content#ordersShipLineItemsResponse". + pub kind: Option, + /// The status of the execution. + #[serde(rename="executionStatus")] + pub execution_status: Option, +} + +impl ResponseResult for OrdersShipLineItemsResponse {} + + +/// 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 OrderAddress { + /// City, town or commune. May also include dependent localities or sublocalities (e.g. neighborhoods or suburbs). + pub locality: Option, + /// CLDR country code (e.g. "US"). + pub country: Option, + /// Strings representing the lines of the printed label for mailing the order, for example: + /// John Smith + /// 1600 Amphitheatre Parkway + /// Mountain View, CA, 94043 + /// United States + #[serde(rename="fullAddress")] + pub full_address: Option>, + /// Street-level part of the address. + #[serde(rename="streetAddress")] + pub street_address: Option>, + /// Postal Code or ZIP (e.g. "94043"). + #[serde(rename="postalCode")] + pub postal_code: Option, + /// Name of the recipient. + #[serde(rename="recipientName")] + pub recipient_name: Option, + /// Whether the address is a post office box. + #[serde(rename="isPostOfficeBox")] + pub is_post_office_box: Option, + /// Top-level administrative subdivision of the country (e.g. "CA"). + pub region: Option, +} + +impl Part for OrderAddress {} + + +/// 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 OrderLineItemProductVariantAttribute { + /// The dimension of the variant. + pub dimension: Option, + /// The value for the dimension. + pub value: Option, +} + +impl Part for OrderLineItemProductVariantAttribute {} + + +/// 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 OrderCancellation { + /// The quantity that was canceled. + pub quantity: Option, + /// The reason for the cancellation. + pub reason: Option, + /// Date on which the cancellation has been created, in ISO 8601 format. + #[serde(rename="creationDate")] + pub creation_date: Option, + /// The actor that created the cancellation. + pub actor: Option, + /// The explanation of the reason. + #[serde(rename="reasonText")] + pub reason_text: Option, +} + +impl Part for OrderCancellation {} + + +/// 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, Deserialize)] +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 OrdersCustomBatchRequestEntryCancel { + /// The reason for the cancellation. + pub reason: Option, + /// The explanation of the reason. + #[serde(rename="reasonText")] + pub reason_text: Option, +} + +impl Part for OrdersCustomBatchRequestEntryCancel {} + + +/// 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: Option, + /// The type of the attribute. + #[serde(rename="type")] + pub type_: Option, + /// The name of the attribute. Underscores will be replaced by spaces upon insertion. + pub name: Option, + /// The value of the attribute. + pub value: Option, +} + +impl Part for ProductCustomAttribute {} + + +/// 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(rename="weightMax")] + pub weight_max: Option, + /// Delivery location in terms of a location ID. Can be used to represent administrative areas, smaller country subdivisions, or cities. + #[serde(rename="deliveryLocationId")] + pub delivery_location_id: Option, + /// Shipping label of the product. The products with the label are matched. + #[serde(rename="shippingLabel")] + pub shipping_label: Option, + /// Delivery location in terms of a location group name. A location group with this name must be specified among location groups. + #[serde(rename="deliveryLocationGroup")] + pub delivery_location_group: Option, + /// Delivery location in terms of a postal code. + #[serde(rename="deliveryPostalCode")] + pub delivery_postal_code: Option, + /// Maximum shipping price. Forms an interval between the maximum of smaller prices (exclusive) and this price (inclusive). + #[serde(rename="priceMax")] + pub price_max: Option, + /// Delivery location in terms of a postal code range. + #[serde(rename="deliveryPostalCodeRange")] + pub delivery_postal_code_range: Option, +} + +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, Deserialize)] +pub struct InventoryCustomBatchRequest { + /// The request entries to be processed in the batch. + pub entries: Option>, +} + +impl RequestValue for InventoryCustomBatchRequest {} + + +/// 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*). +/// +/// * [cancellineitem orders](struct.OrderCancellineitemCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct OrdersCancelLineItemRequest { + /// The ID of the operation. Unique across all operations for a given order. + #[serde(rename="operationId")] + pub operation_id: Option, + /// The reason for the cancellation. + pub reason: Option, + /// The explanation of the reason. + #[serde(rename="reasonText")] + pub reason_text: Option, + /// The ID of the line item to cancel. + #[serde(rename="lineItemId")] + pub line_item_id: Option, + /// The quantity to cancel. + pub quantity: Option, +} + +impl RequestValue for OrdersCancelLineItemRequest {} + + +/// 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 ProductStatusDataQualityIssue { + /// The value the attribute had at time of evaluation. + #[serde(rename="valueProvided")] + pub value_provided: Option, + /// The severity of the data quality issue. + pub severity: Option, + /// The time stamp of the data quality issue. + pub timestamp: Option, + /// A more detailed error string. + pub detail: Option, + /// The attribute name that is relevant for the issue. + pub location: Option, + /// The value of that attribute that was found on the landing page + #[serde(rename="valueOnLandingPage")] + pub value_on_landing_page: Option, + /// The id of the data quality issue. + pub id: Option, + /// The fetch status for landing_page_errors. + #[serde(rename="fetchStatus")] + pub fetch_status: Option, +} + +impl Part for ProductStatusDataQualityIssue {} + + +/// 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: Option, + /// Decision tree for "complicated" shipping cost calculation. + #[serde(rename="costRuleTree")] + pub cost_rule_tree: Option, + /// The CLDR territory code of the sale country for which this service can be used. + #[serde(rename="saleCountry")] + pub sale_country: Option, + /// Calculation method for the "simple" case that needs no rules. + #[serde(rename="calculationMethod")] + pub calculation_method: Option, + /// The name of this shipping service. + pub name: Option, +} + +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, Serialize, Deserialize)] +pub struct AccountshippingCustomBatchResponseEntry { + /// The ID of the request entry this entry responds to. + #[serde(rename="batchId")] + pub batch_id: Option, + /// Identifies what kind of resource this is. Value: the fixed string "content#accountshippingCustomBatchResponseEntry". + pub kind: Option, + /// A list of errors defined if and only if the request failed. + pub errors: Option, + /// The retrieved or updated account shipping settings. + #[serde(rename="accountShipping")] + pub account_shipping: Option, +} + +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*). +/// +/// * [custombatch datafeeds](struct.DatafeedCustombatchCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct DatafeedsCustomBatchResponse { + /// Identifies what kind of resource this is. Value: the fixed string "content#datafeedsCustomBatchResponse". + pub kind: Option, + /// The result of the execution of the batch requests. + pub entries: Option>, +} + +impl ResponseResult for DatafeedsCustomBatchResponse {} + + +/// 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: Option, + /// The name of the destination. + #[serde(rename="destinationName")] + pub destination_name: Option, +} + +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*). +/// +/// * [gettestordertemplate orders](struct.OrderGettestordertemplateCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct OrdersGetTestOrderTemplateResponse { + /// Identifies what kind of resource this is. Value: the fixed string "content#ordersGetTestOrderTemplateResponse". + pub kind: Option, + /// The requested test order template. + pub template: Option, +} + +impl ResponseResult for OrdersGetTestOrderTemplateResponse {} + + +/// 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 OrderLineItem { + /// Product data from the time of the order placement. + pub product: Option, + /// Number of items delivered. + #[serde(rename="quantityDelivered")] + pub quantity_delivered: Option, + /// Details of the return policy for the line item. + #[serde(rename="returnInfo")] + pub return_info: Option, + /// Total price for the line item. For example, if two items for $10 are purchased, the total price will be $20. + pub price: Option, + /// Number of items pending. + #[serde(rename="quantityPending")] + pub quantity_pending: Option, + /// Total tax amount for the line item. For example, if two items are purchased, and each have a cost tax of $2, the total tax amount will be $4. + pub tax: Option, + /// Cancellations of the line item. + pub cancellations: Option>, + /// Number of items canceled. + #[serde(rename="quantityCanceled")] + pub quantity_canceled: Option, + /// The id of the line item. + pub id: Option, + /// Returns of the line item. + pub returns: Option>, + /// Number of items shipped. + #[serde(rename="quantityShipped")] + pub quantity_shipped: Option, + /// Number of items returned. + #[serde(rename="quantityReturned")] + pub quantity_returned: Option, + /// Number of items ordered. + #[serde(rename="quantityOrdered")] + pub quantity_ordered: Option, + /// Details of the requested shipping for the line item. + #[serde(rename="shippingDetails")] + pub shipping_details: Option, +} + +impl Part for OrderLineItem {} + + +/// 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*). +/// +/// * [createtestorder orders](struct.OrderCreatetestorderCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct OrdersCreateTestOrderResponse { + /// The ID of the newly created test order. + #[serde(rename="orderId")] + pub order_id: Option, + /// Identifies what kind of resource this is. Value: the fixed string "content#ordersCreateTestOrderResponse". + pub kind: Option, +} + +impl ResponseResult for OrdersCreateTestOrderResponse {} + + +/// 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 OrderDeliveryDetails { + /// The phone number of the person receiving the delivery. + #[serde(rename="phoneNumber")] + pub phone_number: Option, + /// The delivery address + pub address: Option, +} + +impl Part for OrderDeliveryDetails {} + + +/// 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: Option, + /// An optional password for fetch_url. + pub password: Option, + /// The day of the week the feed file should be fetched. + pub weekday: Option, + /// The hour of the day the feed file should be fetched (0-24). + pub hour: Option, + /// Time zone used for schedule. UTC by default. E.g., "America/Los_Angeles". + #[serde(rename="timeZone")] + pub time_zone: Option, + /// 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(rename="fetchUrl")] + pub fetch_url: Option, + /// The day of the month the feed file should be fetched (1-31). + #[serde(rename="dayOfMonth")] + pub day_of_month: Option, +} + +impl Part for DatafeedFetchSchedule {} + + +/// 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, Deserialize)] +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: Option, + /// Name of loyalty points program. It is recommended to limit the name to 12 full-width characters or 24 Roman characters. + pub name: Option, + /// The retailer's loyalty points in absolute value. + #[serde(rename="pointsValue")] + pub points_value: Option, +} + +impl Part for LoyaltyPoints {} + + +/// 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 ProductAspect { + /// Whether the aspect is required, excluded or should be validated. + pub intention: Option, + /// The name of the aspect. + #[serde(rename="aspectName")] + pub aspect_name: Option, + /// The name of the destination. Leave out to apply to all destinations. + #[serde(rename="destinationName")] + pub destination_name: Option, +} + +impl Part for ProductAspect {} + + +/// 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, Serialize, Deserialize)] +pub struct AccounttaxCustomBatchResponse { + /// Identifies what kind of resource this is. Value: the fixed string "content#accounttaxCustomBatchResponse". + pub kind: Option, + /// The result of the execution of the batch requests. + pub entries: Option>, +} + +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, Serialize, Deserialize)] +pub struct AccountshippingCustomBatchResponse { + /// Identifies what kind of resource this is. Value: the fixed string "content#accountshippingCustomBatchResponse". + pub kind: Option, + /// The result of the execution of the batch requests. + pub entries: Option>, +} + +impl ResponseResult for AccountshippingCustomBatchResponse {} /// A batch entry encoding a single non-batch accountstatuses request. @@ -755,6 +1727,43 @@ pub struct AccountstatusesCustomBatchRequestEntry { impl Part for AccountstatusesCustomBatchRequestEntry {} +/// 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, Deserialize)] +pub struct ProductstatusesCustomBatchRequestEntry { + /// An entry ID, unique within the batch request. + #[serde(rename="batchId")] + pub batch_id: Option, + /// The ID of the managing account. + #[serde(rename="merchantId")] + pub merchant_id: Option, + /// no description provided + pub method: Option, + /// The ID of the product whose status to get. + #[serde(rename="productId")] + pub product_id: Option, +} + +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 AccountShippingRateTableCell { + /// The rate applicable if the cell conditions are matched. + pub rate: Option, + /// 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: Option, +} + +impl Part for AccountShippingRateTableCell {} + + /// There is no detailed description. /// /// # Activities @@ -762,20 +1771,274 @@ impl Part for AccountstatusesCustomBatchRequestEntry {} /// This type is used in activities, which are methods you may call on this type or where 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) +/// * [custombatch productstatuses](struct.ProductstatuseCustombatchCall.html) (request) /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] -pub struct AccounttaxListResponse { - /// The token for the retrieval of the next page of account tax settings. - #[serde(rename="nextPageToken")] - pub next_page_token: Option, - /// Identifies what kind of resource this is. Value: the fixed string "content#accounttaxListResponse". - pub kind: Option, - /// no description provided - pub resources: Option>, +pub struct ProductstatusesCustomBatchRequest { + /// The request entries to be processed in the batch. + pub entries: Option>, } -impl ResponseResult for AccounttaxListResponse {} +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*). +/// +/// * [updateshipment orders](struct.OrderUpdateshipmentCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct OrdersUpdateShipmentResponse { + /// Identifies what kind of resource this is. Value: the fixed string "content#ordersUpdateShipmentResponse". + pub kind: Option, + /// The status of the execution. + #[serde(rename="executionStatus")] + pub execution_status: Option, +} + +impl ResponseResult for OrdersUpdateShipmentResponse {} + + +/// 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 OrderRefund { + /// The amount that is refunded. + pub amount: Option, + /// Date on which the item has been created, in ISO 8601 format. + #[serde(rename="creationDate")] + pub creation_date: Option, + /// The reason for the refund. + pub reason: Option, + /// The actor that created the refund. + pub actor: Option, + /// The explanation of the reason. + #[serde(rename="reasonText")] + pub reason_text: Option, +} + +impl Part for OrderRefund {} + + +/// 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(rename="postalCodeRanges")] + pub postal_code_ranges: Option>, + /// The CLDR territory code of the country in which this location group is. + pub country: Option, + /// A location ID (also called criteria ID) representing administrative areas, smaller country subdivisions (counties), or cities. + #[serde(rename="locationIds")] + pub location_ids: Option>, + /// The name of the location group. + pub name: Option, + /// 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(rename="postalCodes")] + pub postal_codes: Option>, +} + +impl Part for AccountShippingLocationGroup {} + + +/// 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 AccountIdentifier { + /// The aggregator ID, set for aggregators and subaccounts (in that case, it represents the aggregator of the subaccount). + #[serde(rename="aggregatorId")] + pub aggregator_id: Option, + /// The merchant account ID, set for individual accounts and subaccounts. + #[serde(rename="merchantId")] + pub merchant_id: Option, +} + +impl Part for AccountIdentifier {} + + +/// 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, Serialize, Deserialize)] +pub struct DatafeedStatus { + /// Identifies what kind of resource this is. Value: the fixed string "content#datafeedStatus". + pub kind: Option, + /// The list of errors occurring in the feed. + pub errors: Option>, + /// The list of errors occurring in the feed. + pub warnings: Option>, + /// The number of items in the feed that were processed. + #[serde(rename="itemsTotal")] + pub items_total: Option, + /// The processing status of the feed. + #[serde(rename="processingStatus")] + pub processing_status: Option, + /// The last date at which the feed was uploaded. + #[serde(rename="lastUploadDate")] + pub last_upload_date: Option, + /// The number of items in the feed that were valid. + #[serde(rename="itemsValid")] + pub items_valid: Option, + /// The ID of the feed for which the status is reported. + #[serde(rename="datafeedId")] + pub datafeed_id: Option, +} + +impl ResponseResult for DatafeedStatus {} + + +/// 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: Option>, + /// The name of the group. Underscores will be replaced by spaces upon insertion. + pub name: Option, +} + +impl Part for ProductCustomGroup {} + + +/// 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*). +/// +/// * [updatemerchantorderid orders](struct.OrderUpdatemerchantorderidCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct OrdersUpdateMerchantOrderIdRequest { + /// The merchant order id to be assigned to the order. Must be unique per merchant. + #[serde(rename="merchantOrderId")] + pub merchant_order_id: Option, + /// The ID of the operation. Unique across all operations for a given order. + #[serde(rename="operationId")] + pub operation_id: Option, +} + +impl RequestValue for OrdersUpdateMerchantOrderIdRequest {} + + +/// 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, Serialize, Deserialize)] +pub struct ProductsCustomBatchResponse { + /// Identifies what kind of resource this is. Value: the fixed string "content#productsCustomBatchResponse". + pub kind: Option, + /// The result of the execution of the batch requests. + pub entries: Option>, +} + +impl ResponseResult for ProductsCustomBatchResponse {} + + +/// 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, Serialize, Deserialize)] +pub struct InventoryCustomBatchResponseEntry { + /// The ID of the request entry this entry responds to. + #[serde(rename="batchId")] + pub batch_id: Option, + /// Identifies what kind of resource this is. Value: the fixed string "content#inventoryCustomBatchResponseEntry". + pub kind: Option, + /// A list of errors defined if and only if the request failed. + pub errors: Option, +} + +impl Part for InventoryCustomBatchResponseEntry {} + + +/// 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, Deserialize)] +pub struct DatafeedstatusesCustomBatchRequestEntry { + /// An entry ID, unique within the batch request. + #[serde(rename="batchId")] + pub batch_id: Option, + /// The ID of the data feed to get or delete. + #[serde(rename="datafeedId")] + pub datafeed_id: Option, + /// The ID of the managing account. + #[serde(rename="merchantId")] + pub merchant_id: Option, + /// no description provided + pub method: Option, +} + +impl Part for DatafeedstatusesCustomBatchRequestEntry {} + + +/// 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 OrderCustomer { + /// If set, this indicates the user had a choice to opt in or out of providing marketing rights to the merchant. If unset, this indicates the user has already made this choice in a previous purchase, and was thus not shown the marketing right opt in/out checkbox during the Purchases on Google checkout flow. + #[serde(rename="explicitMarketingPreference")] + pub explicit_marketing_preference: Option, + /// Full name of the customer. + #[serde(rename="fullName")] + pub full_name: Option, + /// Email address of the customer. + pub email: Option, +} + +impl Part for OrderCustomer {} + + +/// 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, Serialize, Deserialize)] +pub struct AccountstatusesCustomBatchResponseEntry { + /// The ID of the request entry this entry responds to. + #[serde(rename="batchId")] + pub batch_id: Option, + /// A list of errors defined if and only if the request failed. + pub errors: Option, + /// The requested account status. Defined if and only if the request was successful. + #[serde(rename="accountStatus")] + pub account_status: Option, +} + +impl Part for AccountstatusesCustomBatchResponseEntry {} /// There is no detailed description. @@ -884,27 +2147,60 @@ impl ResponseResult for DatafeedsListResponse {} /// 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(rename="locationId")] - pub location_id: Option, - /// A free-form description of the service class or delivery speed. - pub service: Option, - /// 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(rename="postalCode")] - pub postal_code: Option, - /// The two-letter ISO 3166 country code for the country to which an item will ship. - pub country: Option, - /// Fixed shipping price, represented as a number. - pub price: Option, - /// The geographic region to which a shipping rate applies (e.g. zip code). - pub region: Option, - /// The location where the shipping is applicable, represented by a location group name. - #[serde(rename="locationGroupName")] - pub location_group_name: Option, +pub struct OrdersCustomBatchRequestEntryCancelLineItem { + /// The reason for the cancellation. + pub reason: Option, + /// The explanation of the reason. + #[serde(rename="reasonText")] + pub reason_text: Option, + /// The ID of the line item to cancel. + #[serde(rename="lineItemId")] + pub line_item_id: Option, + /// The quantity to cancel. + pub quantity: Option, } -impl Part for ProductShipping {} +impl Part for OrdersCustomBatchRequestEntryCancelLineItem {} + + +/// 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*). +/// +/// * [acknowledge orders](struct.OrderAcknowledgeCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct OrdersAcknowledgeRequest { + /// The ID of the operation. Unique across all operations for a given order. + #[serde(rename="operationId")] + pub operation_id: Option, +} + +impl RequestValue for OrdersAcknowledgeRequest {} + + +/// 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 OrdersCustomBatchRequestEntryReturnLineItem { + /// The reason for the return. + pub reason: Option, + /// The explanation of the reason. + #[serde(rename="reasonText")] + pub reason_text: Option, + /// The ID of the line item to return. + #[serde(rename="lineItemId")] + pub line_item_id: Option, + /// The quantity to return. + pub quantity: Option, +} + +impl Part for OrdersCustomBatchRequestEntryReturnLineItem {} /// The tax settings of a merchant account. @@ -933,28 +2229,40 @@ impl RequestValue for AccountTax {} impl ResponseResult for AccountTax {} -/// A batch entry encoding a single non-batch products request. +/// 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*). +/// +/// * [refund orders](struct.OrderRefundCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct OrdersRefundResponse { + /// Identifies what kind of resource this is. Value: the fixed string "content#ordersRefundResponse". + pub kind: Option, + /// The status of the execution. + #[serde(rename="executionStatus")] + pub execution_status: Option, +} + +impl ResponseResult for OrdersRefundResponse {} + + +/// 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 ProductsCustomBatchRequestEntry { - /// An entry ID, unique within the batch request. - #[serde(rename="batchId")] - pub batch_id: Option, - /// The product to insert. Only required if the method is insert. - pub product: Option, - /// The ID of the managing account. - #[serde(rename="merchantId")] - pub merchant_id: Option, - /// no description provided - pub method: Option, - /// The ID of the product to get or delete. Only defined if the method is get or delete. - #[serde(rename="productId")] - pub product_id: Option, +pub struct Weight { + /// The weight unit. + pub unit: Option, + /// The weight represented as a number. + pub value: Option, } -impl Part for ProductsCustomBatchRequestEntry {} +impl Part for Weight {} /// A batch entry encoding a single non-batch accounts response. @@ -984,35 +2292,15 @@ impl Part for AccountsCustomBatchResponseEntry {} /// This type is used in activities, which are methods you may call on this type or where 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) +/// * [custombatch accountstatuses](struct.AccountstatuseCustombatchCall.html) (request) /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] -pub struct AccountsCustomBatchRequest { +pub struct AccountstatusesCustomBatchRequest { /// The request entries to be processed in the batch. - pub entries: Option>, + 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, Serialize, Deserialize)] -pub struct ProductstatusesCustomBatchResponse { - /// Identifies what kind of resource this is. Value: the fixed string "content#productstatusesCustomBatchResponse". - pub kind: Option, - /// The result of the execution of the batch requests. - pub entries: Option>, -} - -impl ResponseResult for ProductstatusesCustomBatchResponse {} +impl RequestValue for AccountstatusesCustomBatchRequest {} /// A carrier-calculated shipping rate. @@ -1028,7 +2316,7 @@ pub struct AccountShippingCarrierRate { pub carrier: Option, /// The name of the carrier rate. pub name: Option, - /// Sale country for which this carrier rate is valid, represented as an ISO 3166-1 Alpha-2 code. + /// The sale country for which this carrier rate is valid, represented as a CLDR territory code. #[serde(rename="saleCountry")] pub sale_country: Option, /// The carrier service, such as "Ground" or "2Day". @@ -1077,7 +2365,7 @@ pub struct Datafeed { /// Fetch schedule for the feed file. #[serde(rename="fetchSchedule")] pub fetch_schedule: Option, - /// The two-letter ISO 3166 country where the items in the feed will be included in the search index. + /// The country where the items in the feed will be included in the search index, represented as a CLDR territory code. #[serde(rename="targetCountry")] pub target_country: Option, /// The filename of the feed. All feeds must have a unique file name. @@ -1098,29 +2386,37 @@ impl Resource for Datafeed {} impl ResponseResult for Datafeed {} -/// Shipping cost calculation method. Exactly one of the field is set. +/// 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 AccountShippingShippingServiceCalculationMethod { - /// Percentage of the price, represented as a floating point number without the percentage character. - #[serde(rename="percentageRate")] - pub percentage_rate: Option, - /// Name of the carrier rate to use for the calculation. - #[serde(rename="carrierRate")] - pub carrier_rate: Option, - /// Name of the rate table to use for the calculation. - #[serde(rename="rateTable")] - pub rate_table: Option, - /// Delivery is excluded. Valid only within cost rules tree. - pub excluded: Option, - /// Fixed price shipping, represented as a floating point number associated with a currency. - #[serde(rename="flatRate")] - pub flat_rate: Option, +pub struct TestOrder { + /// The details of the customer who placed the order. + pub customer: Option, + /// Identifies what kind of resource this is. Value: the fixed string "content#testOrder". + pub kind: Option, + /// Line items that are ordered. At least one line item must be provided. + #[serde(rename="lineItems")] + pub line_items: Option>, + /// Identifier of one of the predefined delivery addresses for the delivery. + #[serde(rename="predefinedDeliveryAddress")] + pub predefined_delivery_address: Option, + /// The total cost of shipping for all items. + #[serde(rename="shippingCost")] + pub shipping_cost: Option, + /// The requested shipping option. + #[serde(rename="shippingOption")] + pub shipping_option: Option, + /// The tax for the total shipping cost. + #[serde(rename="shippingCostTax")] + pub shipping_cost_tax: Option, + /// The details of the payment method. + #[serde(rename="paymentMethod")] + pub payment_method: Option, } -impl Part for AccountShippingShippingServiceCalculationMethod {} +impl Part for TestOrder {} /// There is no detailed description. @@ -1128,25 +2424,21 @@ impl Part for AccountShippingShippingServiceCalculationMethod {} /// 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: Option, - /// The numeric id of a location that the tax rate applies to as defined in the AdWords API. - #[serde(rename="locationId")] - pub location_id: Option, - /// 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(rename="postalCode")] - pub postal_code: Option, - /// The country within which the item is taxed, specified with a two-letter ISO 3166 country code. - pub country: Option, - /// The geographic region to which the tax rate applies. - pub region: Option, - /// Set to true if tax is charged on shipping. - #[serde(rename="taxShip")] - pub tax_ship: Option, +pub struct OrderLineItemShippingDetailsMethod { + /// Minimum transit time. + #[serde(rename="minDaysInTransit")] + pub min_days_in_transit: Option, + /// The carrier for the shipping. Optional. + pub carrier: Option, + /// The name of the shipping method. + #[serde(rename="methodName")] + pub method_name: Option, + /// Maximum transit time. + #[serde(rename="maxDaysInTransit")] + pub max_days_in_transit: Option, } -impl Part for ProductTax {} +impl Part for OrderLineItemShippingDetailsMethod {} /// There is no detailed description. @@ -1156,41 +2448,15 @@ impl Part for ProductTax {} /// This type is used in activities, which are methods you may call on this type or where 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) +/// * [advancetestorder orders](struct.OrderAdvancetestorderCall.html) (response) /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] -pub struct DatafeedstatusesCustomBatchResponse { - /// Identifies what kind of resource this is. Value: the fixed string "content#datafeedstatusesCustomBatchResponse". +pub struct OrdersAdvanceTestOrderResponse { + /// Identifies what kind of resource this is. Value: the fixed string "content#ordersAdvanceTestOrderResponse". pub kind: Option, - /// The result of the execution of the batch requests. - pub entries: Option>, } -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, Deserialize)] -pub struct AccountsCustomBatchRequestEntry { - /// An entry ID, unique within the batch request. - #[serde(rename="batchId")] - pub batch_id: Option, - /// The account to create or update. Only defined if the method is insert or update. - pub account: Option, - /// The ID of the account to get or delete. Only defined if the method is get or delete. - #[serde(rename="accountId")] - pub account_id: Option, - /// The ID of the managing account. - #[serde(rename="merchantId")] - pub merchant_id: Option, - /// no description provided - pub method: Option, -} - -impl Part for AccountsCustomBatchRequestEntry {} +impl ResponseResult for OrdersAdvanceTestOrderResponse {} /// There is no detailed description. @@ -1235,29 +2501,6 @@ pub struct ProductsCustomBatchRequest { 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, Serialize, Deserialize)] -pub struct DatafeedstatusesListResponse { - /// The token for the retrieval of the next page of datafeed statuses. - #[serde(rename="nextPageToken")] - pub next_page_token: Option, - /// Identifies what kind of resource this is. Value: the fixed string "content#datafeedstatusesListResponse". - pub kind: Option, - /// no description provided - pub resources: Option>, -} - -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. @@ -1273,26 +2516,6 @@ pub struct ProductUnitPricingMeasure { 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, Serialize, Deserialize)] -pub struct AccountstatusesCustomBatchResponse { - /// Identifies what kind of resource this is. Value: the fixed string "content#accountstatusesCustomBatchResponse". - pub kind: Option, - /// The result of the execution of the batch requests. - pub entries: Option>, -} - -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 @@ -1317,101 +2540,6 @@ pub struct AccountStatus { 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: Option, - /// The number of installments the buyer has to pay. - pub months: Option, -} - -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, Serialize, Deserialize)] -pub struct DatafeedstatusesCustomBatchResponseEntry { - /// The ID of the request entry this entry responds to. - #[serde(rename="batchId")] - pub batch_id: Option, - /// A list of errors defined if and only if the request failed. - pub errors: Option, - /// The requested data feed status. Defined if and only if the request was successful. - #[serde(rename="datafeedStatus")] - pub datafeed_status: Option, -} - -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, Deserialize)] -pub struct Inventory { - /// Identifies what kind of resource this is. Value: the fixed string "content#inventory". - pub kind: Option, - /// The sale price of the product. Mandatory if sale_price_effective_date is defined. - #[serde(rename="salePrice")] - pub sale_price: Option, - /// 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(rename="salePriceEffectiveDate")] - pub sale_price_effective_date: Option, - /// The price of the product. - pub price: Option, - /// The availability of the product. - pub availability: Option, - /// The quantity of the product. Must be equal to or greater than zero. Supported only for local products. - pub quantity: Option, -} - -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: Option>, - /// Sale country for which this table is valid, represented as an ISO 3166-1 Alpha-2 code. - #[serde(rename="saleCountry")] - pub sale_country: Option, - /// The name of the rate table. - pub name: Option, -} - -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, Serialize, Deserialize)] -pub struct ProductStatusDestinationStatus { - /// The destination's approval status. - #[serde(rename="approvalStatus")] - pub approval_status: Option, - /// The name of the destination - pub destination: Option, - /// Whether the destination is required, excluded, selected by default or should be validated. - pub intention: Option, -} - -impl Part for ProductStatusDestinationStatus {} - - /// There is no detailed description. /// /// # Activities @@ -1419,15 +2547,40 @@ impl Part for ProductStatusDestinationStatus {} /// This type is used in activities, which are methods you may call on this type or where 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) +/// * [custombatch orders](struct.OrderCustombatchCall.html) (request) /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] -pub struct AccounttaxCustomBatchRequest { +pub struct OrdersCustomBatchRequest { /// The request entries to be processed in the batch. - pub entries: Option>, + pub entries: Option>, } -impl RequestValue for AccounttaxCustomBatchRequest {} +impl RequestValue for OrdersCustomBatchRequest {} + + +/// 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(rename="percentageRate")] + pub percentage_rate: Option, + /// Name of the carrier rate to use for the calculation. + #[serde(rename="carrierRate")] + pub carrier_rate: Option, + /// Name of the rate table to use for the calculation. + #[serde(rename="rateTable")] + pub rate_table: Option, + /// Delivery is excluded. Valid only within cost rules tree. + pub excluded: Option, + /// Fixed price shipping, represented as a floating point number associated with a currency. + #[serde(rename="flatRate")] + pub flat_rate: Option, +} + +impl Part for AccountShippingShippingServiceCalculationMethod {} /// A batch entry encoding a single non-batch inventory request. @@ -1457,22 +2610,81 @@ 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) +/// This type is not used in any activity, and only used as *part* of another schema. /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] -pub struct ProductsCustomBatchResponse { - /// Identifies what kind of resource this is. Value: the fixed string "content#productsCustomBatchResponse". - pub kind: Option, - /// The result of the execution of the batch requests. - pub entries: Option>, +pub struct OrderShipment { + /// The status of the shipment. + pub status: Option, + /// Date on which the shipment has been created, in ISO 8601 format. + #[serde(rename="creationDate")] + pub creation_date: Option, + /// The carrier handling the shipment. + pub carrier: Option, + /// The tracking id for the shipment. + #[serde(rename="trackingId")] + pub tracking_id: Option, + /// Date on which the shipment has been delivered, in ISO 8601 format. Present only if status is delievered + #[serde(rename="deliveryDate")] + pub delivery_date: Option, + /// The line items that are shipped. + #[serde(rename="lineItems")] + pub line_items: Option>, + /// The id of the shipment. + pub id: Option, } -impl ResponseResult for ProductsCustomBatchResponse {} +impl Part for OrderShipment {} + + +/// 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 TestOrderLineItem { + /// Details of the return policy for the line item. + #[serde(rename="returnInfo")] + pub return_info: Option, + /// Product data from the time of the order placement. + pub product: Option, + /// Unit tax for the line item. + #[serde(rename="unitTax")] + pub unit_tax: Option, + /// Number of items ordered. + #[serde(rename="quantityOrdered")] + pub quantity_ordered: Option, + /// Details of the requested shipping for the line item. + #[serde(rename="shippingDetails")] + pub shipping_details: Option, +} + +impl Part for TestOrderLineItem {} + + +/// 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, Deserialize)] +pub struct AccounttaxCustomBatchRequestEntry { + /// An entry ID, unique within the batch request. + #[serde(rename="batchId")] + pub batch_id: Option, + /// The account tax settings to update. Only defined if the method is update. + #[serde(rename="accountTax")] + pub account_tax: Option, + /// The ID of the account for which to get/update account tax settings. + #[serde(rename="accountId")] + pub account_id: Option, + /// The ID of the managing account. + #[serde(rename="merchantId")] + pub merchant_id: Option, + /// no description provided + pub method: Option, +} + +impl Part for AccounttaxCustomBatchRequestEntry {} /// There is no detailed description. @@ -1522,26 +2734,63 @@ pub struct AccountStatusExampleItem { impl Part for AccountStatusExampleItem {} -/// A batch entry encoding a single non-batch productstatuses request. +/// 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, Serialize, Deserialize)] +pub struct AccountsCustomBatchResponse { + /// Identifies what kind of resource this is. Value: the fixed string "content#accountsCustomBatchResponse". + pub kind: Option, + /// The result of the execution of the batch requests. + pub entries: Option>, +} + +impl ResponseResult for AccountsCustomBatchResponse {} + + +/// 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, Serialize, Deserialize)] +pub struct InventoryCustomBatchResponse { + /// Identifies what kind of resource this is. Value: the fixed string "content#inventoryCustomBatchResponse". + pub kind: Option, + /// The result of the execution of the batch requests. + pub entries: Option>, +} + +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 ProductstatusesCustomBatchRequestEntry { - /// An entry ID, unique within the batch request. - #[serde(rename="batchId")] - pub batch_id: Option, - /// The ID of the managing account. - #[serde(rename="merchantId")] - pub merchant_id: Option, - /// no description provided - pub method: Option, - /// The ID of the product whose status to get. - #[serde(rename="productId")] - pub product_id: Option, +pub struct OrderLineItemShippingDetails { + /// The delivery by date, in ISO 8601 format. + #[serde(rename="deliverByDate")] + pub deliver_by_date: Option, + /// Details of the shipping method. + pub method: Option, + /// The ship by date, in ISO 8601 format. + #[serde(rename="shipByDate")] + pub ship_by_date: Option, } -impl Part for ProductstatusesCustomBatchRequestEntry {} +impl Part for OrderLineItemShippingDetails {} /// There is no detailed description. @@ -1559,23 +2808,71 @@ pub struct Price { impl Part for Price {} -/// An error occurring in the feed, like "invalid 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*). +/// +/// * [cancel orders](struct.OrderCancelCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct OrdersCancelRequest { + /// The reason for the cancellation. + pub reason: Option, + /// The explanation of the reason. + #[serde(rename="reasonText")] + pub reason_text: Option, + /// The ID of the operation. Unique across all operations for a given order. + #[serde(rename="operationId")] + pub operation_id: Option, +} + +impl RequestValue for OrdersCancelRequest {} + + +/// 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 DatafeedStatusError { - /// The number of occurrences of the error in the feed. - pub count: Option, - /// The error message, e.g., "Invalid price". - pub message: Option, - /// The code of the error, e.g., "validation/invalid_value". - pub code: Option, - /// A list of example occurrences of the error, grouped by product. - pub examples: Option>, +pub struct TestOrderLineItemProduct { + /// The CLDR territory code of the target country of the product. + #[serde(rename="targetCountry")] + pub target_country: Option, + /// The two-letter ISO 639-1 language code for the item. + #[serde(rename="contentLanguage")] + pub content_language: Option, + /// The title of the product. + pub title: Option, + /// Manufacturer Part Number (MPN) of the item. Optional. + pub mpn: Option, + /// Variant attributes for the item. Optional. + #[serde(rename="variantAttributes")] + pub variant_attributes: Option>, + /// Brand of the item. + pub brand: Option, + /// URL of an image of the item. + #[serde(rename="imageLink")] + pub image_link: Option, + /// An identifier of the item. + #[serde(rename="offerId")] + pub offer_id: Option, + /// Shared identifier for all variants of the same product. Optional. + #[serde(rename="itemGroupId")] + pub item_group_id: Option, + /// Global Trade Item Number (GTIN) of the item. Optional. + pub gtin: Option, + /// Condition or state of the item. + pub condition: Option, + /// The price for the product. + pub price: Option, + /// The item's channel. + pub channel: Option, } -impl Part for DatafeedStatusError {} +impl Part for TestOrderLineItemProduct {} /// An example occurrence for a particular error. @@ -1597,6 +2894,35 @@ pub struct DatafeedStatusExample { impl Part for DatafeedStatusExample {} +/// 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*). +/// +/// * [returnlineitem orders](struct.OrderReturnlineitemCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct OrdersReturnLineItemRequest { + /// The ID of the operation. Unique across all operations for a given order. + #[serde(rename="operationId")] + pub operation_id: Option, + /// The reason for the return. + pub reason: Option, + /// The explanation of the reason. + #[serde(rename="reasonText")] + pub reason_text: Option, + /// The ID of the line item to return. + #[serde(rename="lineItemId")] + pub line_item_id: Option, + /// The quantity to return. + pub quantity: Option, +} + +impl RequestValue for OrdersReturnLineItemRequest {} + + /// There is no detailed description. /// /// This type is not used in any activity, and only used as *part* of another schema. @@ -1612,31 +2938,6 @@ pub struct ProductShippingWeight { 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, Deserialize)] -pub struct AccounttaxCustomBatchRequestEntry { - /// An entry ID, unique within the batch request. - #[serde(rename="batchId")] - pub batch_id: Option, - /// The account tax settings to update. Only defined if the method is update. - #[serde(rename="accountTax")] - pub account_tax: Option, - /// The ID of the account for which to get/update account tax settings. - #[serde(rename="accountId")] - pub account_id: Option, - /// The ID of the managing account. - #[serde(rename="merchantId")] - pub merchant_id: Option, - /// no description provided - pub method: Option, -} - -impl Part for AccounttaxCustomBatchRequestEntry {} - - /// The shipping settings of a merchant account. /// /// # Activities @@ -1672,21 +2973,6 @@ 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: Option, - /// The denominator of the unit price. - pub value: Option, -} - -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. @@ -1712,26 +2998,6 @@ pub struct AccountTaxTaxRule { 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: Option, - /// The type of the attribute. - #[serde(rename="type")] - pub type_: Option, - /// The name of the attribute. Underscores will be replaced by spaces upon insertion. - pub name: Option, - /// The value of the attribute. - pub value: Option, -} - -impl Part for ProductCustomAttribute {} - - /// There is no detailed description. /// /// # Activities @@ -1755,38 +3021,6 @@ pub struct AccountstatusesListResponse { 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(rename="weightMax")] - pub weight_max: Option, - /// Delivery location in terms of a location ID. Can be used to represent administrative areas, smaller country subdivisions, or cities. - #[serde(rename="deliveryLocationId")] - pub delivery_location_id: Option, - /// Shipping label of the product. The products with the label are matched. - #[serde(rename="shippingLabel")] - pub shipping_label: Option, - /// Delivery location in terms of a location group name. A location group with this name must be specified among location groups. - #[serde(rename="deliveryLocationGroup")] - pub delivery_location_group: Option, - /// Delivery location in terms of a postal code. - #[serde(rename="deliveryPostalCode")] - pub delivery_postal_code: Option, - /// Maximum shipping price. Forms an interval between the maximum of smaller prices (exclusive) and this price (inclusive). - #[serde(rename="priceMax")] - pub price_max: Option, - /// Delivery location in terms of a postal code range. - #[serde(rename="deliveryPostalCodeRange")] - pub delivery_postal_code_range: Option, -} - -impl Part for AccountShippingCondition {} - - /// There is no detailed description. /// /// # Activities @@ -1794,15 +3028,17 @@ impl Part for AccountShippingCondition {} /// This type is used in activities, which are methods you may call on this type or where 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) +/// * [custombatch orders](struct.OrderCustombatchCall.html) (response) /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] -pub struct InventoryCustomBatchRequest { - /// The request entries to be processed in the batch. - pub entries: Option>, +pub struct OrdersCustomBatchResponse { + /// Identifies what kind of resource this is. Value: the fixed string "content#ordersCustomBatchResponse". + pub kind: Option, + /// The result of the execution of the batch requests. + pub entries: Option>, } -impl RequestValue for InventoryCustomBatchRequest {} +impl ResponseResult for OrdersCustomBatchResponse {} /// Product data. @@ -1840,7 +3076,7 @@ pub struct Product { pub adwords_grouping: Option, /// Specifies the intended destinations for the product. pub destinations: Option>, - /// The two-letter ISO 3166 country code for the item. + /// The CLDR territory code for the item. #[serde(rename="targetCountry")] pub target_country: Option, /// Custom label 4 for custom grouping of items in a Shopping campaign. @@ -1976,6 +3212,9 @@ pub struct Product { /// Length of the item for shipping. #[serde(rename="shippingLength")] pub shipping_length: Option, + /// The quantity of the product that is reserved for sell-on-google ads. + #[serde(rename="sellOnGoogleQuantity")] + pub sell_on_google_quantity: Option, /// URL directly to your item's landing page for dynamic remarketing campaigns. #[serde(rename="displayAdsLink")] pub display_ads_link: Option, @@ -2009,36 +3248,6 @@ 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, Serialize, Deserialize)] -pub struct ProductStatusDataQualityIssue { - /// The value the attribute had at time of evaluation. - #[serde(rename="valueProvided")] - pub value_provided: Option, - /// The severity of the data quality issue. - pub severity: Option, - /// The time stamp of the data quality issue. - pub timestamp: Option, - /// A more detailed error string. - pub detail: Option, - /// The attribute name that is relevant for the issue. - pub location: Option, - /// The value of that attribute that was found on the landing page - #[serde(rename="valueOnLandingPage")] - pub value_on_landing_page: Option, - /// The id of the data quality issue. - pub id: Option, - /// The fetch status for landing_page_errors. - #[serde(rename="fetchStatus")] - pub fetch_status: Option, -} - -impl Part for ProductStatusDataQualityIssue {} - - /// There is no detailed description. /// /// # Activities @@ -2062,51 +3271,6 @@ pub struct ProductsListResponse { 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: Option, - /// Decision tree for "complicated" shipping cost calculation. - #[serde(rename="costRuleTree")] - pub cost_rule_tree: Option, - /// Sale country for which this service can be used, represented as an ISO 3166-1 Alpha-2 code. - #[serde(rename="saleCountry")] - pub sale_country: Option, - /// Calculation method for the "simple" case that needs no rules. - #[serde(rename="calculationMethod")] - pub calculation_method: Option, - /// The name of this shipping service. - pub name: Option, -} - -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, Serialize, Deserialize)] -pub struct AccountshippingCustomBatchResponseEntry { - /// The ID of the request entry this entry responds to. - #[serde(rename="batchId")] - pub batch_id: Option, - /// Identifies what kind of resource this is. Value: the fixed string "content#accountshippingCustomBatchResponseEntry". - pub kind: Option, - /// A list of errors defined if and only if the request failed. - pub errors: Option, - /// The retrieved or updated account shipping settings. - #[serde(rename="accountShipping")] - pub account_shipping: Option, -} - -impl Part for AccountshippingCustomBatchResponseEntry {} - - /// There is no detailed description. /// /// # Activities @@ -2118,59 +3282,26 @@ impl Part for AccountshippingCustomBatchResponseEntry {} /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct InventorySetRequest { + /// The quantity of the product that is reserved for sell-on-google ads. Supported only for online products. + #[serde(rename="sellOnGoogleQuantity")] + pub sell_on_google_quantity: Option, + /// The sale price of the product. Mandatory if sale_price_effective_date is defined. + #[serde(rename="salePrice")] + pub sale_price: Option, /// 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(rename="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(rename="salePrice")] - pub sale_price: Option, + /// The quantity of the product. Must be equal to or greater than zero. Supported only for local products. + pub quantity: 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: Option, - /// The name of the destination. - #[serde(rename="destinationName")] - pub destination_name: Option, -} - -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, Serialize, Deserialize)] -pub struct AccountsCustomBatchResponse { - /// Identifies what kind of resource this is. Value: the fixed string "content#accountsCustomBatchResponse". - pub kind: Option, - /// The result of the execution of the batch requests. - pub entries: Option>, -} - -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. @@ -2195,6 +3326,84 @@ pub struct DatafeedsCustomBatchRequestEntry { 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*). +/// +/// * [get orders](struct.OrderGetCall.html) (response) +/// * [list orders](struct.OrderListCall.html) (none) +/// * [updateshipment orders](struct.OrderUpdateshipmentCall.html) (none) +/// * [advancetestorder orders](struct.OrderAdvancetestorderCall.html) (none) +/// * [updatemerchantorderid orders](struct.OrderUpdatemerchantorderidCall.html) (none) +/// * [returnlineitem orders](struct.OrderReturnlineitemCall.html) (none) +/// * [gettestordertemplate orders](struct.OrderGettestordertemplateCall.html) (none) +/// * [createtestorder orders](struct.OrderCreatetestorderCall.html) (none) +/// * [refund orders](struct.OrderRefundCall.html) (none) +/// * [custombatch orders](struct.OrderCustombatchCall.html) (none) +/// * [cancellineitem orders](struct.OrderCancellineitemCall.html) (none) +/// * [getbymerchantorderid orders](struct.OrderGetbymerchantorderidCall.html) (none) +/// * [acknowledge orders](struct.OrderAcknowledgeCall.html) (none) +/// * [cancel orders](struct.OrderCancelCall.html) (none) +/// * [shiplineitems orders](struct.OrderShiplineitemCall.html) (none) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Order { + /// Shipments of the order. + pub shipments: Option>, + /// The status of the order. + pub status: Option, + /// The status of the payment. + #[serde(rename="paymentStatus")] + pub payment_status: Option, + /// The net amount for the order. For example, if an order was originally for a grand total of $100 and a refund was issued for $20, the net amount will be $80. + #[serde(rename="netAmount")] + pub net_amount: Option, + /// The REST id of the order. Globally unique. + pub id: Option, + /// The details of the customer who placed the order. + pub customer: Option, + /// Identifies what kind of resource this is. Value: the fixed string "content#order". + pub kind: Option, + /// Line items that are ordered. + #[serde(rename="lineItems")] + pub line_items: Option>, + /// Refunds for the order. + pub refunds: Option>, + /// Whether the order was acknowledged. + pub acknowledged: Option, + /// The total cost of shipping for all items. + #[serde(rename="shippingCost")] + pub shipping_cost: Option, + /// no description provided + #[serde(rename="merchantId")] + pub merchant_id: Option, + /// Merchant-provided id of the order. + #[serde(rename="merchantOrderId")] + pub merchant_order_id: Option, + /// The requested shipping option. + #[serde(rename="shippingOption")] + pub shipping_option: Option, + /// The details for the delivery. + #[serde(rename="deliveryDetails")] + pub delivery_details: Option, + /// The date when the order was placed, in ISO 8601 format. + #[serde(rename="placedDate")] + pub placed_date: Option, + /// The tax for the total shipping cost. + #[serde(rename="shippingCostTax")] + pub shipping_cost_tax: Option, + /// The details of the payment method. + #[serde(rename="paymentMethod")] + pub payment_method: Option, +} + +impl Resource for Order {} +impl ResponseResult for Order {} + + /// There is no detailed description. /// /// # Activities @@ -2218,19 +3427,89 @@ pub struct ProductstatusesListResponse { impl ResponseResult for ProductstatusesListResponse {} +/// 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*). +/// +/// * [cancel orders](struct.OrderCancelCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct OrdersCancelResponse { + /// Identifies what kind of resource this is. Value: the fixed string "content#ordersCancelResponse". + pub kind: Option, + /// The status of the execution. + #[serde(rename="executionStatus")] + pub execution_status: Option, +} + +impl ResponseResult for OrdersCancelResponse {} + + +/// 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*). +/// +/// * [returnlineitem orders](struct.OrderReturnlineitemCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct OrdersReturnLineItemResponse { + /// Identifies what kind of resource this is. Value: the fixed string "content#ordersReturnLineItemResponse". + pub kind: Option, + /// The status of the execution. + #[serde(rename="executionStatus")] + pub execution_status: Option, +} + +impl ResponseResult for OrdersReturnLineItemResponse {} + + +/// 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*). +/// +/// * [acknowledge orders](struct.OrderAcknowledgeCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct OrdersAcknowledgeResponse { + /// Identifies what kind of resource this is. Value: the fixed string "content#ordersAcknowledgeResponse". + pub kind: Option, + /// The status of the execution. + #[serde(rename="executionStatus")] + pub execution_status: Option, +} + +impl ResponseResult for OrdersAcknowledgeResponse {} + + /// 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: Option, - /// The weight represented as a number. - pub value: Option, +pub struct OrdersCustomBatchRequestEntryShipLineItems { + /// Line items to ship. + #[serde(rename="lineItems")] + pub line_items: Option>, + /// The carrier handling the shipment. + pub carrier: Option, + /// The tracking id for the shipment. + #[serde(rename="trackingId")] + pub tracking_id: Option, + /// The ID of the shipment. + #[serde(rename="shipmentId")] + pub shipment_id: Option, } -impl Part for Weight {} +impl Part for OrdersCustomBatchRequestEntryShipLineItems {} /// There is no detailed description. @@ -2265,6 +3544,35 @@ pub struct AccountStatusDataQualityIssue { impl Part for AccountStatusDataQualityIssue {} +/// 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 OrderPaymentMethod { + /// The card expiration month (January = 1, February = 2 etc.). + #[serde(rename="expirationMonth")] + pub expiration_month: Option, + /// The card expiration year (4-digit, e.g. 2015). + #[serde(rename="expirationYear")] + pub expiration_year: Option, + /// The billing phone number. + #[serde(rename="phoneNumber")] + pub phone_number: Option, + /// The billing address. + #[serde(rename="billingAddress")] + pub billing_address: Option, + /// The type of instrument (VISA, Mastercard, etc). + #[serde(rename="type")] + pub type_: Option, + /// The last four digits of the card number. + #[serde(rename="lastFourDigits")] + pub last_four_digits: Option, +} + +impl Part for OrderPaymentMethod {} + + /// There is no detailed description. /// /// # Activities @@ -2309,22 +3617,25 @@ pub struct ProductstatusesCustomBatchResponseEntry { impl Part for ProductstatusesCustomBatchResponseEntry {} -/// There is no detailed description. +/// A batch entry encoding a single non-batch accounttax 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*). -/// -/// * [custombatch accountshipping](struct.AccountshippingCustombatchCall.html) (request) +/// This type is not used in any activity, and only used as *part* of another schema. /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] -pub struct AccountshippingCustomBatchRequest { - /// The request entries to be processed in the batch. - pub entries: Option>, +pub struct AccounttaxCustomBatchResponseEntry { + /// The ID of the request entry this entry responds to. + #[serde(rename="batchId")] + pub batch_id: Option, + /// The retrieved or updated account tax settings. + #[serde(rename="accountTax")] + pub account_tax: Option, + /// A list of errors defined if and only if the request failed. + pub errors: Option, + /// Identifies what kind of resource this is. Value: the fixed string "content#accounttaxCustomBatchResponseEntry". + pub kind: Option, } -impl RequestValue for AccountshippingCustomBatchRequest {} +impl Part for AccounttaxCustomBatchResponseEntry {} /// There is no detailed description. @@ -2332,17 +3643,37 @@ impl RequestValue for AccountshippingCustomBatchRequest {} /// 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: Option, - /// Name of loyalty points program. It is recommended to limit the name to 12 full-width characters or 24 Roman characters. - pub name: Option, - /// The retailer's loyalty points in absolute value. - #[serde(rename="pointsValue")] - pub points_value: Option, +pub struct OrdersCustomBatchResponseEntry { + /// The ID of the request entry this entry responds to. + #[serde(rename="batchId")] + pub batch_id: Option, + /// Identifies what kind of resource this is. Value: the fixed string "content#ordersCustomBatchResponseEntry". + pub kind: Option, + /// A list of errors defined if and only if the request failed. + pub errors: Option, + /// The retrieved order. Only defined if the method is get and if the request was successful. + pub order: Option, + /// The status of the execution. Only defined if the method is not get or getByMerchantOrderId and if the request was successful. + #[serde(rename="executionStatus")] + pub execution_status: Option, } -impl Part for LoyaltyPoints {} +impl Part for OrdersCustomBatchResponseEntry {} + + +/// 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: Option, + /// The denominator of the unit price. + pub value: Option, +} + +impl Part for ProductUnitPricingBaseMeasure {} /// There is no detailed description. @@ -2352,15 +3683,26 @@ impl Part for LoyaltyPoints {} /// This type is used in activities, which are methods you may call on this type or where 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) +/// * [updateshipment orders](struct.OrderUpdateshipmentCall.html) (request) /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] -pub struct DatafeedsCustomBatchRequest { - /// The request entries to be processed in the batch. - pub entries: Option>, +pub struct OrdersUpdateShipmentRequest { + /// New status for the shipment. Not updated if missing. + pub status: Option, + /// The carrier handling the shipment. Not updated if missing. + pub carrier: Option, + /// The ID of the operation. Unique across all operations for a given order. + #[serde(rename="operationId")] + pub operation_id: Option, + /// The tracking id for the shipment. Not updated if missing. + #[serde(rename="trackingId")] + pub tracking_id: Option, + /// The ID of the shipment. + #[serde(rename="shipmentId")] + pub shipment_id: Option, } -impl RequestValue for DatafeedsCustomBatchRequest {} +impl RequestValue for OrdersUpdateShipmentRequest {} /// There is no detailed description. @@ -2383,6 +3725,26 @@ pub struct DatafeedFormat { 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 OrderLineItemReturnInfo { + /// URL of the item return policy. + #[serde(rename="policyUrl")] + pub policy_url: Option, + /// Whether the item is returnable. + #[serde(rename="isReturnable")] + pub is_returnable: Option, + /// How many days later the item can be returned. + #[serde(rename="daysToReturn")] + pub days_to_return: Option, +} + +impl Part for OrderLineItemReturnInfo {} + + /// There is no detailed description. /// /// This type is not used in any activity, and only used as *part* of another schema. @@ -2399,23 +3761,6 @@ pub struct AccountAdwordsLink { 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: Option, - /// The last (inclusive) postal code or prefix of the range. - pub end: Option, -} - -impl Part for AccountShippingPostalCodeRange {} - - // ################### // MethodBuilders ### @@ -3162,7 +4507,7 @@ impl<'a, C, A> InventoryMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Updates price and availability of a product in your Merchant Center account. + /// Updates price and availability of a product in your Merchant Center account. This operation does not update the expiration date of the product. /// /// # Arguments /// @@ -3186,7 +4531,7 @@ impl<'a, C, A> InventoryMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Updates price and availability for multiple products or stores in a single request. + /// Updates price and availability for multiple products or stores in a single request. This operation does not update the expiration date of the products. /// /// # Arguments /// @@ -3576,6 +4921,351 @@ impl<'a, C, A> AccountshippingMethods<'a, C, A> { +/// A builder providing access to all methods supported on *order* 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 `acknowledge(...)`, `advancetestorder(...)`, `cancel(...)`, `cancellineitem(...)`, `createtestorder(...)`, `custombatch(...)`, `get(...)`, `getbymerchantorderid(...)`, `gettestordertemplate(...)`, `list(...)`, `refund(...)`, `returnlineitem(...)`, `shiplineitems(...)`, `updatemerchantorderid(...)` and `updateshipment(...)` +/// // to build up your call. +/// let rb = hub.orders(); +/// # } +/// ``` +pub struct OrderMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a ShoppingContent, +} + +impl<'a, C, A> MethodsBuilder for OrderMethods<'a, C, A> {} + +impl<'a, C, A> OrderMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Lists the orders in your Merchant Center account. + /// + /// # Arguments + /// + /// * `merchantId` - The ID of the managing account. + pub fn list(&self, merchant_id: &str) -> OrderListCall<'a, C, A> { + OrderListCall { + hub: self.hub, + _merchant_id: merchant_id.to_string(), + _statuses: Default::default(), + _placed_date_start: Default::default(), + _placed_date_end: Default::default(), + _page_token: Default::default(), + _order_by: Default::default(), + _max_results: Default::default(), + _acknowledged: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Sandbox only. Retrieves an order template that can be used to quickly create a new order in sandbox. + /// + /// # Arguments + /// + /// * `merchantId` - The ID of the managing account. + /// * `templateName` - The name of the template to retrieve. + pub fn gettestordertemplate(&self, merchant_id: &str, template_name: &str) -> OrderGettestordertemplateCall<'a, C, A> { + OrderGettestordertemplateCall { + hub: self.hub, + _merchant_id: merchant_id.to_string(), + _template_name: template_name.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves an order from your Merchant Center account. + /// + /// # Arguments + /// + /// * `merchantId` - The ID of the managing account. + /// * `orderId` - The ID of the order. + pub fn get(&self, merchant_id: &str, order_id: &str) -> OrderGetCall<'a, C, A> { + OrderGetCall { + hub: self.hub, + _merchant_id: merchant_id.to_string(), + _order_id: order_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Refund a portion of the order, up to the full amount paid. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `merchantId` - The ID of the managing account. + /// * `orderId` - The ID of the order to refund. + pub fn refund(&self, request: OrdersRefundRequest, merchant_id: &str, order_id: &str) -> OrderRefundCall<'a, C, A> { + OrderRefundCall { + hub: self.hub, + _request: request, + _merchant_id: merchant_id.to_string(), + _order_id: order_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Marks an order as acknowledged. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `merchantId` - The ID of the managing account. + /// * `orderId` - The ID of the order. + pub fn acknowledge(&self, request: OrdersAcknowledgeRequest, merchant_id: &str, order_id: &str) -> OrderAcknowledgeCall<'a, C, A> { + OrderAcknowledgeCall { + hub: self.hub, + _request: request, + _merchant_id: merchant_id.to_string(), + _order_id: order_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 merchant order ID for a given order. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `merchantId` - The ID of the managing account. + /// * `orderId` - The ID of the order. + pub fn updatemerchantorderid(&self, request: OrdersUpdateMerchantOrderIdRequest, merchant_id: &str, order_id: &str) -> OrderUpdatemerchantorderidCall<'a, C, A> { + OrderUpdatemerchantorderidCall { + hub: self.hub, + _request: request, + _merchant_id: merchant_id.to_string(), + _order_id: order_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Sandbox only. Moves a test order from state "inProgress" to state "pendingShipment". + /// + /// # Arguments + /// + /// * `merchantId` - The ID of the managing account. + /// * `orderId` - The ID of the test order to modify. + pub fn advancetestorder(&self, merchant_id: &str, order_id: &str) -> OrderAdvancetestorderCall<'a, C, A> { + OrderAdvancetestorderCall { + hub: self.hub, + _merchant_id: merchant_id.to_string(), + _order_id: order_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Sandbox only. Creates a test order. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `merchantId` - The ID of the managing account. + pub fn createtestorder(&self, request: OrdersCreateTestOrderRequest, merchant_id: &str) -> OrderCreatetestorderCall<'a, C, A> { + OrderCreatetestorderCall { + hub: self.hub, + _request: request, + _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: + /// + /// Returns a line item. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `merchantId` - The ID of the managing account. + /// * `orderId` - The ID of the order. + pub fn returnlineitem(&self, request: OrdersReturnLineItemRequest, merchant_id: &str, order_id: &str) -> OrderReturnlineitemCall<'a, C, A> { + OrderReturnlineitemCall { + hub: self.hub, + _request: request, + _merchant_id: merchant_id.to_string(), + _order_id: order_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves an order using merchant order id. + /// + /// # Arguments + /// + /// * `merchantId` - The ID of the managing account. + /// * `merchantOrderId` - The merchant order id to be looked for. + pub fn getbymerchantorderid(&self, merchant_id: &str, merchant_order_id: &str) -> OrderGetbymerchantorderidCall<'a, C, A> { + OrderGetbymerchantorderidCall { + hub: self.hub, + _merchant_id: merchant_id.to_string(), + _merchant_order_id: merchant_order_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves or modifies multiple orders in a single request. + /// + /// # Arguments + /// + /// * `request` - No description provided. + pub fn custombatch(&self, request: OrdersCustomBatchRequest) -> OrderCustombatchCall<'a, C, A> { + OrderCustombatchCall { + hub: self.hub, + _request: request, + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Marks line item(s) as shipped. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `merchantId` - The ID of the managing account. + /// * `orderId` - The ID of the order. + pub fn shiplineitems(&self, request: OrdersShipLineItemsRequest, merchant_id: &str, order_id: &str) -> OrderShiplineitemCall<'a, C, A> { + OrderShiplineitemCall { + hub: self.hub, + _request: request, + _merchant_id: merchant_id.to_string(), + _order_id: order_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 shipment's status, carrier, and/or tracking ID. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `merchantId` - The ID of the managing account. + /// * `orderId` - The ID of the order. + pub fn updateshipment(&self, request: OrdersUpdateShipmentRequest, merchant_id: &str, order_id: &str) -> OrderUpdateshipmentCall<'a, C, A> { + OrderUpdateshipmentCall { + hub: self.hub, + _request: request, + _merchant_id: merchant_id.to_string(), + _order_id: order_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Cancels a line item. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `merchantId` - The ID of the managing account. + /// * `orderId` - The ID of the order. + pub fn cancellineitem(&self, request: OrdersCancelLineItemRequest, merchant_id: &str, order_id: &str) -> OrderCancellineitemCall<'a, C, A> { + OrderCancellineitemCall { + hub: self.hub, + _request: request, + _merchant_id: merchant_id.to_string(), + _order_id: order_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Cancels all line items in an order. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `merchantId` - The ID of the managing account. + /// * `orderId` - The ID of the order to cancel. + pub fn cancel(&self, request: OrdersCancelRequest, merchant_id: &str, order_id: &str) -> OrderCancelCall<'a, C, A> { + OrderCancelCall { + hub: self.hub, + _request: request, + _merchant_id: merchant_id.to_string(), + _order_id: order_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + // ################### @@ -4146,8 +5836,8 @@ impl<'a, C, A> AccounttaxPatchCall<'a, C, A> where C: BorrowMut, /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.accounttax().list("merchantId") -/// .page_token("erat") -/// .max_results(66) +/// .page_token("justo") +/// .max_results(80) /// .doit(); /// # } /// ``` @@ -5191,8 +6881,8 @@ impl<'a, C, A> DatafeedstatuseGetCall<'a, C, A> where C: BorrowMut DatafeedstatuseCustombatchCall<'a, C, A> where C: BorrowMut DatafeedDeleteCall<'a, C, A> where C: BorrowMut, A /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.datafeeds().insert(req, "merchantId") -/// .dry_run(false) +/// .dry_run(true) /// .doit(); /// # } /// ``` @@ -6987,8 +8677,8 @@ impl<'a, C, A> DatafeedInsertCall<'a, C, A> where C: BorrowMut, A /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.datafeeds().list("merchantId") -/// .page_token("sadipscing") -/// .max_results(53) +/// .page_token("aliquyam") +/// .max_results(28) /// .doit(); /// # } /// ``` @@ -7253,7 +8943,7 @@ impl<'a, C, A> DatafeedListCall<'a, C, A> where C: BorrowMut, A: /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.datafeeds().update(req, "merchantId", "datafeedId") -/// .dry_run(false) +/// .dry_run(true) /// .doit(); /// # } /// ``` @@ -7784,8 +9474,8 @@ impl<'a, C, A> ProductstatuseGetCall<'a, C, A> where C: BorrowMut /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.productstatuses().list("merchantId") -/// .page_token("dolore") -/// .max_results(64) +/// .page_token("sanctus") +/// .max_results(79) /// .doit(); /// # } /// ``` @@ -8487,7 +10177,7 @@ impl<'a, C, A> AccountAuthinfoCall<'a, C, A> where C: BorrowMut, /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.accounts().patch(req, "merchantId", "accountId") -/// .dry_run(false) +/// .dry_run(true) /// .doit(); /// # } /// ``` @@ -9312,7 +11002,7 @@ impl<'a, C, A> AccountUpdateCall<'a, C, A> where C: BorrowMut, A: /// // Values shown here are possibly random and not representative ! /// let result = hub.accounts().list("merchantId") /// .page_token("et") -/// .max_results(55) +/// .max_results(5) /// .doit(); /// # } /// ``` @@ -9571,7 +11261,7 @@ impl<'a, C, A> AccountListCall<'a, C, A> where C: BorrowMut, A: o /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.accounts().delete("merchantId", "accountId") -/// .dry_run(true) +/// .dry_run(false) /// .doit(); /// # } /// ``` @@ -10072,7 +11762,7 @@ impl<'a, C, A> AccountCustombatchCall<'a, C, A> where C: BorrowMut AccountInsertCall<'a, C, A> where C: BorrowMut, A: } -/// Updates price and availability of a product in your Merchant Center account. +/// Updates price and availability of a product in your Merchant Center account. This operation does not update the expiration date of the product. /// /// A builder for the *set* method supported by a *inventory* resource. /// It is not used directly, but through a `InventoryMethods` instance. @@ -10351,7 +12041,7 @@ impl<'a, C, A> AccountInsertCall<'a, C, A> where C: BorrowMut, A: /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.inventory().set(req, "merchantId", "storeCode", "productId") -/// .dry_run(false) +/// .dry_run(true) /// .doit(); /// # } /// ``` @@ -10621,7 +12311,7 @@ impl<'a, C, A> InventorySetCall<'a, C, A> where C: BorrowMut, A: } -/// Updates price and availability for multiple products or stores in a single request. +/// Updates price and availability for multiple products or stores in a single request. This operation does not update the expiration date of the products. /// /// A builder for the *custombatch* method supported by a *inventory* resource. /// It is not used directly, but through a `InventoryMethods` instance. @@ -10654,7 +12344,7 @@ impl<'a, C, A> InventorySetCall<'a, C, A> where C: BorrowMut, A: /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.inventory().custombatch(req) -/// .dry_run(false) +/// .dry_run(true) /// .doit(); /// # } /// ``` @@ -11142,8 +12832,8 @@ impl<'a, C, A> AccountstatuseGetCall<'a, C, A> where C: BorrowMut /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.accountstatuses().list("merchantId") -/// .page_token("justo") -/// .max_results(49) +/// .page_token("consetetur") +/// .max_results(17) /// .doit(); /// # } /// ``` @@ -11634,8 +13324,8 @@ impl<'a, C, A> AccountstatuseCustombatchCall<'a, C, A> where C: BorrowMut ProductGetCall<'a, C, A> where C: BorrowMut, A: oa /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.products().delete("merchantId", "productId") -/// .dry_run(false) +/// .dry_run(true) /// .doit(); /// # } /// ``` @@ -12397,7 +14087,7 @@ impl<'a, C, A> ProductDeleteCall<'a, C, A> where C: BorrowMut, A: /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.products().custombatch(req) -/// .dry_run(false) +/// .dry_run(true) /// .doit(); /// # } /// ``` @@ -12643,7 +14333,7 @@ impl<'a, C, A> ProductCustombatchCall<'a, C, A> where C: BorrowMut ProductInsertCall<'a, C, A> where C: BorrowMut, A: /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.accountshipping().list("merchantId") -/// .page_token("Lorem") -/// .max_results(84) +/// .page_token("labore") +/// .max_results(64) /// .doit(); /// # } /// ``` @@ -14225,3 +15915,4055 @@ impl<'a, C, A> AccountshippingGetCall<'a, C, A> where C: BorrowMut::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.orders().list("merchantId") +/// .add_statuses("labore") +/// .placed_date_start("sed") +/// .placed_date_end("ea") +/// .page_token("gubergren") +/// .order_by("aliquyam") +/// .max_results(77) +/// .acknowledged(true) +/// .doit(); +/// # } +/// ``` +pub struct OrderListCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a ShoppingContent, + _merchant_id: String, + _statuses: Vec, + _placed_date_start: Option, + _placed_date_end: Option, + _page_token: Option, + _order_by: Option, + _max_results: Option, + _acknowledged: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for OrderListCall<'a, C, A> {} + +impl<'a, C, A> OrderListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, OrdersListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.orders.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((10 + self._additional_params.len())); + params.push(("merchantId", self._merchant_id.to_string())); + if self._statuses.len() > 0 { + let mut s = String::new(); + for f in self._statuses.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("statuses", s)); + } + if let Some(value) = self._placed_date_start { + params.push(("placedDateStart", value.to_string())); + } + if let Some(value) = self._placed_date_end { + params.push(("placedDateEnd", 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._acknowledged { + params.push(("acknowledged", value.to_string())); + } + for &field in ["alt", "merchantId", "statuses", "placedDateStart", "placedDateEnd", "pageToken", "orderBy", "maxResults", "acknowledged"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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}/orders".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The ID of the managing account. + /// + /// 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) -> OrderListCall<'a, C, A> { + self._merchant_id = new_value.to_string(); + self + } + /// Obtains orders that match any of the specified statuses. Multiple values can be specified with comma separation. Additionally, please note that active is a shortcut for pendingShipment and partiallyShipped, and completed is a shortcut for shipped , partiallyDelivered, delivered, partiallyReturned, returned, and canceled. + /// + /// Append the given value to the *statuses* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + pub fn add_statuses(mut self, new_value: &str) -> OrderListCall<'a, C, A> { + self._statuses.push(new_value.to_string()); + self + } + /// Obtains orders placed after this date (inclusively), in ISO 8601 format. + /// + /// Sets the *placed date start* query property to the given value. + pub fn placed_date_start(mut self, new_value: &str) -> OrderListCall<'a, C, A> { + self._placed_date_start = Some(new_value.to_string()); + self + } + /// Obtains orders placed before this date (exclusively), in ISO 8601 format. + /// + /// Sets the *placed date end* query property to the given value. + pub fn placed_date_end(mut self, new_value: &str) -> OrderListCall<'a, C, A> { + self._placed_date_end = Some(new_value.to_string()); + self + } + /// The token returned by the previous request. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> OrderListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// The ordering of the returned list. The only supported value are placedDate desc and placedDate asc for now, which returns orders sorted by placement date. "placedDate desc" stands for listing orders by placement date, from oldest to most recent. "placedDate asc" stands for listing orders by placement date, from most recent to oldest. In future releases we'll support other sorting criteria. + /// + /// Sets the *order by* query property to the given value. + pub fn order_by(mut self, new_value: &str) -> OrderListCall<'a, C, A> { + self._order_by = Some(new_value.to_string()); + self + } + /// The maximum number of orders to return in the response, used for paging. The default value is 25 orders per page, and the maximum allowed value is 250 orders per page. + /// Known issue: All List calls will return all Orders without limit regardless of the value of this field. + /// + /// Sets the *max results* query property to the given value. + pub fn max_results(mut self, new_value: u32) -> OrderListCall<'a, C, A> { + self._max_results = Some(new_value); + self + } + /// Obtains orders that match the acknowledgement status. When set to true, obtains orders that have been acknowledged. When false, obtains orders that have not been acknowledged. + /// We recommend using this filter set to false, in conjunction with the acknowledge call, such that only un-acknowledged orders are returned. + /// + /// Sets the *acknowledged* query property to the given value. + pub fn acknowledged(mut self, new_value: bool) -> OrderListCall<'a, C, A> { + self._acknowledged = Some(new_value); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> OrderListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> OrderListCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Full`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> OrderListCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Sandbox only. Retrieves an order template that can be used to quickly create a new order in sandbox. +/// +/// A builder for the *gettestordertemplate* method supported by a *order* resource. +/// It is not used directly, but through a `OrderMethods` instance. +/// +/// # 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.orders().gettestordertemplate("merchantId", "templateName") +/// .doit(); +/// # } +/// ``` +pub struct OrderGettestordertemplateCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a ShoppingContent, + _merchant_id: String, + _template_name: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for OrderGettestordertemplateCall<'a, C, A> {} + +impl<'a, C, A> OrderGettestordertemplateCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, OrdersGetTestOrderTemplateResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.orders.gettestordertemplate", + 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(("templateName", self._template_name.to_string())); + for &field in ["alt", "merchantId", "templateName"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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}/testordertemplates/{templateName}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{merchantId}", "merchantId"), ("{templateName}", "templateName")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["templateName", "merchantId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The ID of the managing account. + /// + /// 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) -> OrderGettestordertemplateCall<'a, C, A> { + self._merchant_id = new_value.to_string(); + self + } + /// The name of the template to retrieve. + /// + /// Sets the *template 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 template_name(mut self, new_value: &str) -> OrderGettestordertemplateCall<'a, C, A> { + self._template_name = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> OrderGettestordertemplateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> OrderGettestordertemplateCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Full`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> OrderGettestordertemplateCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Retrieves an order from your Merchant Center account. +/// +/// A builder for the *get* method supported by a *order* resource. +/// It is not used directly, but through a `OrderMethods` instance. +/// +/// # 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.orders().get("merchantId", "orderId") +/// .doit(); +/// # } +/// ``` +pub struct OrderGetCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a ShoppingContent, + _merchant_id: String, + _order_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for OrderGetCall<'a, C, A> {} + +impl<'a, C, A> OrderGetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Order)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.orders.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(("orderId", self._order_id.to_string())); + for &field in ["alt", "merchantId", "orderId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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}/orders/{orderId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{merchantId}", "merchantId"), ("{orderId}", "orderId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["orderId", "merchantId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The ID of the managing account. + /// + /// 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) -> OrderGetCall<'a, C, A> { + self._merchant_id = new_value.to_string(); + self + } + /// The ID of the order. + /// + /// Sets the *order id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn order_id(mut self, new_value: &str) -> OrderGetCall<'a, C, A> { + self._order_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> OrderGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> OrderGetCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Full`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> OrderGetCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Refund a portion of the order, up to the full amount paid. +/// +/// A builder for the *refund* method supported by a *order* resource. +/// It is not used directly, but through a `OrderMethods` instance. +/// +/// # 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::OrdersRefundRequest; +/// # #[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 = OrdersRefundRequest::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.orders().refund(req, "merchantId", "orderId") +/// .doit(); +/// # } +/// ``` +pub struct OrderRefundCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a ShoppingContent, + _request: OrdersRefundRequest, + _merchant_id: String, + _order_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for OrderRefundCall<'a, C, A> {} + +impl<'a, C, A> OrderRefundCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, OrdersRefundResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.orders.refund", + 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())); + params.push(("orderId", self._order_id.to_string())); + for &field in ["alt", "merchantId", "orderId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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}/orders/{orderId}/refund".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{merchantId}", "merchantId"), ("{orderId}", "orderId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["orderId", "merchantId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: OrdersRefundRequest) -> OrderRefundCall<'a, C, A> { + self._request = new_value; + self + } + /// The ID of the managing account. + /// + /// 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) -> OrderRefundCall<'a, C, A> { + self._merchant_id = new_value.to_string(); + self + } + /// The ID of the order to refund. + /// + /// Sets the *order id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn order_id(mut self, new_value: &str) -> OrderRefundCall<'a, C, A> { + self._order_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> OrderRefundCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> OrderRefundCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Full`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> OrderRefundCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Marks an order as acknowledged. +/// +/// A builder for the *acknowledge* method supported by a *order* resource. +/// It is not used directly, but through a `OrderMethods` instance. +/// +/// # 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::OrdersAcknowledgeRequest; +/// # #[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 = OrdersAcknowledgeRequest::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.orders().acknowledge(req, "merchantId", "orderId") +/// .doit(); +/// # } +/// ``` +pub struct OrderAcknowledgeCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a ShoppingContent, + _request: OrdersAcknowledgeRequest, + _merchant_id: String, + _order_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for OrderAcknowledgeCall<'a, C, A> {} + +impl<'a, C, A> OrderAcknowledgeCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, OrdersAcknowledgeResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.orders.acknowledge", + 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())); + params.push(("orderId", self._order_id.to_string())); + for &field in ["alt", "merchantId", "orderId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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}/orders/{orderId}/acknowledge".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{merchantId}", "merchantId"), ("{orderId}", "orderId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["orderId", "merchantId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: OrdersAcknowledgeRequest) -> OrderAcknowledgeCall<'a, C, A> { + self._request = new_value; + self + } + /// The ID of the managing account. + /// + /// 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) -> OrderAcknowledgeCall<'a, C, A> { + self._merchant_id = new_value.to_string(); + self + } + /// The ID of the order. + /// + /// Sets the *order id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn order_id(mut self, new_value: &str) -> OrderAcknowledgeCall<'a, C, A> { + self._order_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> OrderAcknowledgeCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> OrderAcknowledgeCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Full`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> OrderAcknowledgeCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Updates the merchant order ID for a given order. +/// +/// A builder for the *updatemerchantorderid* method supported by a *order* resource. +/// It is not used directly, but through a `OrderMethods` instance. +/// +/// # 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::OrdersUpdateMerchantOrderIdRequest; +/// # #[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 = OrdersUpdateMerchantOrderIdRequest::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.orders().updatemerchantorderid(req, "merchantId", "orderId") +/// .doit(); +/// # } +/// ``` +pub struct OrderUpdatemerchantorderidCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a ShoppingContent, + _request: OrdersUpdateMerchantOrderIdRequest, + _merchant_id: String, + _order_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for OrderUpdatemerchantorderidCall<'a, C, A> {} + +impl<'a, C, A> OrderUpdatemerchantorderidCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, OrdersUpdateMerchantOrderIdResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.orders.updatemerchantorderid", + 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())); + params.push(("orderId", self._order_id.to_string())); + for &field in ["alt", "merchantId", "orderId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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}/orders/{orderId}/updateMerchantOrderId".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{merchantId}", "merchantId"), ("{orderId}", "orderId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["orderId", "merchantId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: OrdersUpdateMerchantOrderIdRequest) -> OrderUpdatemerchantorderidCall<'a, C, A> { + self._request = new_value; + self + } + /// The ID of the managing account. + /// + /// 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) -> OrderUpdatemerchantorderidCall<'a, C, A> { + self._merchant_id = new_value.to_string(); + self + } + /// The ID of the order. + /// + /// Sets the *order id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn order_id(mut self, new_value: &str) -> OrderUpdatemerchantorderidCall<'a, C, A> { + self._order_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> OrderUpdatemerchantorderidCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> OrderUpdatemerchantorderidCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Full`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> OrderUpdatemerchantorderidCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Sandbox only. Moves a test order from state "inProgress" to state "pendingShipment". +/// +/// A builder for the *advancetestorder* method supported by a *order* resource. +/// It is not used directly, but through a `OrderMethods` instance. +/// +/// # 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.orders().advancetestorder("merchantId", "orderId") +/// .doit(); +/// # } +/// ``` +pub struct OrderAdvancetestorderCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a ShoppingContent, + _merchant_id: String, + _order_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for OrderAdvancetestorderCall<'a, C, A> {} + +impl<'a, C, A> OrderAdvancetestorderCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, OrdersAdvanceTestOrderResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.orders.advancetestorder", + 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())); + params.push(("orderId", self._order_id.to_string())); + for &field in ["alt", "merchantId", "orderId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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}/testorders/{orderId}/advance".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{merchantId}", "merchantId"), ("{orderId}", "orderId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["orderId", "merchantId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The ID of the managing account. + /// + /// 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) -> OrderAdvancetestorderCall<'a, C, A> { + self._merchant_id = new_value.to_string(); + self + } + /// The ID of the test order to modify. + /// + /// Sets the *order id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn order_id(mut self, new_value: &str) -> OrderAdvancetestorderCall<'a, C, A> { + self._order_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> OrderAdvancetestorderCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> OrderAdvancetestorderCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Full`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> OrderAdvancetestorderCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Sandbox only. Creates a test order. +/// +/// A builder for the *createtestorder* method supported by a *order* resource. +/// It is not used directly, but through a `OrderMethods` instance. +/// +/// # 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::OrdersCreateTestOrderRequest; +/// # #[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 = OrdersCreateTestOrderRequest::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.orders().createtestorder(req, "merchantId") +/// .doit(); +/// # } +/// ``` +pub struct OrderCreatetestorderCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a ShoppingContent, + _request: OrdersCreateTestOrderRequest, + _merchant_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for OrderCreatetestorderCall<'a, C, A> {} + +impl<'a, C, A> OrderCreatetestorderCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, OrdersCreateTestOrderResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.orders.createtestorder", + 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 Err(Error::FieldClash(field)); + } + } + for (name, 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}/testorders".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: OrdersCreateTestOrderRequest) -> OrderCreatetestorderCall<'a, C, A> { + self._request = new_value; + self + } + /// The ID of the managing account. + /// + /// 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) -> OrderCreatetestorderCall<'a, C, A> { + self._merchant_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> OrderCreatetestorderCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> OrderCreatetestorderCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Full`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> OrderCreatetestorderCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Returns a line item. +/// +/// A builder for the *returnlineitem* method supported by a *order* resource. +/// It is not used directly, but through a `OrderMethods` instance. +/// +/// # 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::OrdersReturnLineItemRequest; +/// # #[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 = OrdersReturnLineItemRequest::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.orders().returnlineitem(req, "merchantId", "orderId") +/// .doit(); +/// # } +/// ``` +pub struct OrderReturnlineitemCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a ShoppingContent, + _request: OrdersReturnLineItemRequest, + _merchant_id: String, + _order_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for OrderReturnlineitemCall<'a, C, A> {} + +impl<'a, C, A> OrderReturnlineitemCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, OrdersReturnLineItemResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.orders.returnlineitem", + 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())); + params.push(("orderId", self._order_id.to_string())); + for &field in ["alt", "merchantId", "orderId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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}/orders/{orderId}/returnLineItem".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{merchantId}", "merchantId"), ("{orderId}", "orderId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["orderId", "merchantId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: OrdersReturnLineItemRequest) -> OrderReturnlineitemCall<'a, C, A> { + self._request = new_value; + self + } + /// The ID of the managing account. + /// + /// 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) -> OrderReturnlineitemCall<'a, C, A> { + self._merchant_id = new_value.to_string(); + self + } + /// The ID of the order. + /// + /// Sets the *order id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn order_id(mut self, new_value: &str) -> OrderReturnlineitemCall<'a, C, A> { + self._order_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> OrderReturnlineitemCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> OrderReturnlineitemCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Full`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> OrderReturnlineitemCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Retrieves an order using merchant order id. +/// +/// A builder for the *getbymerchantorderid* method supported by a *order* resource. +/// It is not used directly, but through a `OrderMethods` instance. +/// +/// # 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.orders().getbymerchantorderid("merchantId", "merchantOrderId") +/// .doit(); +/// # } +/// ``` +pub struct OrderGetbymerchantorderidCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a ShoppingContent, + _merchant_id: String, + _merchant_order_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for OrderGetbymerchantorderidCall<'a, C, A> {} + +impl<'a, C, A> OrderGetbymerchantorderidCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, OrdersGetByMerchantOrderIdResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.orders.getbymerchantorderid", + 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(("merchantOrderId", self._merchant_order_id.to_string())); + for &field in ["alt", "merchantId", "merchantOrderId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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}/ordersbymerchantid/{merchantOrderId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{merchantId}", "merchantId"), ("{merchantOrderId}", "merchantOrderId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["merchantOrderId", "merchantId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The ID of the managing account. + /// + /// 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) -> OrderGetbymerchantorderidCall<'a, C, A> { + self._merchant_id = new_value.to_string(); + self + } + /// The merchant order id to be looked for. + /// + /// Sets the *merchant order id* path property to 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_order_id(mut self, new_value: &str) -> OrderGetbymerchantorderidCall<'a, C, A> { + self._merchant_order_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> OrderGetbymerchantorderidCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> OrderGetbymerchantorderidCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Full`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> OrderGetbymerchantorderidCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Retrieves or modifies multiple orders in a single request. +/// +/// A builder for the *custombatch* method supported by a *order* resource. +/// It is not used directly, but through a `OrderMethods` instance. +/// +/// # 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::OrdersCustomBatchRequest; +/// # #[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 = OrdersCustomBatchRequest::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.orders().custombatch(req) +/// .doit(); +/// # } +/// ``` +pub struct OrderCustombatchCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a ShoppingContent, + _request: OrdersCustomBatchRequest, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for OrderCustombatchCall<'a, C, A> {} + +impl<'a, C, A> OrderCustombatchCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, OrdersCustomBatchResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.orders.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 Err(Error::FieldClash(field)); + } + } + for (name, 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/orders/batch".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_ref().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: OrdersCustomBatchRequest) -> OrderCustombatchCall<'a, C, A> { + self._request = new_value; + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> OrderCustombatchCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> OrderCustombatchCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Full`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> OrderCustombatchCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Marks line item(s) as shipped. +/// +/// A builder for the *shiplineitems* method supported by a *order* resource. +/// It is not used directly, but through a `OrderMethods` instance. +/// +/// # 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::OrdersShipLineItemsRequest; +/// # #[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 = OrdersShipLineItemsRequest::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.orders().shiplineitems(req, "merchantId", "orderId") +/// .doit(); +/// # } +/// ``` +pub struct OrderShiplineitemCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a ShoppingContent, + _request: OrdersShipLineItemsRequest, + _merchant_id: String, + _order_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for OrderShiplineitemCall<'a, C, A> {} + +impl<'a, C, A> OrderShiplineitemCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, OrdersShipLineItemsResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.orders.shiplineitems", + 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())); + params.push(("orderId", self._order_id.to_string())); + for &field in ["alt", "merchantId", "orderId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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}/orders/{orderId}/shipLineItems".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{merchantId}", "merchantId"), ("{orderId}", "orderId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["orderId", "merchantId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: OrdersShipLineItemsRequest) -> OrderShiplineitemCall<'a, C, A> { + self._request = new_value; + self + } + /// The ID of the managing account. + /// + /// 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) -> OrderShiplineitemCall<'a, C, A> { + self._merchant_id = new_value.to_string(); + self + } + /// The ID of the order. + /// + /// Sets the *order id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn order_id(mut self, new_value: &str) -> OrderShiplineitemCall<'a, C, A> { + self._order_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> OrderShiplineitemCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> OrderShiplineitemCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Full`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> OrderShiplineitemCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Updates a shipment's status, carrier, and/or tracking ID. +/// +/// A builder for the *updateshipment* method supported by a *order* resource. +/// It is not used directly, but through a `OrderMethods` instance. +/// +/// # 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::OrdersUpdateShipmentRequest; +/// # #[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 = OrdersUpdateShipmentRequest::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.orders().updateshipment(req, "merchantId", "orderId") +/// .doit(); +/// # } +/// ``` +pub struct OrderUpdateshipmentCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a ShoppingContent, + _request: OrdersUpdateShipmentRequest, + _merchant_id: String, + _order_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for OrderUpdateshipmentCall<'a, C, A> {} + +impl<'a, C, A> OrderUpdateshipmentCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, OrdersUpdateShipmentResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.orders.updateshipment", + 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())); + params.push(("orderId", self._order_id.to_string())); + for &field in ["alt", "merchantId", "orderId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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}/orders/{orderId}/updateShipment".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{merchantId}", "merchantId"), ("{orderId}", "orderId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["orderId", "merchantId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: OrdersUpdateShipmentRequest) -> OrderUpdateshipmentCall<'a, C, A> { + self._request = new_value; + self + } + /// The ID of the managing account. + /// + /// 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) -> OrderUpdateshipmentCall<'a, C, A> { + self._merchant_id = new_value.to_string(); + self + } + /// The ID of the order. + /// + /// Sets the *order id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn order_id(mut self, new_value: &str) -> OrderUpdateshipmentCall<'a, C, A> { + self._order_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> OrderUpdateshipmentCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> OrderUpdateshipmentCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Full`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> OrderUpdateshipmentCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Cancels a line item. +/// +/// A builder for the *cancellineitem* method supported by a *order* resource. +/// It is not used directly, but through a `OrderMethods` instance. +/// +/// # 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::OrdersCancelLineItemRequest; +/// # #[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 = OrdersCancelLineItemRequest::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.orders().cancellineitem(req, "merchantId", "orderId") +/// .doit(); +/// # } +/// ``` +pub struct OrderCancellineitemCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a ShoppingContent, + _request: OrdersCancelLineItemRequest, + _merchant_id: String, + _order_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for OrderCancellineitemCall<'a, C, A> {} + +impl<'a, C, A> OrderCancellineitemCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, OrdersCancelLineItemResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.orders.cancellineitem", + 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())); + params.push(("orderId", self._order_id.to_string())); + for &field in ["alt", "merchantId", "orderId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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}/orders/{orderId}/cancelLineItem".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{merchantId}", "merchantId"), ("{orderId}", "orderId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["orderId", "merchantId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: OrdersCancelLineItemRequest) -> OrderCancellineitemCall<'a, C, A> { + self._request = new_value; + self + } + /// The ID of the managing account. + /// + /// 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) -> OrderCancellineitemCall<'a, C, A> { + self._merchant_id = new_value.to_string(); + self + } + /// The ID of the order. + /// + /// Sets the *order id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn order_id(mut self, new_value: &str) -> OrderCancellineitemCall<'a, C, A> { + self._order_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> OrderCancellineitemCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> OrderCancellineitemCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Full`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> OrderCancellineitemCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Cancels all line items in an order. +/// +/// A builder for the *cancel* method supported by a *order* resource. +/// It is not used directly, but through a `OrderMethods` instance. +/// +/// # 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::OrdersCancelRequest; +/// # #[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 = OrdersCancelRequest::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.orders().cancel(req, "merchantId", "orderId") +/// .doit(); +/// # } +/// ``` +pub struct OrderCancelCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a ShoppingContent, + _request: OrdersCancelRequest, + _merchant_id: String, + _order_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for OrderCancelCall<'a, C, A> {} + +impl<'a, C, A> OrderCancelCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, OrdersCancelResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.orders.cancel", + 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())); + params.push(("orderId", self._order_id.to_string())); + for &field in ["alt", "merchantId", "orderId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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}/orders/{orderId}/cancel".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{merchantId}", "merchantId"), ("{orderId}", "orderId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["orderId", "merchantId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: OrdersCancelRequest) -> OrderCancelCall<'a, C, A> { + self._request = new_value; + self + } + /// The ID of the managing account. + /// + /// 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) -> OrderCancelCall<'a, C, A> { + self._merchant_id = new_value.to_string(); + self + } + /// The ID of the order to cancel. + /// + /// Sets the *order id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn order_id(mut self, new_value: &str) -> OrderCancelCall<'a, C, A> { + self._order_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> OrderCancelCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> OrderCancelCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Full`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> OrderCancelCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + diff --git a/gen/content2_sandbox-cli/Cargo.toml b/gen/content2_sandbox-cli/Cargo.toml new file mode 100644 index 0000000000..8e10babdb0 --- /dev/null +++ b/gen/content2_sandbox-cli/Cargo.toml @@ -0,0 +1,35 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-content2_sandbox-cli" +version = "0.3.2+20151002" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with Shopping Content (protocol v2sandbox)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/content2_sandbox-cli" +homepage = "https://developers.google.com/shopping-content" +documentation = "http://byron.github.io/google-apis-rs/google_content2_sandbox_cli" +license = "MIT" +keywords = ["content", "google", "cli"] + +[[bin]] +name = "content2-sandbox" + +[dependencies] +hyper = ">= 0.6.8" +mime = "0.1.0" +serde = ">= 0.6.0" +serde_json = ">= 0.6.0" +yup-oauth2 = "*" +strsim = "*" +yup-hyper-mock = ">=1.0.0" +clap = ">= 1.0.3" + +[build-dependencies] +syntex = { version = "*" } +serde_codegen = { version = "*" } + + +[dependencies.google-content2_sandbox] +path = "../content2_sandbox" diff --git a/gen/content2_sandbox-cli/LICENSE.md b/gen/content2_sandbox-cli/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/content2_sandbox-cli/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_sandbox-cli/README.md b/gen/content2_sandbox-cli/README.md new file mode 100644 index 0000000000..058766372d --- /dev/null +++ b/gen/content2_sandbox-cli/README.md @@ -0,0 +1,127 @@ + +The `content2-sandbox` command-line interface *(CLI)* allows to use most features of the *Google Shopping Content* service from the comfort of your terminal. + +By default all output is printed to standard out, but flags can be set to direct it into a file independent of your shell's +capabilities. Errors will be printed to standard error, and cause the program's exit code to be non-zero. + +If data-structures are requested, these will be returned as pretty-printed JSON, to be useful as input to other tools. + +Everything else about the *Shopping Content* API can be found at the +[official documentation site](https://developers.google.com/shopping-content). + +# Downloads + +You can download the pre-compiled 64bit binaries for the following platforms: + +* ![icon](http://megaicons.net/static/img/icons_sizes/6/140/16/ubuntu-icon.png) [ubuntu](http://dl.byronimo.de/google.rs/cli/0.3.2/ubuntu/content2-sandbox.tar.gz) +* ![icon](http://hydra-media.cursecdn.com/wow.gamepedia.com/a/a2/Apple-icon-16x16.png?version=25ddd67ac3dd3b634478e3978b76cb74) [osx](http://dl.byronimo.de/google.rs/cli/0.3.2/osx/content2-sandbox.tar.gz) + +Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/content2_sandbox-cli). + +# Usage + +This documentation was generated from the *Shopping Content* API at revision *20151002*. The CLI is at version *0.3.2*. + +```bash +content2-sandbox [options] + orders + acknowledge (-r )... [-p ]... [-o ] + advancetestorder [-p ]... [-o ] + cancel (-r )... [-p ]... [-o ] + cancellineitem (-r )... [-p ]... [-o ] + createtestorder (-r )... [-p ]... [-o ] + custombatch (-r )... [-p ]... [-o ] + get [-p ]... [-o ] + getbymerchantorderid [-p ]... [-o ] + gettestordertemplate [-p ]... [-o ] + list [-p ]... [-o ] + refund (-r )... [-p ]... [-o ] + returnlineitem (-r )... [-p ]... [-o ] + shiplineitems (-r )... [-p ]... [-o ] + updatemerchantorderid (-r )... [-p ]... [-o ] + updateshipment (-r )... [-p ]... [-o ] + content2-sandbox --help + +Configuration: + [--scope ]... + Specify the authentication a method should be executed in. Each scope + requires the user to grant this application permission to use it. + If unset, it defaults to the shortest scope url for a particular method. + --config-dir + A directory into which we will store our persistent data. Defaults to + a user-writable directory that we will create during the first invocation. + [default: ~/.google-service-cli] + --debug + Output all server communication to standard error. `tx` and `rx` are placed + into the same stream. + --debug-auth + Output all communication related to authentication to standard error. `tx` + and `rx` are placed into the same stream. + +``` + +# Configuration + +The program will store all persistent data in the `~/.google-service-cli` directory in *JSON* files prefixed with `content2-sandbox-`. You can change the directory used to store configuration with the `--config-dir` flag on a per-invocation basis. + +More information about the various kinds of persistent data are given in the following paragraphs. + +# Authentication + +Most APIs require a user to authenticate any request. If this is the case, the [scope][scopes] determines the +set of permissions granted. The granularity of these is usually no more than *read-only* or *full-access*. + +If not set, the system will automatically select the smallest feasible scope, e.g. when invoking a +method that is read-only, it will ask only for a read-only scope. +You may use the `--scope` flag to specify a scope directly. +All applicable scopes are documented in the respective method's CLI documentation. + +The first time a scope is used, the user is asked for permission. Follow the instructions given +by the CLI to grant permissions, or to decline. + +If a scope was authenticated by the user, the respective information will be stored as *JSON* in the configuration +directory, e.g. `~/.google-service-cli/content2-sandbox-token-.json`. No manual management of these tokens +is necessary. + +To revoke granted authentication, please refer to the [official documentation][revoke-access]. + +# Application Secrets + +In order to allow any application to use Google services, it will need to be registered using the +[Google Developer Console][google-dev-console]. APIs the application may use are then enabled for it +one by one. Most APIs can be used for free and have a daily quota. + +To allow more comfortable usage of the CLI without forcing anyone to register an own application, the CLI +comes with a default application secret that is configured accordingly. This also means that heavy usage +all around the world may deplete the daily quota. + +You can workaround this limitation by putting your own secrets file at this location: +`~/.google-service-cli/content2-sandbox-secret.json`, assuming that the required *content* API +was enabled for it. Such a secret file can be downloaded in the *Google Developer Console* at +*APIs & auth -> Credentials -> Download JSON* and used as is. + +Learn more about how to setup Google projects and enable APIs using the [official documentation][google-project-new]. + + +# Debugging + +Even though the CLI does its best to provide usable error messages, sometimes it might be desirable to know +what exactly led to a particular issue. This is done by allowing all client-server communication to be +output to standard error *as-is*. + +The `--debug` flag will print all client-server communication to standard error, whereas the `--debug-auth` flag +will cause all communication related to authentication to standard error. +If the `--debug` flag is set, error-results will be debug-printed, possibly yielding more information about the +issue at hand. + +You may consider redirecting standard error into a file for ease of use, e.g. `content2-sandbox --debug [options] 2>debug.txt`. + + +[scopes]: https://developers.google.com/+/api/oauth#scopes +[revoke-access]: http://webapps.stackexchange.com/a/30849 +[google-dev-console]: https://console.developers.google.com/ +[google-project-new]: https://developers.google.com/console/help/new/ \ No newline at end of file diff --git a/gen/content2_sandbox-cli/mkdocs.yml b/gen/content2_sandbox-cli/mkdocs.yml new file mode 100644 index 0000000000..467202ea28 --- /dev/null +++ b/gen/content2_sandbox-cli/mkdocs.yml @@ -0,0 +1,31 @@ +site_name: Shopping Content v0.3.2+20151002 +site_url: http://byron.github.io/google-apis-rs/google-content2_sandbox-cli +site_description: Write integrating applications with bcore + +repo_url: https://github.com/Byron/google-apis-rs/tree/master/gen/content2_sandbox-cli + +docs_dir: docs +site_dir: build_html + +pages: +- ['index.md', 'Home'] +- ['orders_acknowledge.md', 'Orders', 'Acknowledge'] +- ['orders_advancetestorder.md', 'Orders', 'Advancetestorder'] +- ['orders_cancel.md', 'Orders', 'Cancel'] +- ['orders_cancellineitem.md', 'Orders', 'Cancellineitem'] +- ['orders_createtestorder.md', 'Orders', 'Createtestorder'] +- ['orders_custombatch.md', 'Orders', 'Custombatch'] +- ['orders_get.md', 'Orders', 'Get'] +- ['orders_getbymerchantorderid.md', 'Orders', 'Getbymerchantorderid'] +- ['orders_gettestordertemplate.md', 'Orders', 'Gettestordertemplate'] +- ['orders_list.md', 'Orders', 'List'] +- ['orders_refund.md', 'Orders', 'Refund'] +- ['orders_returnlineitem.md', 'Orders', 'Returnlineitem'] +- ['orders_shiplineitems.md', 'Orders', 'Shiplineitems'] +- ['orders_updatemerchantorderid.md', 'Orders', 'Updatemerchantorderid'] +- ['orders_updateshipment.md', 'Orders', 'Updateshipment'] + +theme: readthedocs + +copyright: Copyright © 2015, `Sebastian Thiel` + diff --git a/gen/content2_sandbox-cli/src/cmn.rs b/gen/content2_sandbox-cli/src/cmn.rs new file mode 100644 index 0000000000..8358f156fa --- /dev/null +++ b/gen/content2_sandbox-cli/src/cmn.rs @@ -0,0 +1,721 @@ +// COPY OF 'src/rust/cli/cmn.rs' +// DO NOT EDIT +use oauth2::{ApplicationSecret, ConsoleApplicationSecret, TokenStorage, Token}; +use serde_json as json; +use serde_json::value::Value; +use mime::Mime; +use clap::{App, SubCommand}; +use strsim; + +use std::fs; +use std::env; +use std::io; +use std::fmt; +use std::path::{Path, PathBuf}; +use std::str::FromStr; +use std::string::ToString; +use std::io::{Write, Read, stdout}; + +use std::default::Default; + +const FIELD_SEP: char = '.'; + + +pub enum ComplexType { + Pod, + Vec, + Map, +} + + // Null, + // Bool(bool), + // I64(i64), + // U64(u64), + // F64(f64), + // String(String), + +pub enum JsonType { + Boolean, + Int, + Uint, + Float, + String, +} + +pub struct JsonTypeInfo { + pub jtype: JsonType, + pub ctype: ComplexType, +} + +// Based on @erickt user comment. Thanks for the idea ! +// Remove all keys whose values are null from given value (changed in place) +pub fn remove_json_null_values(value: &mut Value) { + match *value { + Value::Object(ref mut map) => { + let mut for_removal = Vec::new(); + + for (key, mut value) in map.iter_mut() { + if value.is_null() { + for_removal.push(key.clone()); + } else { + remove_json_null_values(&mut value); + } + } + + for key in &for_removal { + map.remove(key); + } + } + _ => {} + } +} + +fn did_you_mean<'a>(v: &str, possible_values: &[&'a str]) -> Option<&'a str> { + + let mut candidate: Option<(f64, &str)> = None; + for pv in possible_values { + let confidence = strsim::jaro_winkler(v, pv); + if confidence > 0.8 && (candidate.is_none() || (candidate.as_ref().unwrap().0 < confidence)) { + candidate = Some((confidence, pv)); + } + } + match candidate { + None => None, + Some((_, candidate)) => Some(candidate), + } +} + +pub enum CallType { + Upload(UploadProtocol), + Standard, +} + +arg_enum!{ + pub enum UploadProtocol { + Simple, + Resumable + } +} + +impl AsRef for UploadProtocol { + fn as_ref(&self) -> &str { + match *self { + UploadProtocol::Simple => "simple", + UploadProtocol::Resumable => "resumable" + } + } +} + +impl AsRef for CallType { + fn as_ref(&self) -> &str { + match *self { + CallType::Upload(ref proto) => proto.as_ref(), + CallType::Standard => "standard-request" + } + } +} + +#[derive(Clone, Default)] +pub struct FieldCursor(Vec); + +impl ToString for FieldCursor { + fn to_string(&self) -> String { + self.0.join(".") + } +} + +impl From<&'static str> for FieldCursor { + fn from(value: &'static str) -> FieldCursor { + let mut res = FieldCursor::default(); + res.set(value).unwrap(); + res + } +} + +impl FieldCursor { + pub fn set(&mut self, value: &str) -> Result<(), CLIError> { + if value.len() == 0 { + return Err(CLIError::Field(FieldError::Empty)) + } + + let mut first_is_field_sep = false; + let mut char_count: usize = 0; + let mut last_c = FIELD_SEP; + let mut num_conscutive_field_seps = 0; + + let mut field = String::new(); + let mut fields = self.0.clone(); + + let push_field = |fs: &mut Vec, f: &mut String| { + if f.len() > 0 { + fs.push(f.clone()); + f.truncate(0); + } + }; + + for (cid, c) in value.chars().enumerate() { + char_count += 1; + + if c == FIELD_SEP { + if cid == 0 { + first_is_field_sep = true; + } + num_conscutive_field_seps += 1; + if cid > 0 && last_c == FIELD_SEP { + if fields.pop().is_none() { + return Err(CLIError::Field(FieldError::PopOnEmpty(value.to_string()))) + } + } else { + push_field(&mut fields, &mut field); + } + } else { + num_conscutive_field_seps = 0; + if cid == 1 { + if first_is_field_sep { + fields.truncate(0); + } + } + field.push(c); + } + + last_c = c; + } + + push_field(&mut fields, &mut field); + + if char_count == 1 && first_is_field_sep { + fields.truncate(0); + } + if char_count > 1 && num_conscutive_field_seps == 1 { + return Err(CLIError::Field(FieldError::TrailingFieldSep(value.to_string()))) + } + + self.0 = fields; + Ok(()) + } + + pub fn did_you_mean(value: &str, possible_values: &[&str]) -> Option { + if value.len() == 0 { + return None + } + + let mut last_c = FIELD_SEP; + + let mut field = String::new(); + let mut output = String::new(); + + let push_field = |fs: &mut String, f: &mut String| { + if f.len() > 0 { + fs.push_str( + match did_you_mean(&f, possible_values) { + Some(candidate) => candidate, + None => &f, + }); + f.truncate(0); + } + }; + + for (cid, c) in value.chars().enumerate() { + if c == FIELD_SEP { + if last_c != FIELD_SEP { + push_field(&mut output, &mut field); + } + output.push(c); + } else { + field.push(c); + } + + last_c = c; + } + + push_field(&mut output, &mut field); + + if &output == value { + None + } else { + Some(output) + } + } + + pub fn set_json_value(&self, mut object: &mut Value, + value: &str, type_info: JsonTypeInfo, + err: &mut InvalidOptionsError, + orig_cursor: &FieldCursor) { + assert!(self.0.len() > 0); + + for field in &self.0[..self.0.len()-1] { + let tmp = object; + object = + match *tmp { + Value::Object(ref mut mapping) => { + mapping.entry(field.to_owned()).or_insert( + Value::Object(Default::default()) + ) + }, + _ => panic!("We don't expect non-object Values here ...") + }; + } + + match *object { + Value::Object(ref mut mapping) => { + let field = &self.0[self.0.len()-1]; + let to_jval = + |value: &str, jtype: JsonType, err: &mut InvalidOptionsError| + -> Value { + match jtype { + JsonType::Boolean => + Value::Bool(arg_from_str(value, err, &field, "boolean")), + JsonType::Int => + Value::I64(arg_from_str(value, err, &field, "int")), + JsonType::Uint => + Value::U64(arg_from_str(value, err, &field, "uint")), + JsonType::Float => + Value::F64(arg_from_str(value, err, &field, "float")), + JsonType::String => + Value::String(value.to_owned()), + } + }; + + match type_info.ctype { + ComplexType::Pod => { + if mapping.insert(field.to_owned(), to_jval(value, type_info.jtype, err)).is_some() { + err.issues.push(CLIError::Field(FieldError::Duplicate(orig_cursor.to_string()))); + } + }, + ComplexType::Vec => { + match *mapping.entry(field.to_owned()) + .or_insert(Value::Array(Default::default())) { + Value::Array(ref mut values) => values.push(to_jval(value, type_info.jtype, err)), + _ => unreachable!() + } + }, + ComplexType::Map => { + let (key, value) = parse_kv_arg(value, err, true); + let jval = to_jval(value.unwrap_or(""), type_info.jtype, err); + + match *mapping.entry(field.to_owned()) + .or_insert(Value::Object(Default::default())) { + Value::Object(ref mut value_map) => { + if value_map.insert(key.to_owned(), jval).is_some() { + err.issues.push(CLIError::Field(FieldError::Duplicate(orig_cursor.to_string()))); + } + } + _ => unreachable!() + } + } + } + }, + _ => unreachable!() + } + } + + pub fn num_fields(&self) -> usize { + self.0.len() + } +} + +pub fn parse_kv_arg<'a>(kv: &'a str, err: &mut InvalidOptionsError, for_hashmap: bool) + -> (&'a str, Option<&'a str>) { + let mut add_err = || err.issues.push(CLIError::InvalidKeyValueSyntax(kv.to_string(),for_hashmap)); + match kv.find('=') { + None => { + add_err(); + return (kv, None) + }, + Some(pos) => { + let key = &kv[..pos]; + if kv.len() <= pos + 1 { + add_err(); + return (key, Some("")) + } + (key, Some(&kv[pos+1..])) + } + } +} + +pub fn calltype_from_str(name: &str, valid_protocols: Vec, err: &mut InvalidOptionsError) -> CallType { + CallType::Upload( + match UploadProtocol::from_str(name) { + Ok(up) => up, + Err(msg) => { + err.issues.push(CLIError::InvalidUploadProtocol(name.to_string(), valid_protocols)); + UploadProtocol::Simple + } + }) +} + +pub fn input_file_from_opts(file_path: &str, err: &mut InvalidOptionsError) -> Option { + match fs::File::open(file_path) { + Ok(f) => Some(f), + Err(io_err) => { + err.issues.push(CLIError::Input(InputError::IOError((file_path.to_string(), io_err)))); + None + } + } +} + +pub fn input_mime_from_opts(mime: &str, err: &mut InvalidOptionsError) -> Option { + match mime.parse() { + Ok(m) => Some(m), + Err(_) => { + err.issues.push(CLIError::Input(InputError::Mime(mime.to_string()))); + None + } + } +} + +pub fn writer_from_opts(arg: Option<&str>) -> Result, io::Error> { + let f = arg.unwrap_or("-"); + match f { + "-" => Ok(Box::new(stdout())), + _ => match fs::OpenOptions::new().create(true).write(true).open(f) { + Ok(f) => Ok(Box::new(f)), + Err(io_err) => Err(io_err), + } + } +} + + +pub fn arg_from_str<'a, T>(arg: &str, err: &mut InvalidOptionsError, + arg_name: &'a str, + arg_type: &'a str) -> T + where T: FromStr + Default, + ::Err: fmt::Display { + match FromStr::from_str(arg) { + Err(perr) => { + err.issues.push( + CLIError::ParseError(arg_name.to_owned(), arg_type.to_owned(), arg.to_string(), format!("{}", perr)) + ); + Default::default() + }, + Ok(v) => v, + } +} + +pub struct JsonTokenStorage { + pub program_name: &'static str, + pub db_dir: String, +} + +impl JsonTokenStorage { + fn path(&self, scope_hash: u64) -> PathBuf { + Path::new(&self.db_dir).join(&format!("{}-token-{}.json", self.program_name, scope_hash)) + } +} + +impl TokenStorage for JsonTokenStorage { + type Error = json::Error; + + // NOTE: logging might be interesting, currently we swallow all errors + fn set(&mut self, scope_hash: u64, _: &Vec<&str>, token: Option) -> Result<(), json::Error> { + match token { + None => { + match fs::remove_file(self.path(scope_hash)) { + Err(err) => + match err.kind() { + io::ErrorKind::NotFound => Ok(()), + _ => Err(json::Error::IoError(err)) + }, + Ok(_) => Ok(()), + } + } + Some(token) => { + match fs::OpenOptions::new().create(true).write(true).open(&self.path(scope_hash)) { + Ok(mut f) => { + match json::to_writer_pretty(&mut f, &token) { + Ok(_) => Ok(()), + Err(serde_err) => Err(serde_err), + } + }, + Err(io_err) => Err(json::Error::IoError(io_err)) + } + } + } + } + + fn get(&self, scope_hash: u64, _: &Vec<&str>) -> Result, json::Error> { + match fs::File::open(&self.path(scope_hash)) { + Ok(mut f) => { + match json::de::from_reader(f) { + Ok(token) => Ok(Some(token)), + Err(err) => Err(err), + } + }, + Err(io_err) => { + match io_err.kind() { + io::ErrorKind::NotFound => Ok(None), + _ => Err(json::Error::IoError(io_err)) + } + } + } + } +} + + +#[derive(Debug)] +pub enum ApplicationSecretError { + DecoderError((String, json::Error)), + FormatError(String), +} + +impl fmt::Display for ApplicationSecretError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + ApplicationSecretError::DecoderError((ref path, ref err)) + => writeln!(f, "Could not decode file at '{}' with error: {}.", + path, err), + ApplicationSecretError::FormatError(ref path) + => writeln!(f, "'installed' field is unset in secret file at '{}'.", + path), + } + } +} + +#[derive(Debug)] +pub enum ConfigurationError { + DirectoryCreationFailed((String, io::Error)), + DirectoryUnset, + HomeExpansionFailed(String), + Secret(ApplicationSecretError), + IOError((String, io::Error)), +} + +impl fmt::Display for ConfigurationError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + ConfigurationError::DirectoryCreationFailed((ref dir, ref err)) + => writeln!(f, "Directory '{}' could not be created with error: {}.", dir, err), + ConfigurationError::DirectoryUnset + => writeln!(f, "--config-dir was unset or empty."), + ConfigurationError::HomeExpansionFailed(ref dir) + => writeln!(f, "Couldn't find HOME directory of current user, failed to expand '{}'.", dir), + ConfigurationError::Secret(ref err) + => writeln!(f, "Secret -> {}", err), + ConfigurationError::IOError((ref path, ref err)) + => writeln!(f, "IO operation failed on path '{}' with error: {}.", path, err), + } + } +} + +#[derive(Debug)] +pub enum InputError { + IOError((String, io::Error)), + Mime(String), +} + +impl fmt::Display for InputError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + InputError::IOError((ref file_path, ref io_err)) + => writeln!(f, "Failed to open '{}' for reading with error: {}.", file_path, io_err), + InputError::Mime(ref mime) + => writeln!(f, "'{}' is not a known mime-type.", mime), + } + } +} + +#[derive(Debug)] +pub enum FieldError { + PopOnEmpty(String), + TrailingFieldSep(String), + Unknown(String, Option, Option), + Duplicate(String), + Empty, +} + + +impl fmt::Display for FieldError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + FieldError::PopOnEmpty(ref field) + => writeln!(f, "'{}': Cannot move up on empty field cursor.", field), + FieldError::TrailingFieldSep(ref field) + => writeln!(f, "'{}': Single field separator may not be last character.", field), + FieldError::Unknown(ref field, ref suggestion, ref value) => { + let suffix = + match *suggestion { + Some(ref s) => { + let kv = + match *value { + Some(ref v) => format!("{}={}", s, v), + None => s.clone(), + }; + format!(" Did you mean '{}' ?", kv) + }, + None => String::new(), + }; + writeln!(f, "Field '{}' does not exist.{}", field, suffix) + }, + FieldError::Duplicate(ref cursor) + => writeln!(f, "Value at '{}' was already set", cursor), + FieldError::Empty + => writeln!(f, "Field names must not be empty."), + } + } +} + + +#[derive(Debug)] +pub enum CLIError { + Configuration(ConfigurationError), + ParseError(String, String, String, String), + UnknownParameter(String, Vec<&'static str>), + InvalidUploadProtocol(String, Vec), + InvalidKeyValueSyntax(String, bool), + Input(InputError), + Field(FieldError), + MissingCommandError, + MissingMethodError(String), +} + +impl fmt::Display for CLIError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + CLIError::Configuration(ref err) => write!(f, "Configuration -> {}", err), + CLIError::Input(ref err) => write!(f, "Input -> {}", err), + CLIError::Field(ref err) => write!(f, "Field -> {}", err), + CLIError::InvalidUploadProtocol(ref proto_name, ref valid_names) + => writeln!(f, "'{}' is not a valid upload protocol. Choose from one of {}.", proto_name, valid_names.join(", ")), + CLIError::ParseError(ref arg_name, ref type_name, ref value, ref err_desc) + => writeln!(f, "Failed to parse argument '{}' with value '{}' as {} with error: {}.", + arg_name, value, type_name, err_desc), + CLIError::UnknownParameter(ref param_name, ref possible_values) => { + let mut suffix = + match did_you_mean(param_name, &possible_values) { + Some(v) => format!(" Did you mean '{}' ?", v), + None => String::new(), + }; + write!(f, "Parameter '{}' is unknown.{}\n", param_name, suffix) + }, + CLIError::InvalidKeyValueSyntax(ref kv, is_hashmap) => { + let hashmap_info = if is_hashmap { "hashmap " } else { "" }; + writeln!(f, "'{}' does not match {}pattern =.", kv, hashmap_info) + }, + CLIError::MissingCommandError => writeln!(f, "Please specify the main sub-command."), + CLIError::MissingMethodError(ref cmd) => writeln!(f, "Please specify the method to call on the '{}' command.", cmd), + } + } +} + +#[derive(Debug)] +pub struct InvalidOptionsError { + pub issues: Vec, + pub exit_code: i32, +} + +impl fmt::Display for InvalidOptionsError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + for issue in &self.issues { + try!(issue.fmt(f)); + } + Ok(()) + } +} + +impl InvalidOptionsError { + pub fn single(err: CLIError, exit_code: i32) -> InvalidOptionsError { + InvalidOptionsError { + issues: vec![err], + exit_code: exit_code, + } + } + + pub fn new() -> InvalidOptionsError { + InvalidOptionsError { + issues: Vec::new(), + exit_code: 1, + } + } +} + +pub fn assure_config_dir_exists(dir: &str) -> Result { + let trdir = dir.trim(); + if trdir.len() == 0 { + return Err(CLIError::Configuration(ConfigurationError::DirectoryUnset)) + } + + let expanded_config_dir = + if trdir.as_bytes()[0] == b'~' { + match env::var("HOME").ok().or(env::var("UserProfile").ok()) { + None => return Err(CLIError::Configuration(ConfigurationError::HomeExpansionFailed(trdir.to_string()))), + Some(mut user) => { + user.push_str(&trdir[1..]); + user + } + } + } else { + trdir.to_string() + }; + + if let Err(err) = fs::create_dir(&expanded_config_dir) { + if err.kind() != io::ErrorKind::AlreadyExists { + return Err(CLIError::Configuration( + ConfigurationError::DirectoryCreationFailed((expanded_config_dir, err)))) + } + } + + Ok(expanded_config_dir) +} + +pub fn application_secret_from_directory(dir: &str, + secret_basename: &str, + json_console_secret: &str) + -> Result { + let secret_path = Path::new(dir).join(secret_basename); + let secret_str = || secret_path.as_path().to_str().unwrap().to_string(); + let secret_io_error = |io_err: io::Error| { + Err(CLIError::Configuration(ConfigurationError::IOError( + (secret_str(), io_err) + ))) + }; + + for _ in 0..2 { + match fs::File::open(&secret_path) { + Err(mut err) => { + if err.kind() == io::ErrorKind::NotFound { + // Write our built-in one - user may adjust the written file at will + + err = match fs::OpenOptions::new().create(true).write(true).open(&secret_path) { + Err(cfe) => cfe, + Ok(mut f) => { + // Assure we convert 'ugly' json string into pretty one + let console_secret: ConsoleApplicationSecret + = json::from_str(json_console_secret).unwrap(); + match json::to_writer_pretty(&mut f, &console_secret) { + Err(serde_err) => match serde_err { + json::Error::IoError(err) => err, + _ => panic!("Unexpected serde error: {:#?}", serde_err) + }, + Ok(_) => continue, + } + } + }; + // fall through to IO error handling + } + return secret_io_error(err) + }, + Ok(mut f) => { + match json::de::from_reader::<_, ConsoleApplicationSecret>(f) { + Err(json::Error::IoError(err)) => + return secret_io_error(err), + Err(json_err) => + return Err(CLIError::Configuration( + ConfigurationError::Secret( + ApplicationSecretError::DecoderError( + (secret_str(), json_err) + )))), + Ok(console_secret) => + match console_secret.installed { + Some(secret) => return Ok(secret), + None => return Err( + CLIError::Configuration( + ConfigurationError::Secret( + ApplicationSecretError::FormatError(secret_str()) + ))) + }, + } + } + } + } + unreachable!(); +} diff --git a/gen/content2_sandbox-cli/src/main.rs b/gen/content2_sandbox-cli/src/main.rs new file mode 100644 index 0000000000..1855112e5b --- /dev/null +++ b/gen/content2_sandbox-cli/src/main.rs @@ -0,0 +1,1912 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/cli/main.rs.mako' +// DO NOT EDIT ! +#![allow(unused_variables, unused_imports, dead_code, unused_mut)] + +#[macro_use] +extern crate clap; +extern crate yup_oauth2 as oauth2; +extern crate yup_hyper_mock as mock; +extern crate serde; +extern crate serde_json; +extern crate hyper; +extern crate mime; +extern crate strsim; +extern crate google_content2_sandbox as api; + +use std::env; +use std::io::{self, Write}; +use clap::{App, SubCommand, Arg}; + +mod cmn; + +use cmn::{InvalidOptionsError, CLIError, JsonTokenStorage, arg_from_str, writer_from_opts, parse_kv_arg, + input_file_from_opts, input_mime_from_opts, FieldCursor, FieldError, CallType, UploadProtocol, + calltype_from_str, remove_json_null_values, ComplexType, JsonType, JsonTypeInfo}; + +use std::default::Default; +use std::str::FromStr; + +use oauth2::{Authenticator, DefaultAuthenticatorDelegate}; +use serde_json as json; +use clap::ArgMatches; + +enum DoitError { + IoError(String, io::Error), + ApiError(api::Error), +} + +struct Engine<'n, 'a> { + opt: ArgMatches<'n, 'a>, + hub: api::ShoppingContent>, + gp: Vec<&'static str>, + gpm: Vec<(&'static str, &'static str)>, +} + + +impl<'n, 'a> Engine<'n, 'a> { + fn _orders_acknowledge(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "operation-id" => Some(("operationId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["operation-id"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::OrdersAcknowledgeRequest = json::value::from_value(object).unwrap(); + let mut call = self.hub.orders().acknowledge(request, opt.value_of("merchant-id").unwrap_or(""), opt.value_of("order-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _orders_advancetestorder(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.orders().advancetestorder(opt.value_of("merchant-id").unwrap_or(""), opt.value_of("order-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _orders_cancel(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "reason" => Some(("reason", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "reason-text" => Some(("reasonText", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "operation-id" => Some(("operationId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["operation-id", "reason", "reason-text"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::OrdersCancelRequest = json::value::from_value(object).unwrap(); + let mut call = self.hub.orders().cancel(request, opt.value_of("merchant-id").unwrap_or(""), opt.value_of("order-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _orders_cancellineitem(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "quantity" => Some(("quantity", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "reason" => Some(("reason", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "reason-text" => Some(("reasonText", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "line-item-id" => Some(("lineItemId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "operation-id" => Some(("operationId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["line-item-id", "operation-id", "quantity", "reason", "reason-text"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::OrdersCancelLineItemRequest = json::value::from_value(object).unwrap(); + let mut call = self.hub.orders().cancellineitem(request, opt.value_of("merchant-id").unwrap_or(""), opt.value_of("order-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _orders_createtestorder(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "test-order.customer.explicit-marketing-preference" => Some(("testOrder.customer.explicitMarketingPreference", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "test-order.customer.full-name" => Some(("testOrder.customer.fullName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "test-order.customer.email" => Some(("testOrder.customer.email", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "test-order.kind" => Some(("testOrder.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "test-order.predefined-delivery-address" => Some(("testOrder.predefinedDeliveryAddress", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "test-order.shipping-cost.currency" => Some(("testOrder.shippingCost.currency", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "test-order.shipping-cost.value" => Some(("testOrder.shippingCost.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "test-order.shipping-option" => Some(("testOrder.shippingOption", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "test-order.shipping-cost-tax.currency" => Some(("testOrder.shippingCostTax.currency", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "test-order.shipping-cost-tax.value" => Some(("testOrder.shippingCostTax.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "test-order.payment-method.expiration-month" => Some(("testOrder.paymentMethod.expirationMonth", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "test-order.payment-method.type" => Some(("testOrder.paymentMethod.type", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "test-order.payment-method.expiration-year" => Some(("testOrder.paymentMethod.expirationYear", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "test-order.payment-method.last-four-digits" => Some(("testOrder.paymentMethod.lastFourDigits", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "test-order.payment-method.predefined-billing-address" => Some(("testOrder.paymentMethod.predefinedBillingAddress", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "template-name" => Some(("templateName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["currency", "customer", "email", "expiration-month", "expiration-year", "explicit-marketing-preference", "full-name", "kind", "last-four-digits", "payment-method", "predefined-billing-address", "predefined-delivery-address", "shipping-cost", "shipping-cost-tax", "shipping-option", "template-name", "test-order", "type", "value"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::OrdersCreateTestOrderRequest = json::value::from_value(object).unwrap(); + let mut call = self.hub.orders().createtestorder(request, opt.value_of("merchant-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _orders_custombatch(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec![]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::OrdersCustomBatchRequest = json::value::from_value(object).unwrap(); + let mut call = self.hub.orders().custombatch(request); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _orders_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.orders().get(opt.value_of("merchant-id").unwrap_or(""), opt.value_of("order-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _orders_getbymerchantorderid(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.orders().getbymerchantorderid(opt.value_of("merchant-id").unwrap_or(""), opt.value_of("merchant-order-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _orders_gettestordertemplate(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.orders().gettestordertemplate(opt.value_of("merchant-id").unwrap_or(""), opt.value_of("template-name").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _orders_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.orders().list(opt.value_of("merchant-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "statuses" => { + call = call.add_statuses(value.unwrap_or("")); + }, + "placed-date-start" => { + call = call.placed_date_start(value.unwrap_or("")); + }, + "placed-date-end" => { + call = call.placed_date_end(value.unwrap_or("")); + }, + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "order-by" => { + call = call.order_by(value.unwrap_or("")); + }, + "max-results" => { + call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer")); + }, + "acknowledged" => { + call = call.acknowledged(arg_from_str(value.unwrap_or("false"), err, "acknowledged", "boolean")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["order-by", "placed-date-end", "acknowledged", "max-results", "page-token", "placed-date-start", "statuses"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _orders_refund(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "amount.currency" => Some(("amount.currency", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "amount.value" => Some(("amount.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "reason-text" => Some(("reasonText", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "reason" => Some(("reason", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "operation-id" => Some(("operationId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["amount", "currency", "operation-id", "reason", "reason-text", "value"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::OrdersRefundRequest = json::value::from_value(object).unwrap(); + let mut call = self.hub.orders().refund(request, opt.value_of("merchant-id").unwrap_or(""), opt.value_of("order-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _orders_returnlineitem(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "quantity" => Some(("quantity", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "reason" => Some(("reason", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "reason-text" => Some(("reasonText", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "line-item-id" => Some(("lineItemId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "operation-id" => Some(("operationId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["line-item-id", "operation-id", "quantity", "reason", "reason-text"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::OrdersReturnLineItemRequest = json::value::from_value(object).unwrap(); + let mut call = self.hub.orders().returnlineitem(request, opt.value_of("merchant-id").unwrap_or(""), opt.value_of("order-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _orders_shiplineitems(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "shipment-id" => Some(("shipmentId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "carrier" => Some(("carrier", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "tracking-id" => Some(("trackingId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "operation-id" => Some(("operationId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["carrier", "operation-id", "shipment-id", "tracking-id"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::OrdersShipLineItemsRequest = json::value::from_value(object).unwrap(); + let mut call = self.hub.orders().shiplineitems(request, opt.value_of("merchant-id").unwrap_or(""), opt.value_of("order-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _orders_updatemerchantorderid(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "merchant-order-id" => Some(("merchantOrderId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "operation-id" => Some(("operationId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["merchant-order-id", "operation-id"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::OrdersUpdateMerchantOrderIdRequest = json::value::from_value(object).unwrap(); + let mut call = self.hub.orders().updatemerchantorderid(request, opt.value_of("merchant-id").unwrap_or(""), opt.value_of("order-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _orders_updateshipment(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "status" => Some(("status", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "shipment-id" => Some(("shipmentId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "carrier" => Some(("carrier", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "tracking-id" => Some(("trackingId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "operation-id" => Some(("operationId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["carrier", "operation-id", "shipment-id", "status", "tracking-id"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::OrdersUpdateShipmentRequest = json::value::from_value(object).unwrap(); + let mut call = self.hub.orders().updateshipment(request, opt.value_of("merchant-id").unwrap_or(""), opt.value_of("order-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _doit(&self, dry_run: bool) -> Result, Option> { + let mut err = InvalidOptionsError::new(); + let mut call_result: Result<(), DoitError> = Ok(()); + let mut err_opt: Option = None; + match self.opt.subcommand() { + ("orders", Some(opt)) => { + match opt.subcommand() { + ("acknowledge", Some(opt)) => { + call_result = self._orders_acknowledge(opt, dry_run, &mut err); + }, + ("advancetestorder", Some(opt)) => { + call_result = self._orders_advancetestorder(opt, dry_run, &mut err); + }, + ("cancel", Some(opt)) => { + call_result = self._orders_cancel(opt, dry_run, &mut err); + }, + ("cancellineitem", Some(opt)) => { + call_result = self._orders_cancellineitem(opt, dry_run, &mut err); + }, + ("createtestorder", Some(opt)) => { + call_result = self._orders_createtestorder(opt, dry_run, &mut err); + }, + ("custombatch", Some(opt)) => { + call_result = self._orders_custombatch(opt, dry_run, &mut err); + }, + ("get", Some(opt)) => { + call_result = self._orders_get(opt, dry_run, &mut err); + }, + ("getbymerchantorderid", Some(opt)) => { + call_result = self._orders_getbymerchantorderid(opt, dry_run, &mut err); + }, + ("gettestordertemplate", Some(opt)) => { + call_result = self._orders_gettestordertemplate(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._orders_list(opt, dry_run, &mut err); + }, + ("refund", Some(opt)) => { + call_result = self._orders_refund(opt, dry_run, &mut err); + }, + ("returnlineitem", Some(opt)) => { + call_result = self._orders_returnlineitem(opt, dry_run, &mut err); + }, + ("shiplineitems", Some(opt)) => { + call_result = self._orders_shiplineitems(opt, dry_run, &mut err); + }, + ("updatemerchantorderid", Some(opt)) => { + call_result = self._orders_updatemerchantorderid(opt, dry_run, &mut err); + }, + ("updateshipment", Some(opt)) => { + call_result = self._orders_updateshipment(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("orders".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + _ => { + err.issues.push(CLIError::MissingCommandError); + writeln!(io::stderr(), "{}\n", self.opt.usage()).ok(); + } + } + + if dry_run { + if err.issues.len() > 0 { + err_opt = Some(err); + } + Err(err_opt) + } else { + Ok(call_result) + } + } + + // Please note that this call will fail if any part of the opt can't be handled + fn new(opt: ArgMatches<'a, 'n>) -> Result, InvalidOptionsError> { + let (config_dir, secret) = { + let config_dir = match cmn::assure_config_dir_exists(opt.value_of("folder").unwrap_or("~/.google-service-cli")) { + Err(e) => return Err(InvalidOptionsError::single(e, 3)), + Ok(p) => p, + }; + + match cmn::application_secret_from_directory(&config_dir, "content2-sandbox-secret.json", + "{\"installed\":{\"auth_uri\":\"https://accounts.google.com/o/oauth2/auth\",\"client_secret\":\"hCsslbCUyfehWMmbkG8vTYxG\",\"token_uri\":\"https://accounts.google.com/o/oauth2/token\",\"client_email\":\"\",\"redirect_uris\":[\"urn:ietf:wg:oauth:2.0:oob\",\"oob\"],\"client_x509_cert_url\":\"\",\"client_id\":\"620010449518-9ngf7o4dhs0dka470npqvor6dc5lqb9b.apps.googleusercontent.com\",\"auth_provider_x509_cert_url\":\"https://www.googleapis.com/oauth2/v1/certs\"}}") { + Ok(secret) => (config_dir, secret), + Err(e) => return Err(InvalidOptionsError::single(e, 4)) + } + }; + + let auth = Authenticator::new( &secret, DefaultAuthenticatorDelegate, + if opt.is_present("debug-auth") { + hyper::Client::with_connector(mock::TeeConnector { + connector: hyper::net::HttpsConnector::::default() + }) + } else { + hyper::Client::new() + }, + JsonTokenStorage { + program_name: "content2-sandbox", + db_dir: config_dir.clone(), + }, None); + + let client = + if opt.is_present("debug") { + hyper::Client::with_connector(mock::TeeConnector { + connector: hyper::net::HttpsConnector::::default() + }) + } else { + hyper::Client::new() + }; + let engine = Engine { + opt: opt, + hub: api::ShoppingContent::new(client, auth), + gp: vec!["alt", "fields", "key", "oauth-token", "pretty-print", "quota-user", "user-ip"], + gpm: vec![ + ("oauth-token", "oauth_token"), + ("pretty-print", "prettyPrint"), + ("quota-user", "quotaUser"), + ("user-ip", "userIp"), + ] + }; + + match engine._doit(true) { + Err(Some(err)) => Err(err), + Err(None) => Ok(engine), + Ok(_) => unreachable!(), + } + } + + fn doit(&self) -> Result<(), DoitError> { + match self._doit(false) { + Ok(res) => res, + Err(_) => unreachable!(), + } + } +} + +fn main() { + let mut exit_status = 0i32; + let arg_data = [ + ("orders", "methods: 'acknowledge', 'advancetestorder', 'cancel', 'cancellineitem', 'createtestorder', 'custombatch', 'get', 'getbymerchantorderid', 'gettestordertemplate', 'list', 'refund', 'returnlineitem', 'shiplineitems', 'updatemerchantorderid' and 'updateshipment'", vec![ + ("acknowledge", + Some(r##"Marks an order as acknowledged."##), + "Details at http://byron.github.io/google-apis-rs/google_content2_sandbox_cli/orders_acknowledge", + vec![ + (Some(r##"merchant-id"##), + None, + Some(r##"The ID of the managing account."##), + Some(true), + Some(false)), + + (Some(r##"order-id"##), + None, + Some(r##"The ID of the order."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("advancetestorder", + Some(r##"Sandbox only. Moves a test order from state "inProgress" to state "pendingShipment"."##), + "Details at http://byron.github.io/google-apis-rs/google_content2_sandbox_cli/orders_advancetestorder", + vec![ + (Some(r##"merchant-id"##), + None, + Some(r##"The ID of the managing account."##), + Some(true), + Some(false)), + + (Some(r##"order-id"##), + None, + Some(r##"The ID of the test order to modify."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("cancel", + Some(r##"Cancels all line items in an order."##), + "Details at http://byron.github.io/google-apis-rs/google_content2_sandbox_cli/orders_cancel", + vec![ + (Some(r##"merchant-id"##), + None, + Some(r##"The ID of the managing account."##), + Some(true), + Some(false)), + + (Some(r##"order-id"##), + None, + Some(r##"The ID of the order to cancel."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("cancellineitem", + Some(r##"Cancels a line item."##), + "Details at http://byron.github.io/google-apis-rs/google_content2_sandbox_cli/orders_cancellineitem", + vec![ + (Some(r##"merchant-id"##), + None, + Some(r##"The ID of the managing account."##), + Some(true), + Some(false)), + + (Some(r##"order-id"##), + None, + Some(r##"The ID of the order."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("createtestorder", + Some(r##"Sandbox only. Creates a test order."##), + "Details at http://byron.github.io/google-apis-rs/google_content2_sandbox_cli/orders_createtestorder", + vec![ + (Some(r##"merchant-id"##), + None, + Some(r##"The ID of the managing account."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("custombatch", + Some(r##"Retrieves or modifies multiple orders in a single request."##), + "Details at http://byron.github.io/google-apis-rs/google_content2_sandbox_cli/orders_custombatch", + vec![ + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("get", + Some(r##"Retrieves an order from your Merchant Center account."##), + "Details at http://byron.github.io/google-apis-rs/google_content2_sandbox_cli/orders_get", + vec![ + (Some(r##"merchant-id"##), + None, + Some(r##"The ID of the managing account."##), + Some(true), + Some(false)), + + (Some(r##"order-id"##), + None, + Some(r##"The ID of the order."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("getbymerchantorderid", + Some(r##"Retrieves an order using merchant order id."##), + "Details at http://byron.github.io/google-apis-rs/google_content2_sandbox_cli/orders_getbymerchantorderid", + vec![ + (Some(r##"merchant-id"##), + None, + Some(r##"The ID of the managing account."##), + Some(true), + Some(false)), + + (Some(r##"merchant-order-id"##), + None, + Some(r##"The merchant order id to be looked for."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("gettestordertemplate", + Some(r##"Sandbox only. Retrieves an order template that can be used to quickly create a new order in sandbox."##), + "Details at http://byron.github.io/google-apis-rs/google_content2_sandbox_cli/orders_gettestordertemplate", + vec![ + (Some(r##"merchant-id"##), + None, + Some(r##"The ID of the managing account."##), + Some(true), + Some(false)), + + (Some(r##"template-name"##), + None, + Some(r##"The name of the template to retrieve."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Lists the orders in your Merchant Center account."##), + "Details at http://byron.github.io/google-apis-rs/google_content2_sandbox_cli/orders_list", + vec![ + (Some(r##"merchant-id"##), + None, + Some(r##"The ID of the managing account."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("refund", + Some(r##"Refund a portion of the order, up to the full amount paid."##), + "Details at http://byron.github.io/google-apis-rs/google_content2_sandbox_cli/orders_refund", + vec![ + (Some(r##"merchant-id"##), + None, + Some(r##"The ID of the managing account."##), + Some(true), + Some(false)), + + (Some(r##"order-id"##), + None, + Some(r##"The ID of the order to refund."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("returnlineitem", + Some(r##"Returns a line item."##), + "Details at http://byron.github.io/google-apis-rs/google_content2_sandbox_cli/orders_returnlineitem", + vec![ + (Some(r##"merchant-id"##), + None, + Some(r##"The ID of the managing account."##), + Some(true), + Some(false)), + + (Some(r##"order-id"##), + None, + Some(r##"The ID of the order."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("shiplineitems", + Some(r##"Marks line item(s) as shipped."##), + "Details at http://byron.github.io/google-apis-rs/google_content2_sandbox_cli/orders_shiplineitems", + vec![ + (Some(r##"merchant-id"##), + None, + Some(r##"The ID of the managing account."##), + Some(true), + Some(false)), + + (Some(r##"order-id"##), + None, + Some(r##"The ID of the order."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("updatemerchantorderid", + Some(r##"Updates the merchant order ID for a given order."##), + "Details at http://byron.github.io/google-apis-rs/google_content2_sandbox_cli/orders_updatemerchantorderid", + vec![ + (Some(r##"merchant-id"##), + None, + Some(r##"The ID of the managing account."##), + Some(true), + Some(false)), + + (Some(r##"order-id"##), + None, + Some(r##"The ID of the order."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("updateshipment", + Some(r##"Updates a shipment's status, carrier, and/or tracking ID."##), + "Details at http://byron.github.io/google-apis-rs/google_content2_sandbox_cli/orders_updateshipment", + vec![ + (Some(r##"merchant-id"##), + None, + Some(r##"The ID of the managing account."##), + Some(true), + Some(false)), + + (Some(r##"order-id"##), + None, + Some(r##"The ID of the order."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ]; + + let mut app = App::new("content2-sandbox") + .author("Sebastian Thiel ") + .version("0.3.2+20151002") + .about("Manage product items, inventory, and Merchant Center accounts for Google Shopping.") + .after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_content2_sandbox_cli") + .arg(Arg::with_name("url") + .long("scope") + .help("Specify the authentication a method should be executed in. Each scope requires the user to grant this application permission to use it.If unset, it defaults to the shortest scope url for a particular method.") + .multiple(true) + .takes_value(true)) + .arg(Arg::with_name("folder") + .long("config-dir") + .help("A directory into which we will store our persistent data. Defaults to a user-writable directory that we will create during the first invocation.[default: ~/.google-service-cli") + .multiple(false) + .takes_value(true)) + .arg(Arg::with_name("debug") + .long("debug") + .help("Output all server communication to standard error. `tx` and `rx` are placed into the same stream.") + .multiple(false) + .takes_value(false)) + .arg(Arg::with_name("debug-auth") + .long("debug-auth") + .help("Output all communication related to authentication to standard error. `tx` and `rx` are placed into the same stream.") + .multiple(false) + .takes_value(false)); + + for &(main_command_name, ref about, ref subcommands) in arg_data.iter() { + let mut mcmd = SubCommand::with_name(main_command_name).about(about); + + for &(sub_command_name, ref desc, url_info, ref args) in subcommands { + let mut scmd = SubCommand::with_name(sub_command_name); + if let &Some(desc) = desc { + scmd = scmd.about(desc); + } + scmd = scmd.after_help(url_info); + + for &(ref arg_name, ref flag, ref desc, ref required, ref multi) in args { + let arg_name_str = + match (arg_name, flag) { + (&Some(an), _ ) => an, + (_ , &Some(f)) => f, + _ => unreachable!(), + }; + let mut arg = Arg::with_name(arg_name_str) + .empty_values(false); + if let &Some(short_flag) = flag { + arg = arg.short(short_flag); + } + if let &Some(desc) = desc { + arg = arg.help(desc); + } + if arg_name.is_some() && flag.is_some() { + arg = arg.takes_value(true); + } + if let &Some(required) = required { + arg = arg.required(required); + } + if let &Some(multi) = multi { + arg = arg.multiple(multi); + } + scmd = scmd.arg(arg); + } + mcmd = mcmd.subcommand(scmd); + } + app = app.subcommand(mcmd); + } + + let matches = app.get_matches(); + + let debug = matches.is_present("debug"); + match Engine::new(matches) { + Err(err) => { + exit_status = err.exit_code; + writeln!(io::stderr(), "{}", err).ok(); + }, + Ok(engine) => { + if let Err(doit_err) = engine.doit() { + exit_status = 1; + match doit_err { + DoitError::IoError(path, err) => { + writeln!(io::stderr(), "Failed to open output file '{}': {}", path, err).ok(); + }, + DoitError::ApiError(err) => { + if debug { + writeln!(io::stderr(), "{:#?}", err).ok(); + } else { + writeln!(io::stderr(), "{}", err).ok(); + } + } + } + } + } + } + + std::process::exit(exit_status); +} \ No newline at end of file diff --git a/gen/content2_sandbox/Cargo.toml b/gen/content2_sandbox/Cargo.toml new file mode 100644 index 0000000000..0cbd46b256 --- /dev/null +++ b/gen/content2_sandbox/Cargo.toml @@ -0,0 +1,29 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-content2_sandbox" +version = "0.1.9+20151002" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with Shopping Content (protocol v2sandbox)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/content2_sandbox" +homepage = "https://developers.google.com/shopping-content" +documentation = "http://byron.github.io/google-apis-rs/google_content2_sandbox" +license = "MIT" +keywords = ["content", "google", "protocol", "web", "api"] +build = "src/build.rs" + + +[dependencies] +hyper = ">= 0.6.8" +mime = "0.1.0" +serde = ">= 0.6.0" +serde_json = ">= 0.6.0" +yup-oauth2 = "*" +url = "*" + +[build-dependencies] +syntex = { version = "*" } +serde_codegen = { version = "*" } + diff --git a/gen/content2_sandbox/LICENSE.md b/gen/content2_sandbox/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/content2_sandbox/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_sandbox/README.md b/gen/content2_sandbox/README.md new file mode 100644 index 0000000000..c9c711f916 --- /dev/null +++ b/gen/content2_sandbox/README.md @@ -0,0 +1,194 @@ + +The `google-content2_sandbox` library allows access to all features of the *Google Shopping Content* service. + +This documentation was generated from *Shopping Content* crate version *0.1.9+20151002*, where *20151002* is the exact revision of the *content:v2sandbox* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. + +Everything else about the *Shopping Content* *v2_sandbox* API can be found at the +[official documentation site](https://developers.google.com/shopping-content). +# Features + +Handle the following *Resources* with ease from the central [hub](http://byron.github.io/google-apis-rs/google_content2_sandbox/struct.ShoppingContent.html) ... + +* [orders](http://byron.github.io/google-apis-rs/google_content2_sandbox/struct.Order.html) + * [*acknowledge*](http://byron.github.io/google-apis-rs/google_content2_sandbox/struct.OrderAcknowledgeCall.html), [*advancetestorder*](http://byron.github.io/google-apis-rs/google_content2_sandbox/struct.OrderAdvancetestorderCall.html), [*cancel*](http://byron.github.io/google-apis-rs/google_content2_sandbox/struct.OrderCancelCall.html), [*cancellineitem*](http://byron.github.io/google-apis-rs/google_content2_sandbox/struct.OrderCancellineitemCall.html), [*createtestorder*](http://byron.github.io/google-apis-rs/google_content2_sandbox/struct.OrderCreatetestorderCall.html), [*custombatch*](http://byron.github.io/google-apis-rs/google_content2_sandbox/struct.OrderCustombatchCall.html), [*get*](http://byron.github.io/google-apis-rs/google_content2_sandbox/struct.OrderGetCall.html), [*getbymerchantorderid*](http://byron.github.io/google-apis-rs/google_content2_sandbox/struct.OrderGetbymerchantorderidCall.html), [*gettestordertemplate*](http://byron.github.io/google-apis-rs/google_content2_sandbox/struct.OrderGettestordertemplateCall.html), [*list*](http://byron.github.io/google-apis-rs/google_content2_sandbox/struct.OrderListCall.html), [*refund*](http://byron.github.io/google-apis-rs/google_content2_sandbox/struct.OrderRefundCall.html), [*returnlineitem*](http://byron.github.io/google-apis-rs/google_content2_sandbox/struct.OrderReturnlineitemCall.html), [*shiplineitems*](http://byron.github.io/google-apis-rs/google_content2_sandbox/struct.OrderShiplineitemCall.html), [*updatemerchantorderid*](http://byron.github.io/google-apis-rs/google_content2_sandbox/struct.OrderUpdatemerchantorderidCall.html) and [*updateshipment*](http://byron.github.io/google-apis-rs/google_content2_sandbox/struct.OrderUpdateshipmentCall.html) + + + + +# Structure of this Library + +The API is structured into the following primary items: + +* **[Hub](http://byron.github.io/google-apis-rs/google_content2_sandbox/struct.ShoppingContent.html)** + * a central object to maintain state and allow accessing all *Activities* + * creates [*Method Builders*](http://byron.github.io/google-apis-rs/google_content2_sandbox/trait.MethodsBuilder.html) which in turn + allow access to individual [*Call Builders*](http://byron.github.io/google-apis-rs/google_content2_sandbox/trait.CallBuilder.html) +* **[Resources](http://byron.github.io/google-apis-rs/google_content2_sandbox/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_sandbox/trait.Part.html)** + * a collection of properties + * never directly used in *Activities* +* **[Activities](http://byron.github.io/google-apis-rs/google_content2_sandbox/trait.CallBuilder.html)** + * operations to apply to *Resources* + +All *structures* are marked with applicable traits to further categorize them and ease browsing. + +Generally speaking, you can invoke *Activities* like this: + +```Rust,ignore +let r = hub.resource().activity(...).doit() +``` + +Or specifically ... + +```ignore +let r = hub.orders().get(...).doit() +let r = hub.orders().list(...).doit() +let r = hub.orders().updateshipment(...).doit() +let r = hub.orders().advancetestorder(...).doit() +let r = hub.orders().updatemerchantorderid(...).doit() +let r = hub.orders().returnlineitem(...).doit() +let r = hub.orders().gettestordertemplate(...).doit() +let r = hub.orders().createtestorder(...).doit() +let r = hub.orders().refund(...).doit() +let r = hub.orders().custombatch(...).doit() +let r = hub.orders().cancellineitem(...).doit() +let r = hub.orders().getbymerchantorderid(...).doit() +let r = hub.orders().acknowledge(...).doit() +let r = hub.orders().cancel(...).doit() +let r = hub.orders().shiplineitems(...).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_sandbox = "*" +``` + +## A complete example + +```Rust +extern crate hyper; +extern crate yup_oauth2 as oauth2; +extern crate google_content2_sandbox as content2_sandbox; +use content2_sandbox::{Result, Error}; +use std::default::Default; +use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +use content2_sandbox::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); +// You can configure optional parameters by calling the respective setters at will, and +// execute the final call using `doit()`. +// Values shown here are possibly random and not representative ! +let result = hub.orders().list("merchantId") + .add_statuses("sit") + .placed_date_start("Stet") + .placed_date_end("sed") + .page_token("et") + .order_by("dolores") + .max_results(38) + .acknowledged(true) + .doit(); + +match result { + Err(e) => match e { + // The Error enum provides details about what exactly happened. + // You can also just use its `Debug`, `Display` or `Error` traits + Error::HttpError(_) + |Error::MissingAPIKey + |Error::MissingToken(_) + |Error::Cancelled + |Error::UploadSizeLimitExceeded(_, _) + |Error::Failure(_) + |Error::BadRequest(_) + |Error::FieldClash(_) + |Error::JsonDecodeError(_, _) => println!("{}", e), + }, + Ok(res) => println!("Success: {:?}", res), +} + +``` +## Handling Errors + +All errors produced by the system are provided either as [Result](http://byron.github.io/google-apis-rs/google_content2_sandbox/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_sandbox/trait.Delegate.html), or the [Authenticator Delegate](http://byron.github.io/google-apis-rs/google_content2_sandbox/../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 Downloads +If a method supports downloads, the response body, which is part of the [Result](http://byron.github.io/google-apis-rs/google_content2_sandbox/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_sandbox/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_sandbox/trait.Delegate.html) to the +[Method Builder](http://byron.github.io/google-apis-rs/google_content2_sandbox/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_sandbox/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_sandbox/trait.RequestValue.html) and +[decodable](http://byron.github.io/google-apis-rs/google_content2_sandbox/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_sandbox/trait.Part.html) which are identifiable 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_sandbox/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_sandbox/trait.RequestValue.html) are moved + +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_sandbox** 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_sandbox/src/build.rs b/gen/content2_sandbox/src/build.rs new file mode 100644 index 0000000000..57cdec78d3 --- /dev/null +++ b/gen/content2_sandbox/src/build.rs @@ -0,0 +1,16 @@ +extern crate syntex; +extern crate serde_codegen; + +use std::env; +use std::path::Path; + +pub fn main() { + let out_dir = env::var_os("OUT_DIR").unwrap(); + + let src = Path::new("src/lib.rs.in"); + let dst = Path::new(&out_dir).join("lib.rs"); + + let mut registry = syntex::Registry::new(); + serde_codegen::register(&mut registry); + registry.expand("google-content2_sandbox", &src, &dst).unwrap(); +} diff --git a/gen/content2_sandbox/src/cmn.rs b/gen/content2_sandbox/src/cmn.rs new file mode 100644 index 0000000000..0e31353ba3 --- /dev/null +++ b/gen/content2_sandbox/src/cmn.rs @@ -0,0 +1,762 @@ +// COPY OF 'src/rust/api/cmn.rs' +// DO NOT EDIT +use std::io::{self, Read, Seek, Cursor, Write, SeekFrom}; +use std; +use std::fmt::{self, Display}; +use std::str::FromStr; +use std::error; +use std::thread::sleep_ms; + +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::h1::LINE_ENDING; +use hyper::method::Method; +use hyper::status::StatusCode; + +use serde_json as json; + +/// 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 {} + +/// Identifies types for building methods of a particular resource type +pub trait MethodsBuilder {} + +/// Identifies types which represent builders for a particular resource method +pub trait CallBuilder {} + +/// Identifies types which can be inserted and deleted. +/// Types with this trait are most commonly used by clients of this API. +pub trait Resource {} + +/// Identifies types which are used in API responses. +pub trait ResponseResult {} + +/// Identifies types which are used in API requests. +pub trait RequestValue {} + +/// Identifies types which are not actually used by the API +/// This might be a bug within the google API schema. +pub trait UnusedType {} + +/// Identifies types which are only used as part of other types, which +/// usually are carrying the `Resource` trait. +pub trait Part {} + +/// 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 {} + +/// 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 +} + +/// A utility to represent detailed errors we might see in case there are BadRequests. +/// The latter happen if the sent parameters or request structures are unsound +#[derive(Deserialize, Serialize, Debug)] +pub struct ErrorResponse { + error: ServerError, +} + +#[derive(Deserialize, Serialize, Debug)] +pub struct ServerError { + errors: Vec, + code: u16, + message: String, +} + +#[derive(Deserialize, Serialize, Debug)] +pub struct ServerMessage { + domain: String, + reason: String, + message: String, + #[serde(rename="locationType")] + location_type: Option, + location: 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 successful. That way, the delegate 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. + /// + /// If you choose to retry after a duration, the duration should be chosen using the + /// [exponential backoff algorithm](http://en.wikipedia.org/wiki/Exponential_backoff). + /// + /// Return retry information. + fn http_error(&mut self, &hyper::Error) -> 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 it as a general information about the + /// impending failure. + /// The given Error provides information about why the token couldn't be acquired in the + /// first place + fn token(&mut self, err: &error::Error) -> Option { + let _ = err; + 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/canceled, 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()`. + /// It will also be called with None after a successful upload, which allows the delegate + /// to forget the URL. That way, we will not attempt to resume an upload that has already + /// finished. + fn store_upload_url(&mut self, url: Option<&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: &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. + /// + /// If you choose to retry after a duration, the duration should be chosen using the + /// [exponential backoff algorithm](http://en.wikipedia.org/wiki/Exponential_backoff). + fn http_failure(&mut self, _: &hyper::client::Response, Option, _: 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 {} + + +#[derive(Debug)] +pub enum Error { + /// The http connection failed + HttpError(hyper::Error), + + /// 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), + + /// Represents information about a request that was not understood by the server. + /// Details are included. + BadRequest(ErrorResponse), + + /// 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(Box), + + /// 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(String, json::Error), + + /// Indicates an HTTP repsonse with a non-success status code + Failure(hyper::client::Response), +} + + +impl Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + Error::HttpError(ref err) => err.fmt(f), + Error::UploadSizeLimitExceeded(ref resource_size, ref max_size) => + writeln!(f, "The media size {} exceeds the maximum allowed upload size of {}" + , resource_size, max_size), + Error::MissingAPIKey => { + (writeln!(f, "The application's API key was not found in the configuration")).ok(); + writeln!(f, "It is used as there are no Scopes defined for this method.") + }, + Error::BadRequest(ref err) => { + try!(writeln!(f, "Bad Requst ({}): {}", err.error.code, err.error.message)); + for err in err.error.errors.iter() { + try!(writeln!(f, " {}: {}, {}{}", + err.domain, + err.message, + err.reason, + match &err.location { + &Some(ref loc) => format!("@{}", loc), + &None => String::new(), + })); + } + Ok(()) + }, + Error::MissingToken(ref err) => + writeln!(f, "Token retrieval failed with error: {}", err), + Error::Cancelled => + writeln!(f, "Operation cancelled by delegate"), + Error::FieldClash(field) => + writeln!(f, "The custom parameter '{}' is already provided natively by the CallBuilder.", field), + Error::JsonDecodeError(ref json_str, ref err) + => writeln!(f, "{}: {}", err, json_str), + Error::Failure(ref response) => + writeln!(f, "Http status indicates failure: {:?}", response), + } + } +} + +impl error::Error for Error { + fn description(&self) -> &str { + match *self { + Error::HttpError(ref err) => err.description(), + Error::JsonDecodeError(_, ref err) => err.description(), + _ => "NO DESCRIPTION POSSIBLE - use `Display.fmt()` instead" + } + } + + fn cause(&self) -> Option<&error::Error> { + match *self { + Error::HttpError(ref err) => err.cause(), + Error::JsonDecodeError(_, ref err) => err.cause(), + _ => None + } + } +} + +/// A universal result type used as return for all calls. +pub type Result = std::result::Result; + +/// 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 + 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 following macro invocation needs to be expanded, as `include!` +// doens't support external macros +// header!{ +// #[doc="The `X-Upload-Content-Type` header."] +// (XUploadContentType, "X-Upload-Content-Type") => [Mime] + +// xupload_content_type { +// test_header!( +// test1, +// vec![b"text/plain"], +// Some(HeaderField( +// vec![Mime(TopLevel::Text, SubLevel::Plain, Vec::new())] +// ))); + +// } +// } + +/// The `X-Upload-Content-Type` header. +/// +/// Generated via rustc --pretty expanded -Z unstable-options, and manually +/// processed to be more readable. +#[derive(PartialEq, Debug, Clone)] +pub struct XUploadContentType(pub Mime); + +impl ::std::ops::Deref for XUploadContentType { + type Target = Mime; + fn deref<'a>(&'a self) -> &'a Mime { &self.0 } +} +impl ::std::ops::DerefMut for XUploadContentType { + fn deref_mut<'a>(&'a mut self) -> &'a mut Mime { &mut self.0 } +} +impl Header for XUploadContentType { + fn header_name() -> &'static str { "X-Upload-Content-Type" } + fn parse_header(raw: &[Vec]) -> hyper::error::Result { + hyper::header::parsing::from_one_raw_str(raw).map(XUploadContentType) + } +} +impl HeaderFormat for XUploadContentType { + fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { + Display::fmt(&**self, f) + } +} +impl Display for XUploadContentType { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Display::fmt(&**self, f) + } +} + +#[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]) -> hyper::error::Result { + Err(hyper::error::Error::Method) + } +} + + +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]) -> hyper::error::Result { + if raw.len() > 0 { + let v = &raw[0]; + if let Ok(s) = std::str::from_utf8(v) { + const PREFIX: &'static str = "bytes "; + if s.starts_with(PREFIX) { + if let Ok(c) = ::from_str(&s[PREFIX.len()..]) { + return Ok(RangeResponseHeader(c)) + } + } + } + } + Err(hyper::error::Error::Method) + } +} + +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, 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, A> ResumableUploadHelper<'a, A> + where A: oauth2::GetToken { + + fn query_transfer_status(&mut self) -> std::result::Result> { + 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, None) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + return Err(Ok(r)) + } + }; + return Ok(h.0.last) + } + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + return Err(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() { + Ok(s) => s, + Err(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 + }; + + self.reader.seek(SeekFrom::Start(start)).unwrap(); + loop { + let request_size = match self.content_length - start { + rs if rs > chunk_size => chunk_size, + rs => rs + }; + + 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 + } + // workaround https://github.com/rust-lang/rust/issues/22252 + let res = 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(); + match res { + 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, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + } + return Some(Ok(res)) + }, + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + return Some(Err(err)) + } + } + } + } +} + +// Copy of src/rust/cli/cmn.rs +// TODO(ST): Allow sharing common code between program types +pub fn remove_json_null_values(value: &mut json::value::Value) { + match *value { + json::value::Value::Object(ref mut map) => { + let mut for_removal = Vec::new(); + + for (key, mut value) in map.iter_mut() { + if value.is_null() { + for_removal.push(key.clone()); + } else { + remove_json_null_values(&mut value); + } + } + + for key in &for_removal { + map.remove(key); + } + } + _ => {} + } +} diff --git a/gen/content2_sandbox/src/lib.rs b/gen/content2_sandbox/src/lib.rs new file mode 100644 index 0000000000..a43e70e2e3 --- /dev/null +++ b/gen/content2_sandbox/src/lib.rs @@ -0,0 +1,198 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/api/lib.rs.mako' +// DO NOT EDIT ! + +//! This documentation was generated from *Shopping Content* crate version *0.1.9+20151002*, where *20151002* is the exact revision of the *content:v2sandbox* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +//! +//! Everything else about the *Shopping Content* *v2_sandbox* API can be found at the +//! [official documentation site](https://developers.google.com/shopping-content). +//! The original source code is [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/content2_sandbox). +//! # Features +//! +//! Handle the following *Resources* with ease from the central [hub](struct.ShoppingContent.html) ... +//! +//! * [orders](struct.Order.html) +//! * [*acknowledge*](struct.OrderAcknowledgeCall.html), [*advancetestorder*](struct.OrderAdvancetestorderCall.html), [*cancel*](struct.OrderCancelCall.html), [*cancellineitem*](struct.OrderCancellineitemCall.html), [*createtestorder*](struct.OrderCreatetestorderCall.html), [*custombatch*](struct.OrderCustombatchCall.html), [*get*](struct.OrderGetCall.html), [*getbymerchantorderid*](struct.OrderGetbymerchantorderidCall.html), [*gettestordertemplate*](struct.OrderGettestordertemplateCall.html), [*list*](struct.OrderListCall.html), [*refund*](struct.OrderRefundCall.html), [*returnlineitem*](struct.OrderReturnlineitemCall.html), [*shiplineitems*](struct.OrderShiplineitemCall.html), [*updatemerchantorderid*](struct.OrderUpdatemerchantorderidCall.html) and [*updateshipment*](struct.OrderUpdateshipmentCall.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* +//! * creates [*Method Builders*](trait.MethodsBuilder.html) which in turn +//! allow access to individual [*Call Builders*](trait.CallBuilder.html) +//! * **[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* +//! +//! All *structures* are marked with applicable traits to further categorize them and ease browsing. +//! +//! Generally speaking, you can invoke *Activities* like this: +//! +//! ```Rust,ignore +//! let r = hub.resource().activity(...).doit() +//! ``` +//! +//! Or specifically ... +//! +//! ```ignore +//! let r = hub.orders().get(...).doit() +//! let r = hub.orders().list(...).doit() +//! let r = hub.orders().updateshipment(...).doit() +//! let r = hub.orders().advancetestorder(...).doit() +//! let r = hub.orders().updatemerchantorderid(...).doit() +//! let r = hub.orders().returnlineitem(...).doit() +//! let r = hub.orders().gettestordertemplate(...).doit() +//! let r = hub.orders().createtestorder(...).doit() +//! let r = hub.orders().refund(...).doit() +//! let r = hub.orders().custombatch(...).doit() +//! let r = hub.orders().cancellineitem(...).doit() +//! let r = hub.orders().getbymerchantorderid(...).doit() +//! let r = hub.orders().acknowledge(...).doit() +//! let r = hub.orders().cancel(...).doit() +//! let r = hub.orders().shiplineitems(...).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_sandbox = "*" +//! ``` +//! +//! ## A complete example +//! +//! ```test_harness,no_run +//! extern crate hyper; +//! extern crate yup_oauth2 as oauth2; +//! extern crate google_content2_sandbox as content2_sandbox; +//! use content2_sandbox::{Result, Error}; +//! # #[test] fn egal() { +//! use std::default::Default; +//! use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +//! use content2_sandbox::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); +//! // You can configure optional parameters by calling the respective setters at will, and +//! // execute the final call using `doit()`. +//! // Values shown here are possibly random and not representative ! +//! let result = hub.orders().list("merchantId") +//! .add_statuses("duo") +//! .placed_date_start("et") +//! .placed_date_end("eirmod") +//! .page_token("sanctus") +//! .order_by("et") +//! .max_results(55) +//! .acknowledged(true) +//! .doit(); +//! +//! match result { +//! Err(e) => match e { +//! // The Error enum provides details about what exactly happened. +//! // You can also just use its `Debug`, `Display` or `Error` traits +//! Error::HttpError(_) +//! |Error::MissingAPIKey +//! |Error::MissingToken(_) +//! |Error::Cancelled +//! |Error::UploadSizeLimitExceeded(_, _) +//! |Error::Failure(_) +//! |Error::BadRequest(_) +//! |Error::FieldClash(_) +//! |Error::JsonDecodeError(_, _) => println!("{}", e), +//! }, +//! Ok(res) => println!("Success: {:?}", res), +//! } +//! # } +//! ``` +//! ## 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 Downloads +//! 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 identifiable 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 moved +//! +//! 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 +//! +//! + +// 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)] + +include!(concat!(env!("OUT_DIR"), "/lib.rs")); \ No newline at end of file diff --git a/gen/content2_sandbox/src/lib.rs.in b/gen/content2_sandbox/src/lib.rs.in new file mode 100644 index 0000000000..84b2fd1bd6 --- /dev/null +++ b/gen/content2_sandbox/src/lib.rs.in @@ -0,0 +1,5948 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/api/lib.rs.in.mako' +// DO NOT EDIT ! + +extern crate hyper; +extern crate serde; +extern crate serde_json; +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 serde_json as json; +use std::io; +use std::fs; +use std::thread::sleep_ms; + +pub use cmn::{MultiPartReader, ToParts, MethodInfo, Result, Error, CallBuilder, Hub, ReadSeek, Part, + ResponseResult, RequestValue, NestedType, Delegate, DefaultDelegate, MethodsBuilder, + Resource, ErrorResponse, remove_json_null_values}; + + +// ############## +// 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 AsRef for Scope { + fn as_ref(&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_sandbox as content2_sandbox; +/// use content2_sandbox::{Result, Error}; +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use content2_sandbox::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); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.orders().list("merchantId") +/// .add_statuses("justo") +/// .placed_date_start("amet.") +/// .placed_date_end("erat") +/// .page_token("labore") +/// .order_by("sea") +/// .max_results(11) +/// .acknowledged(true) +/// .doit(); +/// +/// match result { +/// Err(e) => match e { +/// // The Error enum provides details about what exactly happened. +/// // You can also just use its `Debug`, `Display` or `Error` traits +/// Error::HttpError(_) +/// |Error::MissingAPIKey +/// |Error::MissingToken(_) +/// |Error::Cancelled +/// |Error::UploadSizeLimitExceeded(_, _) +/// |Error::Failure(_) +/// |Error::BadRequest(_) +/// |Error::FieldClash(_) +/// |Error::JsonDecodeError(_, _) => println!("{}", e), +/// }, +/// Ok(res) => println!("Success: {:?}", res), +/// } +/// # } +/// ``` +pub struct ShoppingContent { + client: RefCell, + auth: RefCell, + _user_agent: String, +} + +impl<'a, C, A> Hub for ShoppingContent {} + +impl<'a, C, A> ShoppingContent + where 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.9".to_string(), + } + } + + pub fn orders(&'a self) -> OrderMethods<'a, C, A> { + OrderMethods { 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.9`. + /// + /// 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, Deserialize)] +pub struct OrderLineItemShippingDetailsMethod { + /// Minimum transit time. + #[serde(rename="minDaysInTransit")] + pub min_days_in_transit: Option, + /// The carrier for the shipping. Optional. + pub carrier: Option, + /// The name of the shipping method. + #[serde(rename="methodName")] + pub method_name: Option, + /// Maximum transit time. + #[serde(rename="maxDaysInTransit")] + pub max_days_in_transit: Option, +} + +impl Part for OrderLineItemShippingDetailsMethod {} + + +/// 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 OrderReturn { + /// Quantity that is returned. + pub quantity: Option, + /// The reason for the return. + pub reason: Option, + /// Date on which the item has been created, in ISO 8601 format. + #[serde(rename="creationDate")] + pub creation_date: Option, + /// The actor that created the refund. + pub actor: Option, + /// The explanation of the reason. + #[serde(rename="reasonText")] + pub reason_text: Option, +} + +impl Part for OrderReturn {} + + +/// 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, Serialize, Deserialize)] +pub struct Errors { + /// The message of the first error in errors. + pub message: Option, + /// The HTTP status of the first error in errors. + pub code: Option, + /// A list of errors. + pub errors: Option>, +} + +impl Part for Errors {} + + +/// 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*). +/// +/// * [advancetestorder orders](struct.OrderAdvancetestorderCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct OrdersAdvanceTestOrderResponse { + /// Identifies what kind of resource this is. Value: the fixed string "content#ordersAdvanceTestOrderResponse". + pub kind: Option, +} + +impl ResponseResult for OrdersAdvanceTestOrderResponse {} + + +/// 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 OrdersCustomBatchRequestEntryUpdateShipment { + /// New status for the shipment. Not updated if missing. + pub status: Option, + /// The carrier handling the shipment. Not updated if missing. + pub carrier: Option, + /// The tracking id for the shipment. Not updated if missing. + #[serde(rename="trackingId")] + pub tracking_id: Option, + /// The ID of the shipment. + #[serde(rename="shipmentId")] + pub shipment_id: Option, +} + +impl Part for OrdersCustomBatchRequestEntryUpdateShipment {} + + +/// 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 ErrorType { + /// The error code. + pub reason: Option, + /// A description of the error. + pub message: Option, + /// The domain of the error. + pub domain: Option, +} + +impl Part for ErrorType {} + + +/// 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 orders](struct.OrderCustombatchCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct OrdersCustomBatchRequest { + /// The request entries to be processed in the batch. + pub entries: Option>, +} + +impl RequestValue for OrdersCustomBatchRequest {} + + +/// 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*). +/// +/// * [shiplineitems orders](struct.OrderShiplineitemCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct OrdersShipLineItemsRequest { + /// The ID of the operation. Unique across all operations for a given order. + #[serde(rename="operationId")] + pub operation_id: Option, + /// Line items to ship. + #[serde(rename="lineItems")] + pub line_items: Option>, + /// The carrier handling the shipment. + pub carrier: Option, + /// The tracking id for the shipment. + #[serde(rename="trackingId")] + pub tracking_id: Option, + /// The ID of the shipment. + #[serde(rename="shipmentId")] + pub shipment_id: Option, +} + +impl RequestValue for OrdersShipLineItemsRequest {} + + +/// 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 OrderShipment { + /// The status of the shipment. + pub status: Option, + /// Date on which the shipment has been created, in ISO 8601 format. + #[serde(rename="creationDate")] + pub creation_date: Option, + /// The carrier handling the shipment. + pub carrier: Option, + /// The tracking id for the shipment. + #[serde(rename="trackingId")] + pub tracking_id: Option, + /// Date on which the shipment has been delivered, in ISO 8601 format. Present only if status is delievered + #[serde(rename="deliveryDate")] + pub delivery_date: Option, + /// The line items that are shipped. + #[serde(rename="lineItems")] + pub line_items: Option>, + /// The id of the shipment. + pub id: Option, +} + +impl Part for OrderShipment {} + + +/// 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 TestOrderLineItem { + /// Details of the return policy for the line item. + #[serde(rename="returnInfo")] + pub return_info: Option, + /// Product data from the time of the order placement. + pub product: Option, + /// Unit tax for the line item. + #[serde(rename="unitTax")] + pub unit_tax: Option, + /// Number of items ordered. + #[serde(rename="quantityOrdered")] + pub quantity_ordered: Option, + /// Details of the requested shipping for the line item. + #[serde(rename="shippingDetails")] + pub shipping_details: Option, +} + +impl Part for TestOrderLineItem {} + + +/// 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*). +/// +/// * [updatemerchantorderid orders](struct.OrderUpdatemerchantorderidCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct OrdersUpdateMerchantOrderIdResponse { + /// Identifies what kind of resource this is. Value: the fixed string "content#ordersUpdateMerchantOrderIdResponse". + pub kind: Option, + /// The status of the execution. + #[serde(rename="executionStatus")] + pub execution_status: Option, +} + +impl ResponseResult for OrdersUpdateMerchantOrderIdResponse {} + + +/// 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*). +/// +/// * [updateshipment orders](struct.OrderUpdateshipmentCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct OrdersUpdateShipmentResponse { + /// Identifies what kind of resource this is. Value: the fixed string "content#ordersUpdateShipmentResponse". + pub kind: Option, + /// The status of the execution. + #[serde(rename="executionStatus")] + pub execution_status: Option, +} + +impl ResponseResult for OrdersUpdateShipmentResponse {} + + +/// 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 OrderRefund { + /// The amount that is refunded. + pub amount: Option, + /// Date on which the item has been created, in ISO 8601 format. + #[serde(rename="creationDate")] + pub creation_date: Option, + /// The reason for the refund. + pub reason: Option, + /// The actor that created the refund. + pub actor: Option, + /// The explanation of the reason. + #[serde(rename="reasonText")] + pub reason_text: Option, +} + +impl Part for OrderRefund {} + + +/// 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 OrderLineItemShippingDetails { + /// The delivery by date, in ISO 8601 format. + #[serde(rename="deliverByDate")] + pub deliver_by_date: Option, + /// Details of the shipping method. + pub method: Option, + /// The ship by date, in ISO 8601 format. + #[serde(rename="shipByDate")] + pub ship_by_date: Option, +} + +impl Part for OrderLineItemShippingDetails {} + + +/// 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: Option, + /// The price represented as a number. + pub value: Option, +} + +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*). +/// +/// * [get orders](struct.OrderGetCall.html) (response) +/// * [list orders](struct.OrderListCall.html) (none) +/// * [updateshipment orders](struct.OrderUpdateshipmentCall.html) (none) +/// * [advancetestorder orders](struct.OrderAdvancetestorderCall.html) (none) +/// * [updatemerchantorderid orders](struct.OrderUpdatemerchantorderidCall.html) (none) +/// * [returnlineitem orders](struct.OrderReturnlineitemCall.html) (none) +/// * [gettestordertemplate orders](struct.OrderGettestordertemplateCall.html) (none) +/// * [createtestorder orders](struct.OrderCreatetestorderCall.html) (none) +/// * [refund orders](struct.OrderRefundCall.html) (none) +/// * [custombatch orders](struct.OrderCustombatchCall.html) (none) +/// * [cancellineitem orders](struct.OrderCancellineitemCall.html) (none) +/// * [getbymerchantorderid orders](struct.OrderGetbymerchantorderidCall.html) (none) +/// * [acknowledge orders](struct.OrderAcknowledgeCall.html) (none) +/// * [cancel orders](struct.OrderCancelCall.html) (none) +/// * [shiplineitems orders](struct.OrderShiplineitemCall.html) (none) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Order { + /// Shipments of the order. + pub shipments: Option>, + /// The status of the order. + pub status: Option, + /// The status of the payment. + #[serde(rename="paymentStatus")] + pub payment_status: Option, + /// The net amount for the order. For example, if an order was originally for a grand total of $100 and a refund was issued for $20, the net amount will be $80. + #[serde(rename="netAmount")] + pub net_amount: Option, + /// The REST id of the order. Globally unique. + pub id: Option, + /// The details of the customer who placed the order. + pub customer: Option, + /// Identifies what kind of resource this is. Value: the fixed string "content#order". + pub kind: Option, + /// Line items that are ordered. + #[serde(rename="lineItems")] + pub line_items: Option>, + /// Refunds for the order. + pub refunds: Option>, + /// Whether the order was acknowledged. + pub acknowledged: Option, + /// The total cost of shipping for all items. + #[serde(rename="shippingCost")] + pub shipping_cost: Option, + /// no description provided + #[serde(rename="merchantId")] + pub merchant_id: Option, + /// Merchant-provided id of the order. + #[serde(rename="merchantOrderId")] + pub merchant_order_id: Option, + /// The requested shipping option. + #[serde(rename="shippingOption")] + pub shipping_option: Option, + /// The details for the delivery. + #[serde(rename="deliveryDetails")] + pub delivery_details: Option, + /// The date when the order was placed, in ISO 8601 format. + #[serde(rename="placedDate")] + pub placed_date: Option, + /// The tax for the total shipping cost. + #[serde(rename="shippingCostTax")] + pub shipping_cost_tax: Option, + /// The details of the payment method. + #[serde(rename="paymentMethod")] + pub payment_method: Option, +} + +impl Resource for Order {} +impl ResponseResult for Order {} + + +/// 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 TestOrderPaymentMethod { + /// The card expiration month (January = 1, February = 2 etc.). + #[serde(rename="expirationMonth")] + pub expiration_month: Option, + /// The last four digits of the card number. + #[serde(rename="lastFourDigits")] + pub last_four_digits: Option, + /// The card expiration year (4-digit, e.g. 2015). + #[serde(rename="expirationYear")] + pub expiration_year: Option, + /// The type of instrument. Note that real orders might have different values than the four values accepted by createTestOrder. + #[serde(rename="type")] + pub type_: Option, + /// The billing address. + #[serde(rename="predefinedBillingAddress")] + pub predefined_billing_address: Option, +} + +impl Part for TestOrderPaymentMethod {} + + +/// 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 OrderAddress { + /// City, town or commune. May also include dependent localities or sublocalities (e.g. neighborhoods or suburbs). + pub locality: Option, + /// CLDR country code (e.g. "US"). + pub country: Option, + /// Strings representing the lines of the printed label for mailing the order, for example: + /// John Smith + /// 1600 Amphitheatre Parkway + /// Mountain View, CA, 94043 + /// United States + #[serde(rename="fullAddress")] + pub full_address: Option>, + /// Street-level part of the address. + #[serde(rename="streetAddress")] + pub street_address: Option>, + /// Postal Code or ZIP (e.g. "94043"). + #[serde(rename="postalCode")] + pub postal_code: Option, + /// Name of the recipient. + #[serde(rename="recipientName")] + pub recipient_name: Option, + /// Whether the address is a post office box. + #[serde(rename="isPostOfficeBox")] + pub is_post_office_box: Option, + /// Top-level administrative subdivision of the country (e.g. "CA"). + pub region: Option, +} + +impl Part for OrderAddress {} + + +/// 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 OrderLineItemProductVariantAttribute { + /// The dimension of the variant. + pub dimension: Option, + /// The value for the dimension. + pub value: Option, +} + +impl Part for OrderLineItemProductVariantAttribute {} + + +/// 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*). +/// +/// * [getbymerchantorderid orders](struct.OrderGetbymerchantorderidCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct OrdersGetByMerchantOrderIdResponse { + /// Identifies what kind of resource this is. Value: the fixed string "content#ordersGetByMerchantOrderIdResponse". + pub kind: Option, + /// The requested order. + pub order: Option, +} + +impl ResponseResult for OrdersGetByMerchantOrderIdResponse {} + + +/// 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*). +/// +/// * [cancellineitem orders](struct.OrderCancellineitemCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct OrdersCancelLineItemResponse { + /// Identifies what kind of resource this is. Value: the fixed string "content#ordersCancelLineItemResponse". + pub kind: Option, + /// The status of the execution. + #[serde(rename="executionStatus")] + pub execution_status: Option, +} + +impl ResponseResult for OrdersCancelLineItemResponse {} + + +/// 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 OrderCancellation { + /// The quantity that was canceled. + pub quantity: Option, + /// The reason for the cancellation. + pub reason: Option, + /// Date on which the cancellation has been created, in ISO 8601 format. + #[serde(rename="creationDate")] + pub creation_date: Option, + /// The actor that created the cancellation. + pub actor: Option, + /// The explanation of the reason. + #[serde(rename="reasonText")] + pub reason_text: Option, +} + +impl Part for OrderCancellation {} + + +/// 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 TestOrderLineItemProduct { + /// The CLDR territory code of the target country of the product. + #[serde(rename="targetCountry")] + pub target_country: Option, + /// The two-letter ISO 639-1 language code for the item. + #[serde(rename="contentLanguage")] + pub content_language: Option, + /// The title of the product. + pub title: Option, + /// Manufacturer Part Number (MPN) of the item. Optional. + pub mpn: Option, + /// Variant attributes for the item. Optional. + #[serde(rename="variantAttributes")] + pub variant_attributes: Option>, + /// Brand of the item. + pub brand: Option, + /// URL of an image of the item. + #[serde(rename="imageLink")] + pub image_link: Option, + /// An identifier of the item. + #[serde(rename="offerId")] + pub offer_id: Option, + /// Shared identifier for all variants of the same product. Optional. + #[serde(rename="itemGroupId")] + pub item_group_id: Option, + /// Global Trade Item Number (GTIN) of the item. Optional. + pub gtin: Option, + /// Condition or state of the item. + pub condition: Option, + /// The price for the product. + pub price: Option, + /// The item's channel. + pub channel: Option, +} + +impl Part for TestOrderLineItemProduct {} + + +/// 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 OrdersCustomBatchRequestEntry { + /// The ID of the order. Required for all methods beside getByMerchantOrderId. + #[serde(rename="orderId")] + pub order_id: Option, + /// An entry ID, unique within the batch request. + #[serde(rename="batchId")] + pub batch_id: Option, + /// Required for shipLineItems method. + #[serde(rename="shipLineItems")] + pub ship_line_items: Option, + /// Required for updateShipment method. + #[serde(rename="updateShipment")] + pub update_shipment: Option, + /// The ID of the managing account. + #[serde(rename="merchantId")] + pub merchant_id: Option, + /// The merchant order id. Required for updateMerchantOrderId and getByMerchantOrderId methods. + #[serde(rename="merchantOrderId")] + pub merchant_order_id: Option, + /// Required for cancelLineItem method. + #[serde(rename="cancelLineItem")] + pub cancel_line_item: Option, + /// Required for refund method. + pub refund: Option, + /// Required for cancel method. + pub cancel: Option, + /// The ID of the operation. Unique across all operations for a given order. Required for all methods beside get and getByMerchantOrderId. + #[serde(rename="operationId")] + pub operation_id: Option, + /// The method to apply. + pub method: Option, + /// Required for returnLineItem method. + #[serde(rename="returnLineItem")] + pub return_line_item: Option, +} + +impl Part for OrdersCustomBatchRequestEntry {} + + +/// 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 OrderLineItemProduct { + /// The CLDR territory code of the target country of the product. + #[serde(rename="targetCountry")] + pub target_country: Option, + /// URL to the cached image shown to the user when order was placed. + #[serde(rename="shownImage")] + pub shown_image: Option, + /// The two-letter ISO 639-1 language code for the item. + #[serde(rename="contentLanguage")] + pub content_language: Option, + /// The title of the product. + pub title: Option, + /// Manufacturer Part Number (MPN) of the item. + pub mpn: Option, + /// Variant attributes for the item. These are dimensions of the product, such as color, gender, material, pattern, and size. You can find a comprehensive list of variant attributes here. + #[serde(rename="variantAttributes")] + pub variant_attributes: Option>, + /// Brand of the item. + pub brand: Option, + /// URL of an image of the item. + #[serde(rename="imageLink")] + pub image_link: Option, + /// An identifier of the item. + #[serde(rename="offerId")] + pub offer_id: Option, + /// The REST id of the product. + pub id: Option, + /// Shared identifier for all variants of the same product. + #[serde(rename="itemGroupId")] + pub item_group_id: Option, + /// Global Trade Item Number (GTIN) of the item. + pub gtin: Option, + /// Condition or state of the item. + pub condition: Option, + /// Price of the item. + pub price: Option, + /// The item's channel (online or local). + pub channel: Option, +} + +impl Part for OrderLineItemProduct {} + + +/// 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*). +/// +/// * [cancellineitem orders](struct.OrderCancellineitemCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct OrdersCancelLineItemRequest { + /// The ID of the operation. Unique across all operations for a given order. + #[serde(rename="operationId")] + pub operation_id: Option, + /// The reason for the cancellation. + pub reason: Option, + /// The explanation of the reason. + #[serde(rename="reasonText")] + pub reason_text: Option, + /// The ID of the line item to cancel. + #[serde(rename="lineItemId")] + pub line_item_id: Option, + /// The quantity to cancel. + pub quantity: Option, +} + +impl RequestValue for OrdersCancelLineItemRequest {} + + +/// 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 TestOrderCustomer { + /// If set, this indicates the user had a choice to opt in or out of providing marketing rights to the merchant. If unset, this indicates the user has already made this choice in a previous purchase, and was thus not shown the marketing right opt in/out checkbox during the Purchases on Google checkout flow. Optional. + #[serde(rename="explicitMarketingPreference")] + pub explicit_marketing_preference: Option, + /// Full name of the customer. + #[serde(rename="fullName")] + pub full_name: Option, + /// Email address of the customer. + pub email: Option, +} + +impl Part for TestOrderCustomer {} + + +/// 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*). +/// +/// * [acknowledge orders](struct.OrderAcknowledgeCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct OrdersAcknowledgeRequest { + /// The ID of the operation. Unique across all operations for a given order. + #[serde(rename="operationId")] + pub operation_id: Option, +} + +impl RequestValue for OrdersAcknowledgeRequest {} + + +/// 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*). +/// +/// * [returnlineitem orders](struct.OrderReturnlineitemCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct OrdersReturnLineItemRequest { + /// The ID of the operation. Unique across all operations for a given order. + #[serde(rename="operationId")] + pub operation_id: Option, + /// The reason for the return. + pub reason: Option, + /// The explanation of the reason. + #[serde(rename="reasonText")] + pub reason_text: Option, + /// The ID of the line item to return. + #[serde(rename="lineItemId")] + pub line_item_id: Option, + /// The quantity to return. + pub quantity: Option, +} + +impl RequestValue for OrdersReturnLineItemRequest {} + + +/// 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 orders](struct.OrderCustombatchCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct OrdersCustomBatchResponse { + /// Identifies what kind of resource this is. Value: the fixed string "content#ordersCustomBatchResponse". + pub kind: Option, + /// The result of the execution of the batch requests. + pub entries: Option>, +} + +impl ResponseResult for OrdersCustomBatchResponse {} + + +/// 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 OrderCustomer { + /// If set, this indicates the user had a choice to opt in or out of providing marketing rights to the merchant. If unset, this indicates the user has already made this choice in a previous purchase, and was thus not shown the marketing right opt in/out checkbox during the Purchases on Google checkout flow. + #[serde(rename="explicitMarketingPreference")] + pub explicit_marketing_preference: Option, + /// Full name of the customer. + #[serde(rename="fullName")] + pub full_name: Option, + /// Email address of the customer. + pub email: Option, +} + +impl Part for OrderCustomer {} + + +/// 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*). +/// +/// * [cancel orders](struct.OrderCancelCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct OrdersCancelRequest { + /// The reason for the cancellation. + pub reason: Option, + /// The explanation of the reason. + #[serde(rename="reasonText")] + pub reason_text: Option, + /// The ID of the operation. Unique across all operations for a given order. + #[serde(rename="operationId")] + pub operation_id: Option, +} + +impl RequestValue for OrdersCancelRequest {} + + +/// 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 orders](struct.OrderListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct OrdersListResponse { + /// The token for the retrieval of the next page of orders. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// Identifies what kind of resource this is. Value: the fixed string "content#ordersListResponse". + pub kind: Option, + /// no description provided + pub resources: Option>, +} + +impl ResponseResult for OrdersListResponse {} + + +/// 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 OrderShipmentLineItemShipment { + /// The id of the line item that is shipped. + #[serde(rename="lineItemId")] + pub line_item_id: Option, + /// The quantity that is shipped. + pub quantity: Option, +} + +impl Part for OrderShipmentLineItemShipment {} + + +/// 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*). +/// +/// * [createtestorder orders](struct.OrderCreatetestorderCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct OrdersCreateTestOrderResponse { + /// The ID of the newly created test order. + #[serde(rename="orderId")] + pub order_id: Option, + /// Identifies what kind of resource this is. Value: the fixed string "content#ordersCreateTestOrderResponse". + pub kind: Option, +} + +impl ResponseResult for OrdersCreateTestOrderResponse {} + + +/// 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*). +/// +/// * [gettestordertemplate orders](struct.OrderGettestordertemplateCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct OrdersGetTestOrderTemplateResponse { + /// Identifies what kind of resource this is. Value: the fixed string "content#ordersGetTestOrderTemplateResponse". + pub kind: Option, + /// The requested test order template. + pub template: Option, +} + +impl ResponseResult for OrdersGetTestOrderTemplateResponse {} + + +/// 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*). +/// +/// * [refund orders](struct.OrderRefundCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct OrdersRefundRequest { + /// The amount that is refunded. + pub amount: Option, + /// The explanation of the reason. + #[serde(rename="reasonText")] + pub reason_text: Option, + /// The reason for the refund. + pub reason: Option, + /// The ID of the operation. Unique across all operations for a given order. + #[serde(rename="operationId")] + pub operation_id: Option, +} + +impl RequestValue for OrdersRefundRequest {} + + +/// 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 OrdersCustomBatchRequestEntryCancel { + /// The reason for the cancellation. + pub reason: Option, + /// The explanation of the reason. + #[serde(rename="reasonText")] + pub reason_text: Option, +} + +impl Part for OrdersCustomBatchRequestEntryCancel {} + + +/// 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 OrderLineItem { + /// Product data from the time of the order placement. + pub product: Option, + /// Number of items delivered. + #[serde(rename="quantityDelivered")] + pub quantity_delivered: Option, + /// Details of the return policy for the line item. + #[serde(rename="returnInfo")] + pub return_info: Option, + /// Total price for the line item. For example, if two items for $10 are purchased, the total price will be $20. + pub price: Option, + /// Number of items pending. + #[serde(rename="quantityPending")] + pub quantity_pending: Option, + /// Total tax amount for the line item. For example, if two items are purchased, and each have a cost tax of $2, the total tax amount will be $4. + pub tax: Option, + /// Cancellations of the line item. + pub cancellations: Option>, + /// Number of items canceled. + #[serde(rename="quantityCanceled")] + pub quantity_canceled: Option, + /// The id of the line item. + pub id: Option, + /// Returns of the line item. + pub returns: Option>, + /// Number of items shipped. + #[serde(rename="quantityShipped")] + pub quantity_shipped: Option, + /// Number of items returned. + #[serde(rename="quantityReturned")] + pub quantity_returned: Option, + /// Number of items ordered. + #[serde(rename="quantityOrdered")] + pub quantity_ordered: Option, + /// Details of the requested shipping for the line item. + #[serde(rename="shippingDetails")] + pub shipping_details: Option, +} + +impl Part for OrderLineItem {} + + +/// 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 OrdersCustomBatchRequestEntryCancelLineItem { + /// The reason for the cancellation. + pub reason: Option, + /// The explanation of the reason. + #[serde(rename="reasonText")] + pub reason_text: Option, + /// The ID of the line item to cancel. + #[serde(rename="lineItemId")] + pub line_item_id: Option, + /// The quantity to cancel. + pub quantity: Option, +} + +impl Part for OrdersCustomBatchRequestEntryCancelLineItem {} + + +/// 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*). +/// +/// * [cancel orders](struct.OrderCancelCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct OrdersCancelResponse { + /// Identifies what kind of resource this is. Value: the fixed string "content#ordersCancelResponse". + pub kind: Option, + /// The status of the execution. + #[serde(rename="executionStatus")] + pub execution_status: Option, +} + +impl ResponseResult for OrdersCancelResponse {} + + +/// 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 OrdersCustomBatchRequestEntryReturnLineItem { + /// The reason for the return. + pub reason: Option, + /// The explanation of the reason. + #[serde(rename="reasonText")] + pub reason_text: Option, + /// The ID of the line item to return. + #[serde(rename="lineItemId")] + pub line_item_id: Option, + /// The quantity to return. + pub quantity: Option, +} + +impl Part for OrdersCustomBatchRequestEntryReturnLineItem {} + + +/// 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*). +/// +/// * [returnlineitem orders](struct.OrderReturnlineitemCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct OrdersReturnLineItemResponse { + /// Identifies what kind of resource this is. Value: the fixed string "content#ordersReturnLineItemResponse". + pub kind: Option, + /// The status of the execution. + #[serde(rename="executionStatus")] + pub execution_status: Option, +} + +impl ResponseResult for OrdersReturnLineItemResponse {} + + +/// 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*). +/// +/// * [refund orders](struct.OrderRefundCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct OrdersRefundResponse { + /// Identifies what kind of resource this is. Value: the fixed string "content#ordersRefundResponse". + pub kind: Option, + /// The status of the execution. + #[serde(rename="executionStatus")] + pub execution_status: Option, +} + +impl ResponseResult for OrdersRefundResponse {} + + +/// 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*). +/// +/// * [acknowledge orders](struct.OrderAcknowledgeCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct OrdersAcknowledgeResponse { + /// Identifies what kind of resource this is. Value: the fixed string "content#ordersAcknowledgeResponse". + pub kind: Option, + /// The status of the execution. + #[serde(rename="executionStatus")] + pub execution_status: Option, +} + +impl ResponseResult for OrdersAcknowledgeResponse {} + + +/// 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 OrderDeliveryDetails { + /// The phone number of the person receiving the delivery. + #[serde(rename="phoneNumber")] + pub phone_number: Option, + /// The delivery address + pub address: Option, +} + +impl Part for OrderDeliveryDetails {} + + +/// 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 OrdersCustomBatchRequestEntryShipLineItems { + /// Line items to ship. + #[serde(rename="lineItems")] + pub line_items: Option>, + /// The carrier handling the shipment. + pub carrier: Option, + /// The tracking id for the shipment. + #[serde(rename="trackingId")] + pub tracking_id: Option, + /// The ID of the shipment. + #[serde(rename="shipmentId")] + pub shipment_id: Option, +} + +impl Part for OrdersCustomBatchRequestEntryShipLineItems {} + + +/// 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*). +/// +/// * [updatemerchantorderid orders](struct.OrderUpdatemerchantorderidCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct OrdersUpdateMerchantOrderIdRequest { + /// The merchant order id to be assigned to the order. Must be unique per merchant. + #[serde(rename="merchantOrderId")] + pub merchant_order_id: Option, + /// The ID of the operation. Unique across all operations for a given order. + #[serde(rename="operationId")] + pub operation_id: Option, +} + +impl RequestValue for OrdersUpdateMerchantOrderIdRequest {} + + +/// 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*). +/// +/// * [createtestorder orders](struct.OrderCreatetestorderCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct OrdersCreateTestOrderRequest { + /// The test order to create. + #[serde(rename="testOrder")] + pub test_order: Option, + /// The test order template to use. Specify as an alternative to testOrder as a shortcut for retrieving a template and then creating an order using that template. + #[serde(rename="templateName")] + pub template_name: Option, +} + +impl RequestValue for OrdersCreateTestOrderRequest {} + + +/// 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 OrderPaymentMethod { + /// The card expiration month (January = 1, February = 2 etc.). + #[serde(rename="expirationMonth")] + pub expiration_month: Option, + /// The card expiration year (4-digit, e.g. 2015). + #[serde(rename="expirationYear")] + pub expiration_year: Option, + /// The billing phone number. + #[serde(rename="phoneNumber")] + pub phone_number: Option, + /// The billing address. + #[serde(rename="billingAddress")] + pub billing_address: Option, + /// The type of instrument (VISA, Mastercard, etc). + #[serde(rename="type")] + pub type_: Option, + /// The last four digits of the card number. + #[serde(rename="lastFourDigits")] + pub last_four_digits: Option, +} + +impl Part for OrderPaymentMethod {} + + +/// 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*). +/// +/// * [shiplineitems orders](struct.OrderShiplineitemCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct OrdersShipLineItemsResponse { + /// Identifies what kind of resource this is. Value: the fixed string "content#ordersShipLineItemsResponse". + pub kind: Option, + /// The status of the execution. + #[serde(rename="executionStatus")] + pub execution_status: Option, +} + +impl ResponseResult for OrdersShipLineItemsResponse {} + + +/// 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*). +/// +/// * [updateshipment orders](struct.OrderUpdateshipmentCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct OrdersUpdateShipmentRequest { + /// New status for the shipment. Not updated if missing. + pub status: Option, + /// The carrier handling the shipment. Not updated if missing. + pub carrier: Option, + /// The ID of the operation. Unique across all operations for a given order. + #[serde(rename="operationId")] + pub operation_id: Option, + /// The tracking id for the shipment. Not updated if missing. + #[serde(rename="trackingId")] + pub tracking_id: Option, + /// The ID of the shipment. + #[serde(rename="shipmentId")] + pub shipment_id: Option, +} + +impl RequestValue for OrdersUpdateShipmentRequest {} + + +/// 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 OrderLineItemReturnInfo { + /// URL of the item return policy. + #[serde(rename="policyUrl")] + pub policy_url: Option, + /// Whether the item is returnable. + #[serde(rename="isReturnable")] + pub is_returnable: Option, + /// How many days later the item can be returned. + #[serde(rename="daysToReturn")] + pub days_to_return: Option, +} + +impl Part for OrderLineItemReturnInfo {} + + +/// 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 OrdersCustomBatchRequestEntryRefund { + /// The amount that is refunded. + pub amount: Option, + /// The explanation of the reason. + #[serde(rename="reasonText")] + pub reason_text: Option, + /// The reason for the refund. + pub reason: Option, +} + +impl Part for OrdersCustomBatchRequestEntryRefund {} + + +/// 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 TestOrder { + /// The details of the customer who placed the order. + pub customer: Option, + /// Identifies what kind of resource this is. Value: the fixed string "content#testOrder". + pub kind: Option, + /// Line items that are ordered. At least one line item must be provided. + #[serde(rename="lineItems")] + pub line_items: Option>, + /// Identifier of one of the predefined delivery addresses for the delivery. + #[serde(rename="predefinedDeliveryAddress")] + pub predefined_delivery_address: Option, + /// The total cost of shipping for all items. + #[serde(rename="shippingCost")] + pub shipping_cost: Option, + /// The requested shipping option. + #[serde(rename="shippingOption")] + pub shipping_option: Option, + /// The tax for the total shipping cost. + #[serde(rename="shippingCostTax")] + pub shipping_cost_tax: Option, + /// The details of the payment method. + #[serde(rename="paymentMethod")] + pub payment_method: Option, +} + +impl Part for TestOrder {} + + +/// 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 OrdersCustomBatchResponseEntry { + /// The ID of the request entry this entry responds to. + #[serde(rename="batchId")] + pub batch_id: Option, + /// Identifies what kind of resource this is. Value: the fixed string "content#ordersCustomBatchResponseEntry". + pub kind: Option, + /// A list of errors defined if and only if the request failed. + pub errors: Option, + /// The retrieved order. Only defined if the method is get and if the request was successful. + pub order: Option, + /// The status of the execution. Only defined if the method is not get or getByMerchantOrderId and if the request was successful. + #[serde(rename="executionStatus")] + pub execution_status: Option, +} + +impl Part for OrdersCustomBatchResponseEntry {} + + + +// ################### +// MethodBuilders ### +// ################# + +/// A builder providing access to all methods supported on *order* 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_sandbox as content2_sandbox; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use content2_sandbox::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 `acknowledge(...)`, `advancetestorder(...)`, `cancel(...)`, `cancellineitem(...)`, `createtestorder(...)`, `custombatch(...)`, `get(...)`, `getbymerchantorderid(...)`, `gettestordertemplate(...)`, `list(...)`, `refund(...)`, `returnlineitem(...)`, `shiplineitems(...)`, `updatemerchantorderid(...)` and `updateshipment(...)` +/// // to build up your call. +/// let rb = hub.orders(); +/// # } +/// ``` +pub struct OrderMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a ShoppingContent, +} + +impl<'a, C, A> MethodsBuilder for OrderMethods<'a, C, A> {} + +impl<'a, C, A> OrderMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves an order from your Merchant Center account. + /// + /// # Arguments + /// + /// * `merchantId` - The ID of the managing account. + /// * `orderId` - The ID of the order. + pub fn get(&self, merchant_id: &str, order_id: &str) -> OrderGetCall<'a, C, A> { + OrderGetCall { + hub: self.hub, + _merchant_id: merchant_id.to_string(), + _order_id: order_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 orders in your Merchant Center account. + /// + /// # Arguments + /// + /// * `merchantId` - The ID of the managing account. + pub fn list(&self, merchant_id: &str) -> OrderListCall<'a, C, A> { + OrderListCall { + hub: self.hub, + _merchant_id: merchant_id.to_string(), + _statuses: Default::default(), + _placed_date_start: Default::default(), + _placed_date_end: Default::default(), + _page_token: Default::default(), + _order_by: Default::default(), + _max_results: Default::default(), + _acknowledged: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates a shipment's status, carrier, and/or tracking ID. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `merchantId` - The ID of the managing account. + /// * `orderId` - The ID of the order. + pub fn updateshipment(&self, request: OrdersUpdateShipmentRequest, merchant_id: &str, order_id: &str) -> OrderUpdateshipmentCall<'a, C, A> { + OrderUpdateshipmentCall { + hub: self.hub, + _request: request, + _merchant_id: merchant_id.to_string(), + _order_id: order_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Sandbox only. Moves a test order from state "inProgress" to state "pendingShipment". + /// + /// # Arguments + /// + /// * `merchantId` - The ID of the managing account. + /// * `orderId` - The ID of the test order to modify. + pub fn advancetestorder(&self, merchant_id: &str, order_id: &str) -> OrderAdvancetestorderCall<'a, C, A> { + OrderAdvancetestorderCall { + hub: self.hub, + _merchant_id: merchant_id.to_string(), + _order_id: order_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 merchant order ID for a given order. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `merchantId` - The ID of the managing account. + /// * `orderId` - The ID of the order. + pub fn updatemerchantorderid(&self, request: OrdersUpdateMerchantOrderIdRequest, merchant_id: &str, order_id: &str) -> OrderUpdatemerchantorderidCall<'a, C, A> { + OrderUpdatemerchantorderidCall { + hub: self.hub, + _request: request, + _merchant_id: merchant_id.to_string(), + _order_id: order_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 line item. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `merchantId` - The ID of the managing account. + /// * `orderId` - The ID of the order. + pub fn returnlineitem(&self, request: OrdersReturnLineItemRequest, merchant_id: &str, order_id: &str) -> OrderReturnlineitemCall<'a, C, A> { + OrderReturnlineitemCall { + hub: self.hub, + _request: request, + _merchant_id: merchant_id.to_string(), + _order_id: order_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Sandbox only. Retrieves an order template that can be used to quickly create a new order in sandbox. + /// + /// # Arguments + /// + /// * `merchantId` - The ID of the managing account. + /// * `templateName` - The name of the template to retrieve. + pub fn gettestordertemplate(&self, merchant_id: &str, template_name: &str) -> OrderGettestordertemplateCall<'a, C, A> { + OrderGettestordertemplateCall { + hub: self.hub, + _merchant_id: merchant_id.to_string(), + _template_name: template_name.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Sandbox only. Creates a test order. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `merchantId` - The ID of the managing account. + pub fn createtestorder(&self, request: OrdersCreateTestOrderRequest, merchant_id: &str) -> OrderCreatetestorderCall<'a, C, A> { + OrderCreatetestorderCall { + hub: self.hub, + _request: request, + _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: + /// + /// Refund a portion of the order, up to the full amount paid. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `merchantId` - The ID of the managing account. + /// * `orderId` - The ID of the order to refund. + pub fn refund(&self, request: OrdersRefundRequest, merchant_id: &str, order_id: &str) -> OrderRefundCall<'a, C, A> { + OrderRefundCall { + hub: self.hub, + _request: request, + _merchant_id: merchant_id.to_string(), + _order_id: order_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves or modifies multiple orders in a single request. + /// + /// # Arguments + /// + /// * `request` - No description provided. + pub fn custombatch(&self, request: OrdersCustomBatchRequest) -> OrderCustombatchCall<'a, C, A> { + OrderCustombatchCall { + hub: self.hub, + _request: request, + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Cancels a line item. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `merchantId` - The ID of the managing account. + /// * `orderId` - The ID of the order. + pub fn cancellineitem(&self, request: OrdersCancelLineItemRequest, merchant_id: &str, order_id: &str) -> OrderCancellineitemCall<'a, C, A> { + OrderCancellineitemCall { + hub: self.hub, + _request: request, + _merchant_id: merchant_id.to_string(), + _order_id: order_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Retrieves an order using merchant order id. + /// + /// # Arguments + /// + /// * `merchantId` - The ID of the managing account. + /// * `merchantOrderId` - The merchant order id to be looked for. + pub fn getbymerchantorderid(&self, merchant_id: &str, merchant_order_id: &str) -> OrderGetbymerchantorderidCall<'a, C, A> { + OrderGetbymerchantorderidCall { + hub: self.hub, + _merchant_id: merchant_id.to_string(), + _merchant_order_id: merchant_order_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Marks an order as acknowledged. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `merchantId` - The ID of the managing account. + /// * `orderId` - The ID of the order. + pub fn acknowledge(&self, request: OrdersAcknowledgeRequest, merchant_id: &str, order_id: &str) -> OrderAcknowledgeCall<'a, C, A> { + OrderAcknowledgeCall { + hub: self.hub, + _request: request, + _merchant_id: merchant_id.to_string(), + _order_id: order_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Cancels all line items in an order. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `merchantId` - The ID of the managing account. + /// * `orderId` - The ID of the order to cancel. + pub fn cancel(&self, request: OrdersCancelRequest, merchant_id: &str, order_id: &str) -> OrderCancelCall<'a, C, A> { + OrderCancelCall { + hub: self.hub, + _request: request, + _merchant_id: merchant_id.to_string(), + _order_id: order_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Marks line item(s) as shipped. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `merchantId` - The ID of the managing account. + /// * `orderId` - The ID of the order. + pub fn shiplineitems(&self, request: OrdersShipLineItemsRequest, merchant_id: &str, order_id: &str) -> OrderShiplineitemCall<'a, C, A> { + OrderShiplineitemCall { + hub: self.hub, + _request: request, + _merchant_id: merchant_id.to_string(), + _order_id: order_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + + + +// ################### +// CallBuilders ### +// ################# + +/// Retrieves an order from your Merchant Center account. +/// +/// A builder for the *get* method supported by a *order* resource. +/// It is not used directly, but through a `OrderMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_content2_sandbox as content2_sandbox; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use content2_sandbox::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.orders().get("merchantId", "orderId") +/// .doit(); +/// # } +/// ``` +pub struct OrderGetCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a ShoppingContent, + _merchant_id: String, + _order_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for OrderGetCall<'a, C, A> {} + +impl<'a, C, A> OrderGetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Order)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.orders.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(("orderId", self._order_id.to_string())); + for &field in ["alt", "merchantId", "orderId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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/v2sandbox/{merchantId}/orders/{orderId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{merchantId}", "merchantId"), ("{orderId}", "orderId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["orderId", "merchantId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The ID of the managing account. + /// + /// 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) -> OrderGetCall<'a, C, A> { + self._merchant_id = new_value.to_string(); + self + } + /// The ID of the order. + /// + /// Sets the *order id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn order_id(mut self, new_value: &str) -> OrderGetCall<'a, C, A> { + self._order_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> OrderGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> OrderGetCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Full`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> OrderGetCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Lists the orders in your Merchant Center account. +/// +/// A builder for the *list* method supported by a *order* resource. +/// It is not used directly, but through a `OrderMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_content2_sandbox as content2_sandbox; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use content2_sandbox::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.orders().list("merchantId") +/// .add_statuses("ea") +/// .placed_date_start("no") +/// .placed_date_end("justo") +/// .page_token("justo") +/// .order_by("et") +/// .max_results(84) +/// .acknowledged(true) +/// .doit(); +/// # } +/// ``` +pub struct OrderListCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a ShoppingContent, + _merchant_id: String, + _statuses: Vec, + _placed_date_start: Option, + _placed_date_end: Option, + _page_token: Option, + _order_by: Option, + _max_results: Option, + _acknowledged: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for OrderListCall<'a, C, A> {} + +impl<'a, C, A> OrderListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, OrdersListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.orders.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((10 + self._additional_params.len())); + params.push(("merchantId", self._merchant_id.to_string())); + if self._statuses.len() > 0 { + let mut s = String::new(); + for f in self._statuses.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("statuses", s)); + } + if let Some(value) = self._placed_date_start { + params.push(("placedDateStart", value.to_string())); + } + if let Some(value) = self._placed_date_end { + params.push(("placedDateEnd", 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._acknowledged { + params.push(("acknowledged", value.to_string())); + } + for &field in ["alt", "merchantId", "statuses", "placedDateStart", "placedDateEnd", "pageToken", "orderBy", "maxResults", "acknowledged"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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/v2sandbox/{merchantId}/orders".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The ID of the managing account. + /// + /// 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) -> OrderListCall<'a, C, A> { + self._merchant_id = new_value.to_string(); + self + } + /// Obtains orders that match any of the specified statuses. Multiple values can be specified with comma separation. Additionally, please note that active is a shortcut for pendingShipment and partiallyShipped, and completed is a shortcut for shipped , partiallyDelivered, delivered, partiallyReturned, returned, and canceled. + /// + /// Append the given value to the *statuses* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + pub fn add_statuses(mut self, new_value: &str) -> OrderListCall<'a, C, A> { + self._statuses.push(new_value.to_string()); + self + } + /// Obtains orders placed after this date (inclusively), in ISO 8601 format. + /// + /// Sets the *placed date start* query property to the given value. + pub fn placed_date_start(mut self, new_value: &str) -> OrderListCall<'a, C, A> { + self._placed_date_start = Some(new_value.to_string()); + self + } + /// Obtains orders placed before this date (exclusively), in ISO 8601 format. + /// + /// Sets the *placed date end* query property to the given value. + pub fn placed_date_end(mut self, new_value: &str) -> OrderListCall<'a, C, A> { + self._placed_date_end = Some(new_value.to_string()); + self + } + /// The token returned by the previous request. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> OrderListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// The ordering of the returned list. The only supported value are placedDate desc and placedDate asc for now, which returns orders sorted by placement date. "placedDate desc" stands for listing orders by placement date, from oldest to most recent. "placedDate asc" stands for listing orders by placement date, from most recent to oldest. In future releases we'll support other sorting criteria. + /// + /// Sets the *order by* query property to the given value. + pub fn order_by(mut self, new_value: &str) -> OrderListCall<'a, C, A> { + self._order_by = Some(new_value.to_string()); + self + } + /// The maximum number of orders to return in the response, used for paging. The default value is 25 orders per page, and the maximum allowed value is 250 orders per page. + /// Known issue: All List calls will return all Orders without limit regardless of the value of this field. + /// + /// Sets the *max results* query property to the given value. + pub fn max_results(mut self, new_value: u32) -> OrderListCall<'a, C, A> { + self._max_results = Some(new_value); + self + } + /// Obtains orders that match the acknowledgement status. When set to true, obtains orders that have been acknowledged. When false, obtains orders that have not been acknowledged. + /// We recommend using this filter set to false, in conjunction with the acknowledge call, such that only un-acknowledged orders are returned. + /// + /// Sets the *acknowledged* query property to the given value. + pub fn acknowledged(mut self, new_value: bool) -> OrderListCall<'a, C, A> { + self._acknowledged = Some(new_value); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> OrderListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> OrderListCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Full`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> OrderListCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Updates a shipment's status, carrier, and/or tracking ID. +/// +/// A builder for the *updateshipment* method supported by a *order* resource. +/// It is not used directly, but through a `OrderMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_content2_sandbox as content2_sandbox; +/// use content2_sandbox::OrdersUpdateShipmentRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use content2_sandbox::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 = OrdersUpdateShipmentRequest::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.orders().updateshipment(req, "merchantId", "orderId") +/// .doit(); +/// # } +/// ``` +pub struct OrderUpdateshipmentCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a ShoppingContent, + _request: OrdersUpdateShipmentRequest, + _merchant_id: String, + _order_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for OrderUpdateshipmentCall<'a, C, A> {} + +impl<'a, C, A> OrderUpdateshipmentCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, OrdersUpdateShipmentResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.orders.updateshipment", + 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())); + params.push(("orderId", self._order_id.to_string())); + for &field in ["alt", "merchantId", "orderId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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/v2sandbox/{merchantId}/orders/{orderId}/updateShipment".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{merchantId}", "merchantId"), ("{orderId}", "orderId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["orderId", "merchantId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: OrdersUpdateShipmentRequest) -> OrderUpdateshipmentCall<'a, C, A> { + self._request = new_value; + self + } + /// The ID of the managing account. + /// + /// 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) -> OrderUpdateshipmentCall<'a, C, A> { + self._merchant_id = new_value.to_string(); + self + } + /// The ID of the order. + /// + /// Sets the *order id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn order_id(mut self, new_value: &str) -> OrderUpdateshipmentCall<'a, C, A> { + self._order_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> OrderUpdateshipmentCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> OrderUpdateshipmentCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Full`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> OrderUpdateshipmentCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Sandbox only. Moves a test order from state "inProgress" to state "pendingShipment". +/// +/// A builder for the *advancetestorder* method supported by a *order* resource. +/// It is not used directly, but through a `OrderMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_content2_sandbox as content2_sandbox; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use content2_sandbox::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.orders().advancetestorder("merchantId", "orderId") +/// .doit(); +/// # } +/// ``` +pub struct OrderAdvancetestorderCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a ShoppingContent, + _merchant_id: String, + _order_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for OrderAdvancetestorderCall<'a, C, A> {} + +impl<'a, C, A> OrderAdvancetestorderCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, OrdersAdvanceTestOrderResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.orders.advancetestorder", + 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())); + params.push(("orderId", self._order_id.to_string())); + for &field in ["alt", "merchantId", "orderId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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/v2sandbox/{merchantId}/testorders/{orderId}/advance".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{merchantId}", "merchantId"), ("{orderId}", "orderId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["orderId", "merchantId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The ID of the managing account. + /// + /// 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) -> OrderAdvancetestorderCall<'a, C, A> { + self._merchant_id = new_value.to_string(); + self + } + /// The ID of the test order to modify. + /// + /// Sets the *order id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn order_id(mut self, new_value: &str) -> OrderAdvancetestorderCall<'a, C, A> { + self._order_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> OrderAdvancetestorderCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> OrderAdvancetestorderCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Full`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> OrderAdvancetestorderCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Updates the merchant order ID for a given order. +/// +/// A builder for the *updatemerchantorderid* method supported by a *order* resource. +/// It is not used directly, but through a `OrderMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_content2_sandbox as content2_sandbox; +/// use content2_sandbox::OrdersUpdateMerchantOrderIdRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use content2_sandbox::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 = OrdersUpdateMerchantOrderIdRequest::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.orders().updatemerchantorderid(req, "merchantId", "orderId") +/// .doit(); +/// # } +/// ``` +pub struct OrderUpdatemerchantorderidCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a ShoppingContent, + _request: OrdersUpdateMerchantOrderIdRequest, + _merchant_id: String, + _order_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for OrderUpdatemerchantorderidCall<'a, C, A> {} + +impl<'a, C, A> OrderUpdatemerchantorderidCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, OrdersUpdateMerchantOrderIdResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.orders.updatemerchantorderid", + 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())); + params.push(("orderId", self._order_id.to_string())); + for &field in ["alt", "merchantId", "orderId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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/v2sandbox/{merchantId}/orders/{orderId}/updateMerchantOrderId".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{merchantId}", "merchantId"), ("{orderId}", "orderId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["orderId", "merchantId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: OrdersUpdateMerchantOrderIdRequest) -> OrderUpdatemerchantorderidCall<'a, C, A> { + self._request = new_value; + self + } + /// The ID of the managing account. + /// + /// 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) -> OrderUpdatemerchantorderidCall<'a, C, A> { + self._merchant_id = new_value.to_string(); + self + } + /// The ID of the order. + /// + /// Sets the *order id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn order_id(mut self, new_value: &str) -> OrderUpdatemerchantorderidCall<'a, C, A> { + self._order_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> OrderUpdatemerchantorderidCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> OrderUpdatemerchantorderidCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Full`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> OrderUpdatemerchantorderidCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Returns a line item. +/// +/// A builder for the *returnlineitem* method supported by a *order* resource. +/// It is not used directly, but through a `OrderMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_content2_sandbox as content2_sandbox; +/// use content2_sandbox::OrdersReturnLineItemRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use content2_sandbox::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 = OrdersReturnLineItemRequest::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.orders().returnlineitem(req, "merchantId", "orderId") +/// .doit(); +/// # } +/// ``` +pub struct OrderReturnlineitemCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a ShoppingContent, + _request: OrdersReturnLineItemRequest, + _merchant_id: String, + _order_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for OrderReturnlineitemCall<'a, C, A> {} + +impl<'a, C, A> OrderReturnlineitemCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, OrdersReturnLineItemResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.orders.returnlineitem", + 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())); + params.push(("orderId", self._order_id.to_string())); + for &field in ["alt", "merchantId", "orderId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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/v2sandbox/{merchantId}/orders/{orderId}/returnLineItem".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{merchantId}", "merchantId"), ("{orderId}", "orderId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["orderId", "merchantId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: OrdersReturnLineItemRequest) -> OrderReturnlineitemCall<'a, C, A> { + self._request = new_value; + self + } + /// The ID of the managing account. + /// + /// 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) -> OrderReturnlineitemCall<'a, C, A> { + self._merchant_id = new_value.to_string(); + self + } + /// The ID of the order. + /// + /// Sets the *order id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn order_id(mut self, new_value: &str) -> OrderReturnlineitemCall<'a, C, A> { + self._order_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> OrderReturnlineitemCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> OrderReturnlineitemCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Full`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> OrderReturnlineitemCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Sandbox only. Retrieves an order template that can be used to quickly create a new order in sandbox. +/// +/// A builder for the *gettestordertemplate* method supported by a *order* resource. +/// It is not used directly, but through a `OrderMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_content2_sandbox as content2_sandbox; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use content2_sandbox::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.orders().gettestordertemplate("merchantId", "templateName") +/// .doit(); +/// # } +/// ``` +pub struct OrderGettestordertemplateCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a ShoppingContent, + _merchant_id: String, + _template_name: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for OrderGettestordertemplateCall<'a, C, A> {} + +impl<'a, C, A> OrderGettestordertemplateCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, OrdersGetTestOrderTemplateResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.orders.gettestordertemplate", + 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(("templateName", self._template_name.to_string())); + for &field in ["alt", "merchantId", "templateName"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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/v2sandbox/{merchantId}/testordertemplates/{templateName}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{merchantId}", "merchantId"), ("{templateName}", "templateName")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["templateName", "merchantId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The ID of the managing account. + /// + /// 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) -> OrderGettestordertemplateCall<'a, C, A> { + self._merchant_id = new_value.to_string(); + self + } + /// The name of the template to retrieve. + /// + /// Sets the *template 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 template_name(mut self, new_value: &str) -> OrderGettestordertemplateCall<'a, C, A> { + self._template_name = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> OrderGettestordertemplateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> OrderGettestordertemplateCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Full`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> OrderGettestordertemplateCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Sandbox only. Creates a test order. +/// +/// A builder for the *createtestorder* method supported by a *order* resource. +/// It is not used directly, but through a `OrderMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_content2_sandbox as content2_sandbox; +/// use content2_sandbox::OrdersCreateTestOrderRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use content2_sandbox::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 = OrdersCreateTestOrderRequest::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.orders().createtestorder(req, "merchantId") +/// .doit(); +/// # } +/// ``` +pub struct OrderCreatetestorderCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a ShoppingContent, + _request: OrdersCreateTestOrderRequest, + _merchant_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for OrderCreatetestorderCall<'a, C, A> {} + +impl<'a, C, A> OrderCreatetestorderCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, OrdersCreateTestOrderResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.orders.createtestorder", + 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 Err(Error::FieldClash(field)); + } + } + for (name, 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/v2sandbox/{merchantId}/testorders".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: OrdersCreateTestOrderRequest) -> OrderCreatetestorderCall<'a, C, A> { + self._request = new_value; + self + } + /// The ID of the managing account. + /// + /// 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) -> OrderCreatetestorderCall<'a, C, A> { + self._merchant_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> OrderCreatetestorderCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> OrderCreatetestorderCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Full`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> OrderCreatetestorderCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Refund a portion of the order, up to the full amount paid. +/// +/// A builder for the *refund* method supported by a *order* resource. +/// It is not used directly, but through a `OrderMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_content2_sandbox as content2_sandbox; +/// use content2_sandbox::OrdersRefundRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use content2_sandbox::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 = OrdersRefundRequest::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.orders().refund(req, "merchantId", "orderId") +/// .doit(); +/// # } +/// ``` +pub struct OrderRefundCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a ShoppingContent, + _request: OrdersRefundRequest, + _merchant_id: String, + _order_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for OrderRefundCall<'a, C, A> {} + +impl<'a, C, A> OrderRefundCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, OrdersRefundResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.orders.refund", + 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())); + params.push(("orderId", self._order_id.to_string())); + for &field in ["alt", "merchantId", "orderId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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/v2sandbox/{merchantId}/orders/{orderId}/refund".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{merchantId}", "merchantId"), ("{orderId}", "orderId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["orderId", "merchantId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: OrdersRefundRequest) -> OrderRefundCall<'a, C, A> { + self._request = new_value; + self + } + /// The ID of the managing account. + /// + /// 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) -> OrderRefundCall<'a, C, A> { + self._merchant_id = new_value.to_string(); + self + } + /// The ID of the order to refund. + /// + /// Sets the *order id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn order_id(mut self, new_value: &str) -> OrderRefundCall<'a, C, A> { + self._order_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> OrderRefundCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> OrderRefundCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Full`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> OrderRefundCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Retrieves or modifies multiple orders in a single request. +/// +/// A builder for the *custombatch* method supported by a *order* resource. +/// It is not used directly, but through a `OrderMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_content2_sandbox as content2_sandbox; +/// use content2_sandbox::OrdersCustomBatchRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use content2_sandbox::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 = OrdersCustomBatchRequest::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.orders().custombatch(req) +/// .doit(); +/// # } +/// ``` +pub struct OrderCustombatchCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a ShoppingContent, + _request: OrdersCustomBatchRequest, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for OrderCustombatchCall<'a, C, A> {} + +impl<'a, C, A> OrderCustombatchCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, OrdersCustomBatchResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.orders.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 Err(Error::FieldClash(field)); + } + } + for (name, 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/v2sandbox/orders/batch".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_ref().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: OrdersCustomBatchRequest) -> OrderCustombatchCall<'a, C, A> { + self._request = new_value; + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> OrderCustombatchCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> OrderCustombatchCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Full`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> OrderCustombatchCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Cancels a line item. +/// +/// A builder for the *cancellineitem* method supported by a *order* resource. +/// It is not used directly, but through a `OrderMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_content2_sandbox as content2_sandbox; +/// use content2_sandbox::OrdersCancelLineItemRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use content2_sandbox::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 = OrdersCancelLineItemRequest::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.orders().cancellineitem(req, "merchantId", "orderId") +/// .doit(); +/// # } +/// ``` +pub struct OrderCancellineitemCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a ShoppingContent, + _request: OrdersCancelLineItemRequest, + _merchant_id: String, + _order_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for OrderCancellineitemCall<'a, C, A> {} + +impl<'a, C, A> OrderCancellineitemCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, OrdersCancelLineItemResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.orders.cancellineitem", + 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())); + params.push(("orderId", self._order_id.to_string())); + for &field in ["alt", "merchantId", "orderId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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/v2sandbox/{merchantId}/orders/{orderId}/cancelLineItem".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{merchantId}", "merchantId"), ("{orderId}", "orderId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["orderId", "merchantId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: OrdersCancelLineItemRequest) -> OrderCancellineitemCall<'a, C, A> { + self._request = new_value; + self + } + /// The ID of the managing account. + /// + /// 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) -> OrderCancellineitemCall<'a, C, A> { + self._merchant_id = new_value.to_string(); + self + } + /// The ID of the order. + /// + /// Sets the *order id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn order_id(mut self, new_value: &str) -> OrderCancellineitemCall<'a, C, A> { + self._order_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> OrderCancellineitemCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> OrderCancellineitemCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Full`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> OrderCancellineitemCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Retrieves an order using merchant order id. +/// +/// A builder for the *getbymerchantorderid* method supported by a *order* resource. +/// It is not used directly, but through a `OrderMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_content2_sandbox as content2_sandbox; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use content2_sandbox::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.orders().getbymerchantorderid("merchantId", "merchantOrderId") +/// .doit(); +/// # } +/// ``` +pub struct OrderGetbymerchantorderidCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a ShoppingContent, + _merchant_id: String, + _merchant_order_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for OrderGetbymerchantorderidCall<'a, C, A> {} + +impl<'a, C, A> OrderGetbymerchantorderidCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, OrdersGetByMerchantOrderIdResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.orders.getbymerchantorderid", + 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(("merchantOrderId", self._merchant_order_id.to_string())); + for &field in ["alt", "merchantId", "merchantOrderId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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/v2sandbox/{merchantId}/ordersbymerchantid/{merchantOrderId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{merchantId}", "merchantId"), ("{merchantOrderId}", "merchantOrderId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["merchantOrderId", "merchantId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The ID of the managing account. + /// + /// 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) -> OrderGetbymerchantorderidCall<'a, C, A> { + self._merchant_id = new_value.to_string(); + self + } + /// The merchant order id to be looked for. + /// + /// Sets the *merchant order id* path property to 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_order_id(mut self, new_value: &str) -> OrderGetbymerchantorderidCall<'a, C, A> { + self._merchant_order_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> OrderGetbymerchantorderidCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> OrderGetbymerchantorderidCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Full`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> OrderGetbymerchantorderidCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Marks an order as acknowledged. +/// +/// A builder for the *acknowledge* method supported by a *order* resource. +/// It is not used directly, but through a `OrderMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_content2_sandbox as content2_sandbox; +/// use content2_sandbox::OrdersAcknowledgeRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use content2_sandbox::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 = OrdersAcknowledgeRequest::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.orders().acknowledge(req, "merchantId", "orderId") +/// .doit(); +/// # } +/// ``` +pub struct OrderAcknowledgeCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a ShoppingContent, + _request: OrdersAcknowledgeRequest, + _merchant_id: String, + _order_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for OrderAcknowledgeCall<'a, C, A> {} + +impl<'a, C, A> OrderAcknowledgeCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, OrdersAcknowledgeResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.orders.acknowledge", + 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())); + params.push(("orderId", self._order_id.to_string())); + for &field in ["alt", "merchantId", "orderId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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/v2sandbox/{merchantId}/orders/{orderId}/acknowledge".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{merchantId}", "merchantId"), ("{orderId}", "orderId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["orderId", "merchantId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: OrdersAcknowledgeRequest) -> OrderAcknowledgeCall<'a, C, A> { + self._request = new_value; + self + } + /// The ID of the managing account. + /// + /// 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) -> OrderAcknowledgeCall<'a, C, A> { + self._merchant_id = new_value.to_string(); + self + } + /// The ID of the order. + /// + /// Sets the *order id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn order_id(mut self, new_value: &str) -> OrderAcknowledgeCall<'a, C, A> { + self._order_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> OrderAcknowledgeCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> OrderAcknowledgeCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Full`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> OrderAcknowledgeCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Cancels all line items in an order. +/// +/// A builder for the *cancel* method supported by a *order* resource. +/// It is not used directly, but through a `OrderMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_content2_sandbox as content2_sandbox; +/// use content2_sandbox::OrdersCancelRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use content2_sandbox::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 = OrdersCancelRequest::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.orders().cancel(req, "merchantId", "orderId") +/// .doit(); +/// # } +/// ``` +pub struct OrderCancelCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a ShoppingContent, + _request: OrdersCancelRequest, + _merchant_id: String, + _order_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for OrderCancelCall<'a, C, A> {} + +impl<'a, C, A> OrderCancelCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, OrdersCancelResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.orders.cancel", + 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())); + params.push(("orderId", self._order_id.to_string())); + for &field in ["alt", "merchantId", "orderId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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/v2sandbox/{merchantId}/orders/{orderId}/cancel".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{merchantId}", "merchantId"), ("{orderId}", "orderId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["orderId", "merchantId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: OrdersCancelRequest) -> OrderCancelCall<'a, C, A> { + self._request = new_value; + self + } + /// The ID of the managing account. + /// + /// 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) -> OrderCancelCall<'a, C, A> { + self._merchant_id = new_value.to_string(); + self + } + /// The ID of the order to cancel. + /// + /// Sets the *order id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn order_id(mut self, new_value: &str) -> OrderCancelCall<'a, C, A> { + self._order_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> OrderCancelCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> OrderCancelCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Full`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> OrderCancelCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Marks line item(s) as shipped. +/// +/// A builder for the *shiplineitems* method supported by a *order* resource. +/// It is not used directly, but through a `OrderMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_content2_sandbox as content2_sandbox; +/// use content2_sandbox::OrdersShipLineItemsRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use content2_sandbox::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 = OrdersShipLineItemsRequest::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.orders().shiplineitems(req, "merchantId", "orderId") +/// .doit(); +/// # } +/// ``` +pub struct OrderShiplineitemCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a ShoppingContent, + _request: OrdersShipLineItemsRequest, + _merchant_id: String, + _order_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for OrderShiplineitemCall<'a, C, A> {} + +impl<'a, C, A> OrderShiplineitemCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, OrdersShipLineItemsResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.orders.shiplineitems", + 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())); + params.push(("orderId", self._order_id.to_string())); + for &field in ["alt", "merchantId", "orderId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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/v2sandbox/{merchantId}/orders/{orderId}/shipLineItems".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{merchantId}", "merchantId"), ("{orderId}", "orderId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["orderId", "merchantId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: OrdersShipLineItemsRequest) -> OrderShiplineitemCall<'a, C, A> { + self._request = new_value; + self + } + /// The ID of the managing account. + /// + /// 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) -> OrderShiplineitemCall<'a, C, A> { + self._merchant_id = new_value.to_string(); + self + } + /// The ID of the order. + /// + /// Sets the *order id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn order_id(mut self, new_value: &str) -> OrderShiplineitemCall<'a, C, A> { + self._order_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> OrderShiplineitemCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> OrderShiplineitemCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Full`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> OrderShiplineitemCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + diff --git a/gen/coordinate1-cli/Cargo.toml b/gen/coordinate1-cli/Cargo.toml index 8440d68928..690f31c917 100644 --- a/gen/coordinate1-cli/Cargo.toml +++ b/gen/coordinate1-cli/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-coordinate1-cli" -version = "0.3.2+20141215" +version = "0.3.2+20150811" 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-cli" diff --git a/gen/coordinate1-cli/README.md b/gen/coordinate1-cli/README.md index beea30b68f..f9300193e1 100644 --- a/gen/coordinate1-cli/README.md +++ b/gen/coordinate1-cli/README.md @@ -24,7 +24,7 @@ Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/ma # Usage -This documentation was generated from the *coordinate* API at revision *20141215*. The CLI is at version *0.3.2*. +This documentation was generated from the *coordinate* API at revision *20150811*. The CLI is at version *0.3.2*. ```bash coordinate1 [options] diff --git a/gen/coordinate1-cli/mkdocs.yml b/gen/coordinate1-cli/mkdocs.yml index 769c02c725..3b1399b4da 100644 --- a/gen/coordinate1-cli/mkdocs.yml +++ b/gen/coordinate1-cli/mkdocs.yml @@ -1,4 +1,4 @@ -site_name: coordinate v0.3.2+20141215 +site_name: coordinate v0.3.2+20150811 site_url: http://byron.github.io/google-apis-rs/google-coordinate1-cli site_description: Write integrating applications with bcore diff --git a/gen/coordinate1-cli/src/main.rs b/gen/coordinate1-cli/src/main.rs index 3bb809850c..81b304ec55 100644 --- a/gen/coordinate1-cli/src/main.rs +++ b/gen/coordinate1-cli/src/main.rs @@ -274,6 +274,9 @@ impl<'n, 'a> Engine<'n, 'a> { "page-token" => { call = call.page_token(value.unwrap_or("")); }, + "omit-job-changes" => { + call = call.omit_job_changes(arg_from_str(value.unwrap_or("false"), err, "omit-job-changes", "boolean")); + }, "min-modified-timestamp-ms" => { call = call.min_modified_timestamp_ms(value.unwrap_or("")); }, @@ -293,7 +296,7 @@ impl<'n, 'a> Engine<'n, 'a> { err.issues.push(CLIError::UnknownParameter(key.to_string(), {let mut v = Vec::new(); v.extend(self.gp.iter().map(|v|*v)); - v.extend(["page-token", "max-results", "min-modified-timestamp-ms"].iter().map(|v|*v)); + v.extend(["page-token", "min-modified-timestamp-ms", "max-results", "omit-job-changes"].iter().map(|v|*v)); v } )); } } @@ -1567,7 +1570,7 @@ fn main() { let mut app = App::new("coordinate1") .author("Sebastian Thiel ") - .version("0.3.2+20141215") + .version("0.3.2+20150811") .about("Lets you view and manage jobs in a Coordinate team.") .after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_coordinate1_cli") .arg(Arg::with_name("url") diff --git a/gen/coordinate1/Cargo.toml b/gen/coordinate1/Cargo.toml index f0d396f928..e5970e542b 100644 --- a/gen/coordinate1/Cargo.toml +++ b/gen/coordinate1/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-coordinate1" -version = "0.1.9+20141215" +version = "0.1.9+20150811" 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" diff --git a/gen/coordinate1/README.md b/gen/coordinate1/README.md index 092308c8e7..c55623f8d4 100644 --- a/gen/coordinate1/README.md +++ b/gen/coordinate1/README.md @@ -5,7 +5,7 @@ DO NOT EDIT ! --> The `google-coordinate1` library allows access to all features of the *Google coordinate* service. -This documentation was generated from *coordinate* crate version *0.1.9+20141215*, where *20141215* is the exact revision of the *coordinate:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +This documentation was generated from *coordinate* crate version *0.1.9+20150811*, where *20150811* is the exact revision of the *coordinate:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. Everything else about the *coordinate* *v1* API can be found at the [official documentation site](https://developers.google.com/coordinate/). diff --git a/gen/coordinate1/src/lib.rs b/gen/coordinate1/src/lib.rs index f6cf6f3fe3..efde4606fb 100644 --- a/gen/coordinate1/src/lib.rs +++ b/gen/coordinate1/src/lib.rs @@ -2,7 +2,7 @@ // This file was generated automatically from 'src/mako/api/lib.rs.mako' // DO NOT EDIT ! -//! This documentation was generated from *coordinate* crate version *0.1.9+20141215*, where *20141215* is the exact revision of the *coordinate:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +//! This documentation was generated from *coordinate* crate version *0.1.9+20150811*, where *20150811* is the exact revision of the *coordinate:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. //! //! Everything else about the *coordinate* *v1* API can be found at the //! [official documentation site](https://developers.google.com/coordinate/). @@ -114,16 +114,16 @@ //! // execute the final call using `doit()`. //! // Values shown here are possibly random and not representative ! //! let result = hub.jobs().update(req, "teamId", "jobId") -//! .title("kasd") -//! .progress("sanctus") -//! .note("takimata") -//! .lng(0.741081967736) -//! .lat(0.155564420342) -//! .customer_phone_number("invidunt") -//! .customer_name("ea") -//! .add_custom_field("sadipscing") -//! .assignee("rebum.") -//! .address("dolore") +//! .title("sanctus") +//! .progress("takimata") +//! .note("At") +//! .lng(0.155564420342) +//! .lat(0.63392024831) +//! .customer_phone_number("ea") +//! .customer_name("sadipscing") +//! .add_custom_field("rebum.") +//! .assignee("dolore") +//! .address("nonumy") //! .doit(); //! //! match result { diff --git a/gen/coordinate1/src/lib.rs.in b/gen/coordinate1/src/lib.rs.in index a0b8761271..14fd0ea466 100644 --- a/gen/coordinate1/src/lib.rs.in +++ b/gen/coordinate1/src/lib.rs.in @@ -713,6 +713,7 @@ impl<'a, C, A> JobMethods<'a, C, A> { hub: self.hub, _team_id: team_id.to_string(), _page_token: Default::default(), + _omit_job_changes: Default::default(), _min_modified_timestamp_ms: Default::default(), _max_results: Default::default(), _delegate: Default::default(), @@ -2192,8 +2193,9 @@ impl<'a, C, A> JobPatchCall<'a, C, A> where C: BorrowMut, A: oaut /// // Values shown here are possibly random and not representative ! /// let result = hub.jobs().list("teamId") /// .page_token("et") -/// .min_modified_timestamp_ms("eirmod") -/// .max_results(43) +/// .omit_job_changes(true) +/// .min_modified_timestamp_ms("sanctus") +/// .max_results(79) /// .doit(); /// # } /// ``` @@ -2203,6 +2205,7 @@ pub struct JobListCall<'a, C, A> hub: &'a Coordinate, _team_id: String, _page_token: Option, + _omit_job_changes: Option, _min_modified_timestamp_ms: Option, _max_results: Option, _delegate: Option<&'a mut Delegate>, @@ -2226,18 +2229,21 @@ impl<'a, C, A> JobListCall<'a, C, A> where C: BorrowMut, A: oauth }; 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())); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + 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._omit_job_changes { + params.push(("omitJobChanges", 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() { + for &field in ["alt", "teamId", "pageToken", "omitJobChanges", "minModifiedTimestampMs", "maxResults"].iter() { if self._additional_params.contains_key(field) { dlg.finished(false); return Err(Error::FieldClash(field)); @@ -2370,6 +2376,13 @@ impl<'a, C, A> JobListCall<'a, C, A> where C: BorrowMut, A: oauth self._page_token = Some(new_value.to_string()); self } + /// Whether to omit detail job history information. + /// + /// Sets the *omit job changes* query property to the given value. + pub fn omit_job_changes(mut self, new_value: bool) -> JobListCall<'a, C, A> { + self._omit_job_changes = Some(new_value); + self + } /// Minimum time a job was modified in milliseconds since epoch. /// /// Sets the *min modified timestamp ms* query property to the given value. @@ -2468,12 +2481,12 @@ impl<'a, C, A> JobListCall<'a, C, A> where C: BorrowMut, A: oauth /// // You can configure optional parameters by calling 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.77599682643, 0.555410189379, "title") -/// .note("ea") -/// .customer_phone_number("sed") +/// let result = hub.jobs().insert(req, "teamId", "address", 0.555410189379, 0.645756686533, "title") +/// .note("sed") +/// .customer_phone_number("dolor") /// .customer_name("dolor") /// .add_custom_field("dolor") -/// .assignee("dolor") +/// .assignee("et") /// .doit(); /// # } /// ``` @@ -2849,9 +2862,9 @@ impl<'a, C, A> JobInsertCall<'a, C, A> where C: BorrowMut, A: oau /// // 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("amet.") -/// .end_time("voluptua.") -/// .duration("Lorem") +/// .start_time("voluptua.") +/// .end_time("Lorem") +/// .duration("gubergren") /// .all_day(true) /// .doit(); /// # } @@ -3176,9 +3189,9 @@ impl<'a, C, A> ScheduleUpdateCall<'a, C, A> where C: BorrowMut, A /// // 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("vero") -/// .end_time("diam") -/// .duration("rebum.") +/// .start_time("diam") +/// .end_time("rebum.") +/// .duration("consetetur") /// .all_day(true) /// .doit(); /// # } @@ -3981,8 +3994,8 @@ impl<'a, C, A> WorkerListCall<'a, C, A> where C: BorrowMut, A: oa /// // 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("duo") -/// .max_results(19) +/// .page_token("aliquyam") +/// .max_results(96) /// .doit(); /// # } /// ``` diff --git a/gen/datastore1_beta2-cli/Cargo.toml b/gen/datastore1_beta2-cli/Cargo.toml index 877f9d99f5..ce5af3a32d 100644 --- a/gen/datastore1_beta2-cli/Cargo.toml +++ b/gen/datastore1_beta2-cli/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-datastore1_beta2-cli" -version = "0.3.2+20150402" +version = "0.3.2+20151008" 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-cli" diff --git a/gen/datastore1_beta2-cli/README.md b/gen/datastore1_beta2-cli/README.md index e6b991b83f..10ae96b038 100644 --- a/gen/datastore1_beta2-cli/README.md +++ b/gen/datastore1_beta2-cli/README.md @@ -24,7 +24,7 @@ Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/ma # Usage -This documentation was generated from the *datastore* API at revision *20150402*. The CLI is at version *0.3.2*. +This documentation was generated from the *datastore* API at revision *20151008*. The CLI is at version *0.3.2*. ```bash datastore1-beta2 [options] diff --git a/gen/datastore1_beta2-cli/mkdocs.yml b/gen/datastore1_beta2-cli/mkdocs.yml index 670b664240..f5e3789de4 100644 --- a/gen/datastore1_beta2-cli/mkdocs.yml +++ b/gen/datastore1_beta2-cli/mkdocs.yml @@ -1,4 +1,4 @@ -site_name: datastore v0.3.2+20150402 +site_name: datastore v0.3.2+20151008 site_url: http://byron.github.io/google-apis-rs/google-datastore1_beta2-cli site_description: Write integrating applications with bcore diff --git a/gen/datastore1_beta2-cli/src/main.rs b/gen/datastore1_beta2-cli/src/main.rs index 0530624e20..42c8d8dd33 100644 --- a/gen/datastore1_beta2-cli/src/main.rs +++ b/gen/datastore1_beta2-cli/src/main.rs @@ -871,7 +871,7 @@ fn main() { let mut app = App::new("datastore1-beta2") .author("Sebastian Thiel ") - .version("0.3.2+20150402") + .version("0.3.2+20151008") .about("API for accessing Google Cloud Datastore.") .after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_datastore1_beta2_cli") .arg(Arg::with_name("url") diff --git a/gen/datastore1_beta2/Cargo.toml b/gen/datastore1_beta2/Cargo.toml index fbe5ccd768..76a98025c7 100644 --- a/gen/datastore1_beta2/Cargo.toml +++ b/gen/datastore1_beta2/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-datastore1_beta2" -version = "0.1.9+20150402" +version = "0.1.9+20151008" 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" diff --git a/gen/datastore1_beta2/README.md b/gen/datastore1_beta2/README.md index ac3eb9bb8e..bab15c8488 100644 --- a/gen/datastore1_beta2/README.md +++ b/gen/datastore1_beta2/README.md @@ -5,7 +5,7 @@ DO NOT EDIT ! --> 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.9+20150402*, where *20150402* is the exact revision of the *datastore:v1beta2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +This documentation was generated from *datastore* crate version *0.1.9+20151008*, where *20151008* is the exact revision of the *datastore:v1beta2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. Everything else about the *datastore* *v1_beta2* API can be found at the [official documentation site](https://developers.google.com/datastore/). diff --git a/gen/datastore1_beta2/src/lib.rs b/gen/datastore1_beta2/src/lib.rs index 95fca490f6..428d7f3ed6 100644 --- a/gen/datastore1_beta2/src/lib.rs +++ b/gen/datastore1_beta2/src/lib.rs @@ -2,7 +2,7 @@ // This file was generated automatically from 'src/mako/api/lib.rs.mako' // DO NOT EDIT ! -//! This documentation was generated from *datastore* crate version *0.1.9+20150402*, where *20150402* is the exact revision of the *datastore:v1beta2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +//! This documentation was generated from *datastore* crate version *0.1.9+20151008*, where *20151008* is the exact revision of the *datastore:v1beta2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. //! //! Everything else about the *datastore* *v1_beta2* API can be found at the //! [official documentation site](https://developers.google.com/datastore/). diff --git a/gen/deploymentmanager2-cli/Cargo.toml b/gen/deploymentmanager2-cli/Cargo.toml new file mode 100644 index 0000000000..abe05d5003 --- /dev/null +++ b/gen/deploymentmanager2-cli/Cargo.toml @@ -0,0 +1,35 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-deploymentmanager2-cli" +version = "0.3.2+20150831" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with Deployment Manager (protocol v2)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/deploymentmanager2-cli" +homepage = "https://cloud.google.com/deployment-manager/" +documentation = "http://byron.github.io/google-apis-rs/google_deploymentmanager2_cli" +license = "MIT" +keywords = ["deploymentmanager", "google", "cli"] + +[[bin]] +name = "deploymentmanager2" + +[dependencies] +hyper = ">= 0.6.8" +mime = "0.1.0" +serde = ">= 0.6.0" +serde_json = ">= 0.6.0" +yup-oauth2 = "*" +strsim = "*" +yup-hyper-mock = ">=1.0.0" +clap = ">= 1.0.3" + +[build-dependencies] +syntex = { version = "*" } +serde_codegen = { version = "*" } + + +[dependencies.google-deploymentmanager2] +path = "../deploymentmanager2" diff --git a/gen/deploymentmanager2-cli/LICENSE.md b/gen/deploymentmanager2-cli/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/deploymentmanager2-cli/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-cli/README.md b/gen/deploymentmanager2-cli/README.md new file mode 100644 index 0000000000..f33ee03457 --- /dev/null +++ b/gen/deploymentmanager2-cli/README.md @@ -0,0 +1,131 @@ + +The `deploymentmanager2` command-line interface *(CLI)* allows to use most features of the *Google Deployment Manager* service from the comfort of your terminal. + +By default all output is printed to standard out, but flags can be set to direct it into a file independent of your shell's +capabilities. Errors will be printed to standard error, and cause the program's exit code to be non-zero. + +If data-structures are requested, these will be returned as pretty-printed JSON, to be useful as input to other tools. + +Everything else about the *Deployment Manager* API can be found at the +[official documentation site](https://cloud.google.com/deployment-manager/). + +# Downloads + +You can download the pre-compiled 64bit binaries for the following platforms: + +* ![icon](http://megaicons.net/static/img/icons_sizes/6/140/16/ubuntu-icon.png) [ubuntu](http://dl.byronimo.de/google.rs/cli/0.3.2/ubuntu/deploymentmanager2.tar.gz) +* ![icon](http://hydra-media.cursecdn.com/wow.gamepedia.com/a/a2/Apple-icon-16x16.png?version=25ddd67ac3dd3b634478e3978b76cb74) [osx](http://dl.byronimo.de/google.rs/cli/0.3.2/osx/deploymentmanager2.tar.gz) + +Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/deploymentmanager2-cli). + +# Usage + +This documentation was generated from the *Deployment Manager* API at revision *20150831*. The CLI is at version *0.3.2*. + +```bash +deploymentmanager2 [options] + deployments + cancel-preview (-r )... [-p ]... [-o ] + delete [-p ]... [-o ] + get [-p ]... [-o ] + insert (-r )... [-p ]... [-o ] + list [-p ]... [-o ] + patch (-r )... [-p ]... [-o ] + stop (-r )... [-p ]... [-o ] + update (-r )... [-p ]... [-o ] + manifests + get [-p ]... [-o ] + list [-p ]... [-o ] + operations + get [-p ]... [-o ] + list [-p ]... [-o ] + resources + get [-p ]... [-o ] + list [-p ]... [-o ] + types + list [-p ]... [-o ] + deploymentmanager2 --help + +Configuration: + [--scope ]... + Specify the authentication a method should be executed in. Each scope + requires the user to grant this application permission to use it. + If unset, it defaults to the shortest scope url for a particular method. + --config-dir + A directory into which we will store our persistent data. Defaults to + a user-writable directory that we will create during the first invocation. + [default: ~/.google-service-cli] + --debug + Output all server communication to standard error. `tx` and `rx` are placed + into the same stream. + --debug-auth + Output all communication related to authentication to standard error. `tx` + and `rx` are placed into the same stream. + +``` + +# Configuration + +The program will store all persistent data in the `~/.google-service-cli` directory in *JSON* files prefixed with `deploymentmanager2-`. You can change the directory used to store configuration with the `--config-dir` flag on a per-invocation basis. + +More information about the various kinds of persistent data are given in the following paragraphs. + +# Authentication + +Most APIs require a user to authenticate any request. If this is the case, the [scope][scopes] determines the +set of permissions granted. The granularity of these is usually no more than *read-only* or *full-access*. + +If not set, the system will automatically select the smallest feasible scope, e.g. when invoking a +method that is read-only, it will ask only for a read-only scope. +You may use the `--scope` flag to specify a scope directly. +All applicable scopes are documented in the respective method's CLI documentation. + +The first time a scope is used, the user is asked for permission. Follow the instructions given +by the CLI to grant permissions, or to decline. + +If a scope was authenticated by the user, the respective information will be stored as *JSON* in the configuration +directory, e.g. `~/.google-service-cli/deploymentmanager2-token-.json`. No manual management of these tokens +is necessary. + +To revoke granted authentication, please refer to the [official documentation][revoke-access]. + +# Application Secrets + +In order to allow any application to use Google services, it will need to be registered using the +[Google Developer Console][google-dev-console]. APIs the application may use are then enabled for it +one by one. Most APIs can be used for free and have a daily quota. + +To allow more comfortable usage of the CLI without forcing anyone to register an own application, the CLI +comes with a default application secret that is configured accordingly. This also means that heavy usage +all around the world may deplete the daily quota. + +You can workaround this limitation by putting your own secrets file at this location: +`~/.google-service-cli/deploymentmanager2-secret.json`, assuming that the required *deploymentmanager* API +was enabled for it. Such a secret file can be downloaded in the *Google Developer Console* at +*APIs & auth -> Credentials -> Download JSON* and used as is. + +Learn more about how to setup Google projects and enable APIs using the [official documentation][google-project-new]. + + +# Debugging + +Even though the CLI does its best to provide usable error messages, sometimes it might be desirable to know +what exactly led to a particular issue. This is done by allowing all client-server communication to be +output to standard error *as-is*. + +The `--debug` flag will print all client-server communication to standard error, whereas the `--debug-auth` flag +will cause all communication related to authentication to standard error. +If the `--debug` flag is set, error-results will be debug-printed, possibly yielding more information about the +issue at hand. + +You may consider redirecting standard error into a file for ease of use, e.g. `deploymentmanager2 --debug [options] 2>debug.txt`. + + +[scopes]: https://developers.google.com/+/api/oauth#scopes +[revoke-access]: http://webapps.stackexchange.com/a/30849 +[google-dev-console]: https://console.developers.google.com/ +[google-project-new]: https://developers.google.com/console/help/new/ \ No newline at end of file diff --git a/gen/deploymentmanager2-cli/mkdocs.yml b/gen/deploymentmanager2-cli/mkdocs.yml new file mode 100644 index 0000000000..3ba79671e5 --- /dev/null +++ b/gen/deploymentmanager2-cli/mkdocs.yml @@ -0,0 +1,31 @@ +site_name: Deployment Manager v0.3.2+20150831 +site_url: http://byron.github.io/google-apis-rs/google-deploymentmanager2-cli +site_description: Write integrating applications with bcore + +repo_url: https://github.com/Byron/google-apis-rs/tree/master/gen/deploymentmanager2-cli + +docs_dir: docs +site_dir: build_html + +pages: +- ['index.md', 'Home'] +- ['deployments_cancel-preview.md', 'Deployments', 'Cancel Preview'] +- ['deployments_delete.md', 'Deployments', 'Delete'] +- ['deployments_get.md', 'Deployments', 'Get'] +- ['deployments_insert.md', 'Deployments', 'Insert'] +- ['deployments_list.md', 'Deployments', 'List'] +- ['deployments_patch.md', 'Deployments', 'Patch'] +- ['deployments_stop.md', 'Deployments', 'Stop'] +- ['deployments_update.md', 'Deployments', 'Update'] +- ['manifests_get.md', 'Manifests', 'Get'] +- ['manifests_list.md', 'Manifests', 'List'] +- ['operations_get.md', 'Operations', 'Get'] +- ['operations_list.md', 'Operations', 'List'] +- ['resources_get.md', 'Resources', 'Get'] +- ['resources_list.md', 'Resources', 'List'] +- ['types_list.md', 'Types', 'List'] + +theme: readthedocs + +copyright: Copyright © 2015, `Sebastian Thiel` + diff --git a/gen/deploymentmanager2-cli/src/cmn.rs b/gen/deploymentmanager2-cli/src/cmn.rs new file mode 100644 index 0000000000..8358f156fa --- /dev/null +++ b/gen/deploymentmanager2-cli/src/cmn.rs @@ -0,0 +1,721 @@ +// COPY OF 'src/rust/cli/cmn.rs' +// DO NOT EDIT +use oauth2::{ApplicationSecret, ConsoleApplicationSecret, TokenStorage, Token}; +use serde_json as json; +use serde_json::value::Value; +use mime::Mime; +use clap::{App, SubCommand}; +use strsim; + +use std::fs; +use std::env; +use std::io; +use std::fmt; +use std::path::{Path, PathBuf}; +use std::str::FromStr; +use std::string::ToString; +use std::io::{Write, Read, stdout}; + +use std::default::Default; + +const FIELD_SEP: char = '.'; + + +pub enum ComplexType { + Pod, + Vec, + Map, +} + + // Null, + // Bool(bool), + // I64(i64), + // U64(u64), + // F64(f64), + // String(String), + +pub enum JsonType { + Boolean, + Int, + Uint, + Float, + String, +} + +pub struct JsonTypeInfo { + pub jtype: JsonType, + pub ctype: ComplexType, +} + +// Based on @erickt user comment. Thanks for the idea ! +// Remove all keys whose values are null from given value (changed in place) +pub fn remove_json_null_values(value: &mut Value) { + match *value { + Value::Object(ref mut map) => { + let mut for_removal = Vec::new(); + + for (key, mut value) in map.iter_mut() { + if value.is_null() { + for_removal.push(key.clone()); + } else { + remove_json_null_values(&mut value); + } + } + + for key in &for_removal { + map.remove(key); + } + } + _ => {} + } +} + +fn did_you_mean<'a>(v: &str, possible_values: &[&'a str]) -> Option<&'a str> { + + let mut candidate: Option<(f64, &str)> = None; + for pv in possible_values { + let confidence = strsim::jaro_winkler(v, pv); + if confidence > 0.8 && (candidate.is_none() || (candidate.as_ref().unwrap().0 < confidence)) { + candidate = Some((confidence, pv)); + } + } + match candidate { + None => None, + Some((_, candidate)) => Some(candidate), + } +} + +pub enum CallType { + Upload(UploadProtocol), + Standard, +} + +arg_enum!{ + pub enum UploadProtocol { + Simple, + Resumable + } +} + +impl AsRef for UploadProtocol { + fn as_ref(&self) -> &str { + match *self { + UploadProtocol::Simple => "simple", + UploadProtocol::Resumable => "resumable" + } + } +} + +impl AsRef for CallType { + fn as_ref(&self) -> &str { + match *self { + CallType::Upload(ref proto) => proto.as_ref(), + CallType::Standard => "standard-request" + } + } +} + +#[derive(Clone, Default)] +pub struct FieldCursor(Vec); + +impl ToString for FieldCursor { + fn to_string(&self) -> String { + self.0.join(".") + } +} + +impl From<&'static str> for FieldCursor { + fn from(value: &'static str) -> FieldCursor { + let mut res = FieldCursor::default(); + res.set(value).unwrap(); + res + } +} + +impl FieldCursor { + pub fn set(&mut self, value: &str) -> Result<(), CLIError> { + if value.len() == 0 { + return Err(CLIError::Field(FieldError::Empty)) + } + + let mut first_is_field_sep = false; + let mut char_count: usize = 0; + let mut last_c = FIELD_SEP; + let mut num_conscutive_field_seps = 0; + + let mut field = String::new(); + let mut fields = self.0.clone(); + + let push_field = |fs: &mut Vec, f: &mut String| { + if f.len() > 0 { + fs.push(f.clone()); + f.truncate(0); + } + }; + + for (cid, c) in value.chars().enumerate() { + char_count += 1; + + if c == FIELD_SEP { + if cid == 0 { + first_is_field_sep = true; + } + num_conscutive_field_seps += 1; + if cid > 0 && last_c == FIELD_SEP { + if fields.pop().is_none() { + return Err(CLIError::Field(FieldError::PopOnEmpty(value.to_string()))) + } + } else { + push_field(&mut fields, &mut field); + } + } else { + num_conscutive_field_seps = 0; + if cid == 1 { + if first_is_field_sep { + fields.truncate(0); + } + } + field.push(c); + } + + last_c = c; + } + + push_field(&mut fields, &mut field); + + if char_count == 1 && first_is_field_sep { + fields.truncate(0); + } + if char_count > 1 && num_conscutive_field_seps == 1 { + return Err(CLIError::Field(FieldError::TrailingFieldSep(value.to_string()))) + } + + self.0 = fields; + Ok(()) + } + + pub fn did_you_mean(value: &str, possible_values: &[&str]) -> Option { + if value.len() == 0 { + return None + } + + let mut last_c = FIELD_SEP; + + let mut field = String::new(); + let mut output = String::new(); + + let push_field = |fs: &mut String, f: &mut String| { + if f.len() > 0 { + fs.push_str( + match did_you_mean(&f, possible_values) { + Some(candidate) => candidate, + None => &f, + }); + f.truncate(0); + } + }; + + for (cid, c) in value.chars().enumerate() { + if c == FIELD_SEP { + if last_c != FIELD_SEP { + push_field(&mut output, &mut field); + } + output.push(c); + } else { + field.push(c); + } + + last_c = c; + } + + push_field(&mut output, &mut field); + + if &output == value { + None + } else { + Some(output) + } + } + + pub fn set_json_value(&self, mut object: &mut Value, + value: &str, type_info: JsonTypeInfo, + err: &mut InvalidOptionsError, + orig_cursor: &FieldCursor) { + assert!(self.0.len() > 0); + + for field in &self.0[..self.0.len()-1] { + let tmp = object; + object = + match *tmp { + Value::Object(ref mut mapping) => { + mapping.entry(field.to_owned()).or_insert( + Value::Object(Default::default()) + ) + }, + _ => panic!("We don't expect non-object Values here ...") + }; + } + + match *object { + Value::Object(ref mut mapping) => { + let field = &self.0[self.0.len()-1]; + let to_jval = + |value: &str, jtype: JsonType, err: &mut InvalidOptionsError| + -> Value { + match jtype { + JsonType::Boolean => + Value::Bool(arg_from_str(value, err, &field, "boolean")), + JsonType::Int => + Value::I64(arg_from_str(value, err, &field, "int")), + JsonType::Uint => + Value::U64(arg_from_str(value, err, &field, "uint")), + JsonType::Float => + Value::F64(arg_from_str(value, err, &field, "float")), + JsonType::String => + Value::String(value.to_owned()), + } + }; + + match type_info.ctype { + ComplexType::Pod => { + if mapping.insert(field.to_owned(), to_jval(value, type_info.jtype, err)).is_some() { + err.issues.push(CLIError::Field(FieldError::Duplicate(orig_cursor.to_string()))); + } + }, + ComplexType::Vec => { + match *mapping.entry(field.to_owned()) + .or_insert(Value::Array(Default::default())) { + Value::Array(ref mut values) => values.push(to_jval(value, type_info.jtype, err)), + _ => unreachable!() + } + }, + ComplexType::Map => { + let (key, value) = parse_kv_arg(value, err, true); + let jval = to_jval(value.unwrap_or(""), type_info.jtype, err); + + match *mapping.entry(field.to_owned()) + .or_insert(Value::Object(Default::default())) { + Value::Object(ref mut value_map) => { + if value_map.insert(key.to_owned(), jval).is_some() { + err.issues.push(CLIError::Field(FieldError::Duplicate(orig_cursor.to_string()))); + } + } + _ => unreachable!() + } + } + } + }, + _ => unreachable!() + } + } + + pub fn num_fields(&self) -> usize { + self.0.len() + } +} + +pub fn parse_kv_arg<'a>(kv: &'a str, err: &mut InvalidOptionsError, for_hashmap: bool) + -> (&'a str, Option<&'a str>) { + let mut add_err = || err.issues.push(CLIError::InvalidKeyValueSyntax(kv.to_string(),for_hashmap)); + match kv.find('=') { + None => { + add_err(); + return (kv, None) + }, + Some(pos) => { + let key = &kv[..pos]; + if kv.len() <= pos + 1 { + add_err(); + return (key, Some("")) + } + (key, Some(&kv[pos+1..])) + } + } +} + +pub fn calltype_from_str(name: &str, valid_protocols: Vec, err: &mut InvalidOptionsError) -> CallType { + CallType::Upload( + match UploadProtocol::from_str(name) { + Ok(up) => up, + Err(msg) => { + err.issues.push(CLIError::InvalidUploadProtocol(name.to_string(), valid_protocols)); + UploadProtocol::Simple + } + }) +} + +pub fn input_file_from_opts(file_path: &str, err: &mut InvalidOptionsError) -> Option { + match fs::File::open(file_path) { + Ok(f) => Some(f), + Err(io_err) => { + err.issues.push(CLIError::Input(InputError::IOError((file_path.to_string(), io_err)))); + None + } + } +} + +pub fn input_mime_from_opts(mime: &str, err: &mut InvalidOptionsError) -> Option { + match mime.parse() { + Ok(m) => Some(m), + Err(_) => { + err.issues.push(CLIError::Input(InputError::Mime(mime.to_string()))); + None + } + } +} + +pub fn writer_from_opts(arg: Option<&str>) -> Result, io::Error> { + let f = arg.unwrap_or("-"); + match f { + "-" => Ok(Box::new(stdout())), + _ => match fs::OpenOptions::new().create(true).write(true).open(f) { + Ok(f) => Ok(Box::new(f)), + Err(io_err) => Err(io_err), + } + } +} + + +pub fn arg_from_str<'a, T>(arg: &str, err: &mut InvalidOptionsError, + arg_name: &'a str, + arg_type: &'a str) -> T + where T: FromStr + Default, + ::Err: fmt::Display { + match FromStr::from_str(arg) { + Err(perr) => { + err.issues.push( + CLIError::ParseError(arg_name.to_owned(), arg_type.to_owned(), arg.to_string(), format!("{}", perr)) + ); + Default::default() + }, + Ok(v) => v, + } +} + +pub struct JsonTokenStorage { + pub program_name: &'static str, + pub db_dir: String, +} + +impl JsonTokenStorage { + fn path(&self, scope_hash: u64) -> PathBuf { + Path::new(&self.db_dir).join(&format!("{}-token-{}.json", self.program_name, scope_hash)) + } +} + +impl TokenStorage for JsonTokenStorage { + type Error = json::Error; + + // NOTE: logging might be interesting, currently we swallow all errors + fn set(&mut self, scope_hash: u64, _: &Vec<&str>, token: Option) -> Result<(), json::Error> { + match token { + None => { + match fs::remove_file(self.path(scope_hash)) { + Err(err) => + match err.kind() { + io::ErrorKind::NotFound => Ok(()), + _ => Err(json::Error::IoError(err)) + }, + Ok(_) => Ok(()), + } + } + Some(token) => { + match fs::OpenOptions::new().create(true).write(true).open(&self.path(scope_hash)) { + Ok(mut f) => { + match json::to_writer_pretty(&mut f, &token) { + Ok(_) => Ok(()), + Err(serde_err) => Err(serde_err), + } + }, + Err(io_err) => Err(json::Error::IoError(io_err)) + } + } + } + } + + fn get(&self, scope_hash: u64, _: &Vec<&str>) -> Result, json::Error> { + match fs::File::open(&self.path(scope_hash)) { + Ok(mut f) => { + match json::de::from_reader(f) { + Ok(token) => Ok(Some(token)), + Err(err) => Err(err), + } + }, + Err(io_err) => { + match io_err.kind() { + io::ErrorKind::NotFound => Ok(None), + _ => Err(json::Error::IoError(io_err)) + } + } + } + } +} + + +#[derive(Debug)] +pub enum ApplicationSecretError { + DecoderError((String, json::Error)), + FormatError(String), +} + +impl fmt::Display for ApplicationSecretError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + ApplicationSecretError::DecoderError((ref path, ref err)) + => writeln!(f, "Could not decode file at '{}' with error: {}.", + path, err), + ApplicationSecretError::FormatError(ref path) + => writeln!(f, "'installed' field is unset in secret file at '{}'.", + path), + } + } +} + +#[derive(Debug)] +pub enum ConfigurationError { + DirectoryCreationFailed((String, io::Error)), + DirectoryUnset, + HomeExpansionFailed(String), + Secret(ApplicationSecretError), + IOError((String, io::Error)), +} + +impl fmt::Display for ConfigurationError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + ConfigurationError::DirectoryCreationFailed((ref dir, ref err)) + => writeln!(f, "Directory '{}' could not be created with error: {}.", dir, err), + ConfigurationError::DirectoryUnset + => writeln!(f, "--config-dir was unset or empty."), + ConfigurationError::HomeExpansionFailed(ref dir) + => writeln!(f, "Couldn't find HOME directory of current user, failed to expand '{}'.", dir), + ConfigurationError::Secret(ref err) + => writeln!(f, "Secret -> {}", err), + ConfigurationError::IOError((ref path, ref err)) + => writeln!(f, "IO operation failed on path '{}' with error: {}.", path, err), + } + } +} + +#[derive(Debug)] +pub enum InputError { + IOError((String, io::Error)), + Mime(String), +} + +impl fmt::Display for InputError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + InputError::IOError((ref file_path, ref io_err)) + => writeln!(f, "Failed to open '{}' for reading with error: {}.", file_path, io_err), + InputError::Mime(ref mime) + => writeln!(f, "'{}' is not a known mime-type.", mime), + } + } +} + +#[derive(Debug)] +pub enum FieldError { + PopOnEmpty(String), + TrailingFieldSep(String), + Unknown(String, Option, Option), + Duplicate(String), + Empty, +} + + +impl fmt::Display for FieldError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + FieldError::PopOnEmpty(ref field) + => writeln!(f, "'{}': Cannot move up on empty field cursor.", field), + FieldError::TrailingFieldSep(ref field) + => writeln!(f, "'{}': Single field separator may not be last character.", field), + FieldError::Unknown(ref field, ref suggestion, ref value) => { + let suffix = + match *suggestion { + Some(ref s) => { + let kv = + match *value { + Some(ref v) => format!("{}={}", s, v), + None => s.clone(), + }; + format!(" Did you mean '{}' ?", kv) + }, + None => String::new(), + }; + writeln!(f, "Field '{}' does not exist.{}", field, suffix) + }, + FieldError::Duplicate(ref cursor) + => writeln!(f, "Value at '{}' was already set", cursor), + FieldError::Empty + => writeln!(f, "Field names must not be empty."), + } + } +} + + +#[derive(Debug)] +pub enum CLIError { + Configuration(ConfigurationError), + ParseError(String, String, String, String), + UnknownParameter(String, Vec<&'static str>), + InvalidUploadProtocol(String, Vec), + InvalidKeyValueSyntax(String, bool), + Input(InputError), + Field(FieldError), + MissingCommandError, + MissingMethodError(String), +} + +impl fmt::Display for CLIError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + CLIError::Configuration(ref err) => write!(f, "Configuration -> {}", err), + CLIError::Input(ref err) => write!(f, "Input -> {}", err), + CLIError::Field(ref err) => write!(f, "Field -> {}", err), + CLIError::InvalidUploadProtocol(ref proto_name, ref valid_names) + => writeln!(f, "'{}' is not a valid upload protocol. Choose from one of {}.", proto_name, valid_names.join(", ")), + CLIError::ParseError(ref arg_name, ref type_name, ref value, ref err_desc) + => writeln!(f, "Failed to parse argument '{}' with value '{}' as {} with error: {}.", + arg_name, value, type_name, err_desc), + CLIError::UnknownParameter(ref param_name, ref possible_values) => { + let mut suffix = + match did_you_mean(param_name, &possible_values) { + Some(v) => format!(" Did you mean '{}' ?", v), + None => String::new(), + }; + write!(f, "Parameter '{}' is unknown.{}\n", param_name, suffix) + }, + CLIError::InvalidKeyValueSyntax(ref kv, is_hashmap) => { + let hashmap_info = if is_hashmap { "hashmap " } else { "" }; + writeln!(f, "'{}' does not match {}pattern =.", kv, hashmap_info) + }, + CLIError::MissingCommandError => writeln!(f, "Please specify the main sub-command."), + CLIError::MissingMethodError(ref cmd) => writeln!(f, "Please specify the method to call on the '{}' command.", cmd), + } + } +} + +#[derive(Debug)] +pub struct InvalidOptionsError { + pub issues: Vec, + pub exit_code: i32, +} + +impl fmt::Display for InvalidOptionsError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + for issue in &self.issues { + try!(issue.fmt(f)); + } + Ok(()) + } +} + +impl InvalidOptionsError { + pub fn single(err: CLIError, exit_code: i32) -> InvalidOptionsError { + InvalidOptionsError { + issues: vec![err], + exit_code: exit_code, + } + } + + pub fn new() -> InvalidOptionsError { + InvalidOptionsError { + issues: Vec::new(), + exit_code: 1, + } + } +} + +pub fn assure_config_dir_exists(dir: &str) -> Result { + let trdir = dir.trim(); + if trdir.len() == 0 { + return Err(CLIError::Configuration(ConfigurationError::DirectoryUnset)) + } + + let expanded_config_dir = + if trdir.as_bytes()[0] == b'~' { + match env::var("HOME").ok().or(env::var("UserProfile").ok()) { + None => return Err(CLIError::Configuration(ConfigurationError::HomeExpansionFailed(trdir.to_string()))), + Some(mut user) => { + user.push_str(&trdir[1..]); + user + } + } + } else { + trdir.to_string() + }; + + if let Err(err) = fs::create_dir(&expanded_config_dir) { + if err.kind() != io::ErrorKind::AlreadyExists { + return Err(CLIError::Configuration( + ConfigurationError::DirectoryCreationFailed((expanded_config_dir, err)))) + } + } + + Ok(expanded_config_dir) +} + +pub fn application_secret_from_directory(dir: &str, + secret_basename: &str, + json_console_secret: &str) + -> Result { + let secret_path = Path::new(dir).join(secret_basename); + let secret_str = || secret_path.as_path().to_str().unwrap().to_string(); + let secret_io_error = |io_err: io::Error| { + Err(CLIError::Configuration(ConfigurationError::IOError( + (secret_str(), io_err) + ))) + }; + + for _ in 0..2 { + match fs::File::open(&secret_path) { + Err(mut err) => { + if err.kind() == io::ErrorKind::NotFound { + // Write our built-in one - user may adjust the written file at will + + err = match fs::OpenOptions::new().create(true).write(true).open(&secret_path) { + Err(cfe) => cfe, + Ok(mut f) => { + // Assure we convert 'ugly' json string into pretty one + let console_secret: ConsoleApplicationSecret + = json::from_str(json_console_secret).unwrap(); + match json::to_writer_pretty(&mut f, &console_secret) { + Err(serde_err) => match serde_err { + json::Error::IoError(err) => err, + _ => panic!("Unexpected serde error: {:#?}", serde_err) + }, + Ok(_) => continue, + } + } + }; + // fall through to IO error handling + } + return secret_io_error(err) + }, + Ok(mut f) => { + match json::de::from_reader::<_, ConsoleApplicationSecret>(f) { + Err(json::Error::IoError(err)) => + return secret_io_error(err), + Err(json_err) => + return Err(CLIError::Configuration( + ConfigurationError::Secret( + ApplicationSecretError::DecoderError( + (secret_str(), json_err) + )))), + Ok(console_secret) => + match console_secret.installed { + Some(secret) => return Ok(secret), + None => return Err( + CLIError::Configuration( + ConfigurationError::Secret( + ApplicationSecretError::FormatError(secret_str()) + ))) + }, + } + } + } + } + unreachable!(); +} diff --git a/gen/deploymentmanager2-cli/src/main.rs b/gen/deploymentmanager2-cli/src/main.rs new file mode 100644 index 0000000000..8eb769bef5 --- /dev/null +++ b/gen/deploymentmanager2-cli/src/main.rs @@ -0,0 +1,1870 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/cli/main.rs.mako' +// DO NOT EDIT ! +#![allow(unused_variables, unused_imports, dead_code, unused_mut)] + +#[macro_use] +extern crate clap; +extern crate yup_oauth2 as oauth2; +extern crate yup_hyper_mock as mock; +extern crate serde; +extern crate serde_json; +extern crate hyper; +extern crate mime; +extern crate strsim; +extern crate google_deploymentmanager2 as api; + +use std::env; +use std::io::{self, Write}; +use clap::{App, SubCommand, Arg}; + +mod cmn; + +use cmn::{InvalidOptionsError, CLIError, JsonTokenStorage, arg_from_str, writer_from_opts, parse_kv_arg, + input_file_from_opts, input_mime_from_opts, FieldCursor, FieldError, CallType, UploadProtocol, + calltype_from_str, remove_json_null_values, ComplexType, JsonType, JsonTypeInfo}; + +use std::default::Default; +use std::str::FromStr; + +use oauth2::{Authenticator, DefaultAuthenticatorDelegate}; +use serde_json as json; +use clap::ArgMatches; + +enum DoitError { + IoError(String, io::Error), + ApiError(api::Error), +} + +struct Engine<'n, 'a> { + opt: ArgMatches<'n, 'a>, + hub: api::DeploymentManager>, + gp: Vec<&'static str>, + gpm: Vec<(&'static str, &'static str)>, +} + + +impl<'n, 'a> Engine<'n, 'a> { + fn _deployments_cancel_preview(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "fingerprint" => Some(("fingerprint", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["fingerprint"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::DeploymentsCancelPreviewRequest = json::value::from_value(object).unwrap(); + let mut call = self.hub.deployments().cancel_preview(request, opt.value_of("project").unwrap_or(""), opt.value_of("deployment").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _deployments_delete(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.deployments().delete(opt.value_of("project").unwrap_or(""), opt.value_of("deployment").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _deployments_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.deployments().get(opt.value_of("project").unwrap_or(""), opt.value_of("deployment").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _deployments_insert(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "update.manifest" => Some(("update.manifest", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "manifest" => Some(("manifest", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "insert-time" => Some(("insertTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "fingerprint" => Some(("fingerprint", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "operation.status" => Some(("operation.status", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "operation.kind" => Some(("operation.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "operation.status-message" => Some(("operation.statusMessage", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "operation.user" => Some(("operation.user", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "operation.start-time" => Some(("operation.startTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "operation.zone" => Some(("operation.zone", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "operation.http-error-status-code" => Some(("operation.httpErrorStatusCode", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "operation.region" => Some(("operation.region", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "operation.target-id" => Some(("operation.targetId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "operation.operation-type" => Some(("operation.operationType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "operation.target-link" => Some(("operation.targetLink", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "operation.insert-time" => Some(("operation.insertTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "operation.http-error-message" => Some(("operation.httpErrorMessage", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "operation.progress" => Some(("operation.progress", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "operation.client-operation-id" => Some(("operation.clientOperationId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "operation.end-time" => Some(("operation.endTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "operation.creation-timestamp" => Some(("operation.creationTimestamp", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "operation.id" => Some(("operation.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "operation.self-link" => Some(("operation.selfLink", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "operation.name" => Some(("operation.name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "target.config.content" => Some(("target.config.content", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "description" => Some(("description", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["client-operation-id", "config", "content", "creation-timestamp", "description", "end-time", "fingerprint", "http-error-message", "http-error-status-code", "id", "insert-time", "kind", "manifest", "name", "operation", "operation-type", "progress", "region", "self-link", "start-time", "status", "status-message", "target", "target-id", "target-link", "update", "user", "zone"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::Deployment = json::value::from_value(object).unwrap(); + let mut call = self.hub.deployments().insert(request, opt.value_of("project").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "preview" => { + call = call.preview(arg_from_str(value.unwrap_or("false"), err, "preview", "boolean")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["preview"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _deployments_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.deployments().list(opt.value_of("project").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "max-results" => { + call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer")); + }, + "filter" => { + call = call.filter(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["filter", "page-token", "max-results"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _deployments_patch(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "update.manifest" => Some(("update.manifest", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "manifest" => Some(("manifest", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "insert-time" => Some(("insertTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "fingerprint" => Some(("fingerprint", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "operation.status" => Some(("operation.status", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "operation.kind" => Some(("operation.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "operation.status-message" => Some(("operation.statusMessage", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "operation.user" => Some(("operation.user", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "operation.start-time" => Some(("operation.startTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "operation.zone" => Some(("operation.zone", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "operation.http-error-status-code" => Some(("operation.httpErrorStatusCode", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "operation.region" => Some(("operation.region", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "operation.target-id" => Some(("operation.targetId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "operation.operation-type" => Some(("operation.operationType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "operation.target-link" => Some(("operation.targetLink", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "operation.insert-time" => Some(("operation.insertTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "operation.http-error-message" => Some(("operation.httpErrorMessage", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "operation.progress" => Some(("operation.progress", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "operation.client-operation-id" => Some(("operation.clientOperationId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "operation.end-time" => Some(("operation.endTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "operation.creation-timestamp" => Some(("operation.creationTimestamp", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "operation.id" => Some(("operation.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "operation.self-link" => Some(("operation.selfLink", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "operation.name" => Some(("operation.name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "target.config.content" => Some(("target.config.content", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "description" => Some(("description", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["client-operation-id", "config", "content", "creation-timestamp", "description", "end-time", "fingerprint", "http-error-message", "http-error-status-code", "id", "insert-time", "kind", "manifest", "name", "operation", "operation-type", "progress", "region", "self-link", "start-time", "status", "status-message", "target", "target-id", "target-link", "update", "user", "zone"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::Deployment = json::value::from_value(object).unwrap(); + let mut call = self.hub.deployments().patch(request, opt.value_of("project").unwrap_or(""), opt.value_of("deployment").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "preview" => { + call = call.preview(arg_from_str(value.unwrap_or("false"), err, "preview", "boolean")); + }, + "delete-policy" => { + call = call.delete_policy(value.unwrap_or("")); + }, + "create-policy" => { + call = call.create_policy(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["preview", "create-policy", "delete-policy"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _deployments_stop(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "fingerprint" => Some(("fingerprint", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["fingerprint"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::DeploymentsStopRequest = json::value::from_value(object).unwrap(); + let mut call = self.hub.deployments().stop(request, opt.value_of("project").unwrap_or(""), opt.value_of("deployment").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _deployments_update(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "update.manifest" => Some(("update.manifest", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "manifest" => Some(("manifest", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "insert-time" => Some(("insertTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "fingerprint" => Some(("fingerprint", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "operation.status" => Some(("operation.status", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "operation.kind" => Some(("operation.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "operation.status-message" => Some(("operation.statusMessage", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "operation.user" => Some(("operation.user", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "operation.start-time" => Some(("operation.startTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "operation.zone" => Some(("operation.zone", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "operation.http-error-status-code" => Some(("operation.httpErrorStatusCode", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "operation.region" => Some(("operation.region", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "operation.target-id" => Some(("operation.targetId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "operation.operation-type" => Some(("operation.operationType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "operation.target-link" => Some(("operation.targetLink", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "operation.insert-time" => Some(("operation.insertTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "operation.http-error-message" => Some(("operation.httpErrorMessage", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "operation.progress" => Some(("operation.progress", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "operation.client-operation-id" => Some(("operation.clientOperationId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "operation.end-time" => Some(("operation.endTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "operation.creation-timestamp" => Some(("operation.creationTimestamp", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "operation.id" => Some(("operation.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "operation.self-link" => Some(("operation.selfLink", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "operation.name" => Some(("operation.name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "target.config.content" => Some(("target.config.content", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "description" => Some(("description", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["client-operation-id", "config", "content", "creation-timestamp", "description", "end-time", "fingerprint", "http-error-message", "http-error-status-code", "id", "insert-time", "kind", "manifest", "name", "operation", "operation-type", "progress", "region", "self-link", "start-time", "status", "status-message", "target", "target-id", "target-link", "update", "user", "zone"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::Deployment = json::value::from_value(object).unwrap(); + let mut call = self.hub.deployments().update(request, opt.value_of("project").unwrap_or(""), opt.value_of("deployment").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "preview" => { + call = call.preview(arg_from_str(value.unwrap_or("false"), err, "preview", "boolean")); + }, + "delete-policy" => { + call = call.delete_policy(value.unwrap_or("")); + }, + "create-policy" => { + call = call.create_policy(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["preview", "create-policy", "delete-policy"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _manifests_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.manifests().get(opt.value_of("project").unwrap_or(""), opt.value_of("deployment").unwrap_or(""), opt.value_of("manifest").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _manifests_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.manifests().list(opt.value_of("project").unwrap_or(""), opt.value_of("deployment").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "max-results" => { + call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer")); + }, + "filter" => { + call = call.filter(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["filter", "page-token", "max-results"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _operations_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.operations().get(opt.value_of("project").unwrap_or(""), opt.value_of("operation").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _operations_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.operations().list(opt.value_of("project").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "max-results" => { + call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer")); + }, + "filter" => { + call = call.filter(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["filter", "page-token", "max-results"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _resources_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.resources().get(opt.value_of("project").unwrap_or(""), opt.value_of("deployment").unwrap_or(""), opt.value_of("resource").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _resources_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.resources().list(opt.value_of("project").unwrap_or(""), opt.value_of("deployment").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "max-results" => { + call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer")); + }, + "filter" => { + call = call.filter(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["filter", "page-token", "max-results"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _types_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.types().list(opt.value_of("project").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "max-results" => { + call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer")); + }, + "filter" => { + call = call.filter(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["filter", "page-token", "max-results"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _doit(&self, dry_run: bool) -> Result, Option> { + let mut err = InvalidOptionsError::new(); + let mut call_result: Result<(), DoitError> = Ok(()); + let mut err_opt: Option = None; + match self.opt.subcommand() { + ("deployments", Some(opt)) => { + match opt.subcommand() { + ("cancel-preview", Some(opt)) => { + call_result = self._deployments_cancel_preview(opt, dry_run, &mut err); + }, + ("delete", Some(opt)) => { + call_result = self._deployments_delete(opt, dry_run, &mut err); + }, + ("get", Some(opt)) => { + call_result = self._deployments_get(opt, dry_run, &mut err); + }, + ("insert", Some(opt)) => { + call_result = self._deployments_insert(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._deployments_list(opt, dry_run, &mut err); + }, + ("patch", Some(opt)) => { + call_result = self._deployments_patch(opt, dry_run, &mut err); + }, + ("stop", Some(opt)) => { + call_result = self._deployments_stop(opt, dry_run, &mut err); + }, + ("update", Some(opt)) => { + call_result = self._deployments_update(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("deployments".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("manifests", Some(opt)) => { + match opt.subcommand() { + ("get", Some(opt)) => { + call_result = self._manifests_get(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._manifests_list(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("manifests".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("operations", Some(opt)) => { + match opt.subcommand() { + ("get", Some(opt)) => { + call_result = self._operations_get(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._operations_list(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("operations".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("resources", Some(opt)) => { + match opt.subcommand() { + ("get", Some(opt)) => { + call_result = self._resources_get(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._resources_list(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("resources".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("types", Some(opt)) => { + match opt.subcommand() { + ("list", Some(opt)) => { + call_result = self._types_list(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("types".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + _ => { + err.issues.push(CLIError::MissingCommandError); + writeln!(io::stderr(), "{}\n", self.opt.usage()).ok(); + } + } + + if dry_run { + if err.issues.len() > 0 { + err_opt = Some(err); + } + Err(err_opt) + } else { + Ok(call_result) + } + } + + // Please note that this call will fail if any part of the opt can't be handled + fn new(opt: ArgMatches<'a, 'n>) -> Result, InvalidOptionsError> { + let (config_dir, secret) = { + let config_dir = match cmn::assure_config_dir_exists(opt.value_of("folder").unwrap_or("~/.google-service-cli")) { + Err(e) => return Err(InvalidOptionsError::single(e, 3)), + Ok(p) => p, + }; + + match cmn::application_secret_from_directory(&config_dir, "deploymentmanager2-secret.json", + "{\"installed\":{\"auth_uri\":\"https://accounts.google.com/o/oauth2/auth\",\"client_secret\":\"hCsslbCUyfehWMmbkG8vTYxG\",\"token_uri\":\"https://accounts.google.com/o/oauth2/token\",\"client_email\":\"\",\"redirect_uris\":[\"urn:ietf:wg:oauth:2.0:oob\",\"oob\"],\"client_x509_cert_url\":\"\",\"client_id\":\"620010449518-9ngf7o4dhs0dka470npqvor6dc5lqb9b.apps.googleusercontent.com\",\"auth_provider_x509_cert_url\":\"https://www.googleapis.com/oauth2/v1/certs\"}}") { + Ok(secret) => (config_dir, secret), + Err(e) => return Err(InvalidOptionsError::single(e, 4)) + } + }; + + let auth = Authenticator::new( &secret, DefaultAuthenticatorDelegate, + if opt.is_present("debug-auth") { + hyper::Client::with_connector(mock::TeeConnector { + connector: hyper::net::HttpsConnector::::default() + }) + } else { + hyper::Client::new() + }, + JsonTokenStorage { + program_name: "deploymentmanager2", + db_dir: config_dir.clone(), + }, None); + + let client = + if opt.is_present("debug") { + hyper::Client::with_connector(mock::TeeConnector { + connector: hyper::net::HttpsConnector::::default() + }) + } else { + hyper::Client::new() + }; + let engine = Engine { + opt: opt, + hub: api::DeploymentManager::new(client, auth), + gp: vec!["alt", "fields", "key", "oauth-token", "pretty-print", "quota-user", "user-ip"], + gpm: vec![ + ("oauth-token", "oauth_token"), + ("pretty-print", "prettyPrint"), + ("quota-user", "quotaUser"), + ("user-ip", "userIp"), + ] + }; + + match engine._doit(true) { + Err(Some(err)) => Err(err), + Err(None) => Ok(engine), + Ok(_) => unreachable!(), + } + } + + fn doit(&self) -> Result<(), DoitError> { + match self._doit(false) { + Ok(res) => res, + Err(_) => unreachable!(), + } + } +} + +fn main() { + let mut exit_status = 0i32; + let arg_data = [ + ("deployments", "methods: 'cancel-preview', 'delete', 'get', 'insert', 'list', 'patch', 'stop' and 'update'", vec![ + ("cancel-preview", + Some(r##"Cancels and removes the preview currently associated with the deployment."##), + "Details at http://byron.github.io/google-apis-rs/google_deploymentmanager2_cli/deployments_cancel-preview", + vec![ + (Some(r##"project"##), + None, + Some(r##"The project ID for this request."##), + Some(true), + Some(false)), + + (Some(r##"deployment"##), + None, + Some(r##"The name of the deployment for this request."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("delete", + Some(r##"Deletes a deployment and all of the resources in the deployment."##), + "Details at http://byron.github.io/google-apis-rs/google_deploymentmanager2_cli/deployments_delete", + vec![ + (Some(r##"project"##), + None, + Some(r##"The project ID for this request."##), + Some(true), + Some(false)), + + (Some(r##"deployment"##), + None, + Some(r##"The name of the deployment for this request."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("get", + Some(r##"Gets information about a specific deployment."##), + "Details at http://byron.github.io/google-apis-rs/google_deploymentmanager2_cli/deployments_get", + vec![ + (Some(r##"project"##), + None, + Some(r##"The project ID for this request."##), + Some(true), + Some(false)), + + (Some(r##"deployment"##), + None, + Some(r##"The name of the deployment for this request."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("insert", + Some(r##"Creates a deployment and all of the resources described by the deployment manifest."##), + "Details at http://byron.github.io/google-apis-rs/google_deploymentmanager2_cli/deployments_insert", + vec![ + (Some(r##"project"##), + None, + Some(r##"The project ID for this request."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Lists all deployments for a given project."##), + "Details at http://byron.github.io/google-apis-rs/google_deploymentmanager2_cli/deployments_list", + vec![ + (Some(r##"project"##), + None, + Some(r##"The project ID for this request."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("patch", + Some(r##"Updates a deployment and all of the resources described by the deployment manifest. This method supports patch semantics."##), + "Details at http://byron.github.io/google-apis-rs/google_deploymentmanager2_cli/deployments_patch", + vec![ + (Some(r##"project"##), + None, + Some(r##"The project ID for this request."##), + Some(true), + Some(false)), + + (Some(r##"deployment"##), + None, + Some(r##"The name of the deployment for this request."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("stop", + Some(r##"Stops an ongoing operation. This does not roll back any work that has already been completed, but prevents any new work from being started."##), + "Details at http://byron.github.io/google-apis-rs/google_deploymentmanager2_cli/deployments_stop", + vec![ + (Some(r##"project"##), + None, + Some(r##"The project ID for this request."##), + Some(true), + Some(false)), + + (Some(r##"deployment"##), + None, + Some(r##"The name of the deployment for this request."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("update", + Some(r##"Updates a deployment and all of the resources described by the deployment manifest."##), + "Details at http://byron.github.io/google-apis-rs/google_deploymentmanager2_cli/deployments_update", + vec![ + (Some(r##"project"##), + None, + Some(r##"The project ID for this request."##), + Some(true), + Some(false)), + + (Some(r##"deployment"##), + None, + Some(r##"The name of the deployment for this request."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("manifests", "methods: 'get' and 'list'", vec![ + ("get", + Some(r##"Gets information about a specific manifest."##), + "Details at http://byron.github.io/google-apis-rs/google_deploymentmanager2_cli/manifests_get", + vec![ + (Some(r##"project"##), + None, + Some(r##"The project ID for this request."##), + Some(true), + Some(false)), + + (Some(r##"deployment"##), + None, + Some(r##"The name of the deployment for this request."##), + Some(true), + Some(false)), + + (Some(r##"manifest"##), + None, + Some(r##"The name of the manifest for this request."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Lists all manifests for a given deployment."##), + "Details at http://byron.github.io/google-apis-rs/google_deploymentmanager2_cli/manifests_list", + vec![ + (Some(r##"project"##), + None, + Some(r##"The project ID for this request."##), + Some(true), + Some(false)), + + (Some(r##"deployment"##), + None, + Some(r##"The name of the deployment for this request."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("operations", "methods: 'get' and 'list'", vec![ + ("get", + Some(r##"Gets information about a specific operation."##), + "Details at http://byron.github.io/google-apis-rs/google_deploymentmanager2_cli/operations_get", + vec![ + (Some(r##"project"##), + None, + Some(r##"The project ID for this request."##), + Some(true), + Some(false)), + + (Some(r##"operation"##), + None, + Some(r##"The name of the operation for this request."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Lists all operations for a project."##), + "Details at http://byron.github.io/google-apis-rs/google_deploymentmanager2_cli/operations_list", + vec![ + (Some(r##"project"##), + None, + Some(r##"The project ID for this request."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("resources", "methods: 'get' and 'list'", vec![ + ("get", + Some(r##"Gets information about a single resource."##), + "Details at http://byron.github.io/google-apis-rs/google_deploymentmanager2_cli/resources_get", + vec![ + (Some(r##"project"##), + None, + Some(r##"The project ID for this request."##), + Some(true), + Some(false)), + + (Some(r##"deployment"##), + None, + Some(r##"The name of the deployment for this request."##), + Some(true), + Some(false)), + + (Some(r##"resource"##), + None, + Some(r##"The name of the resource for this request."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Lists all resources in a given deployment."##), + "Details at http://byron.github.io/google-apis-rs/google_deploymentmanager2_cli/resources_list", + vec![ + (Some(r##"project"##), + None, + Some(r##"The project ID for this request."##), + Some(true), + Some(false)), + + (Some(r##"deployment"##), + None, + Some(r##"The name of the deployment for this request."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("types", "methods: 'list'", vec![ + ("list", + Some(r##"Lists all resource types for Deployment Manager."##), + "Details at http://byron.github.io/google-apis-rs/google_deploymentmanager2_cli/types_list", + vec![ + (Some(r##"project"##), + None, + Some(r##"The project ID for this request."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ]; + + let mut app = App::new("deploymentmanager2") + .author("Sebastian Thiel ") + .version("0.3.2+20150831") + .about("The Deployment Manager API allows users to declaratively configure, deploy and run complex solutions on the Google Cloud Platform.") + .after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_deploymentmanager2_cli") + .arg(Arg::with_name("url") + .long("scope") + .help("Specify the authentication a method should be executed in. Each scope requires the user to grant this application permission to use it.If unset, it defaults to the shortest scope url for a particular method.") + .multiple(true) + .takes_value(true)) + .arg(Arg::with_name("folder") + .long("config-dir") + .help("A directory into which we will store our persistent data. Defaults to a user-writable directory that we will create during the first invocation.[default: ~/.google-service-cli") + .multiple(false) + .takes_value(true)) + .arg(Arg::with_name("debug") + .long("debug") + .help("Output all server communication to standard error. `tx` and `rx` are placed into the same stream.") + .multiple(false) + .takes_value(false)) + .arg(Arg::with_name("debug-auth") + .long("debug-auth") + .help("Output all communication related to authentication to standard error. `tx` and `rx` are placed into the same stream.") + .multiple(false) + .takes_value(false)); + + for &(main_command_name, ref about, ref subcommands) in arg_data.iter() { + let mut mcmd = SubCommand::with_name(main_command_name).about(about); + + for &(sub_command_name, ref desc, url_info, ref args) in subcommands { + let mut scmd = SubCommand::with_name(sub_command_name); + if let &Some(desc) = desc { + scmd = scmd.about(desc); + } + scmd = scmd.after_help(url_info); + + for &(ref arg_name, ref flag, ref desc, ref required, ref multi) in args { + let arg_name_str = + match (arg_name, flag) { + (&Some(an), _ ) => an, + (_ , &Some(f)) => f, + _ => unreachable!(), + }; + let mut arg = Arg::with_name(arg_name_str) + .empty_values(false); + if let &Some(short_flag) = flag { + arg = arg.short(short_flag); + } + if let &Some(desc) = desc { + arg = arg.help(desc); + } + if arg_name.is_some() && flag.is_some() { + arg = arg.takes_value(true); + } + if let &Some(required) = required { + arg = arg.required(required); + } + if let &Some(multi) = multi { + arg = arg.multiple(multi); + } + scmd = scmd.arg(arg); + } + mcmd = mcmd.subcommand(scmd); + } + app = app.subcommand(mcmd); + } + + let matches = app.get_matches(); + + let debug = matches.is_present("debug"); + match Engine::new(matches) { + Err(err) => { + exit_status = err.exit_code; + writeln!(io::stderr(), "{}", err).ok(); + }, + Ok(engine) => { + if let Err(doit_err) = engine.doit() { + exit_status = 1; + match doit_err { + DoitError::IoError(path, err) => { + writeln!(io::stderr(), "Failed to open output file '{}': {}", path, err).ok(); + }, + DoitError::ApiError(err) => { + if debug { + writeln!(io::stderr(), "{:#?}", err).ok(); + } else { + writeln!(io::stderr(), "{}", err).ok(); + } + } + } + } + } + } + + std::process::exit(exit_status); +} \ No newline at end of file diff --git a/gen/deploymentmanager2/Cargo.toml b/gen/deploymentmanager2/Cargo.toml new file mode 100644 index 0000000000..b37d8cba0a --- /dev/null +++ b/gen/deploymentmanager2/Cargo.toml @@ -0,0 +1,29 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-deploymentmanager2" +version = "0.1.9+20150831" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with Deployment Manager (protocol v2)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/deploymentmanager2" +homepage = "https://cloud.google.com/deployment-manager/" +documentation = "http://byron.github.io/google-apis-rs/google_deploymentmanager2" +license = "MIT" +keywords = ["deploymentmanager", "google", "protocol", "web", "api"] +build = "src/build.rs" + + +[dependencies] +hyper = ">= 0.6.8" +mime = "0.1.0" +serde = ">= 0.6.0" +serde_json = ">= 0.6.0" +yup-oauth2 = "*" +url = "*" + +[build-dependencies] +syntex = { version = "*" } +serde_codegen = { version = "*" } + diff --git a/gen/deploymentmanager2/LICENSE.md b/gen/deploymentmanager2/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/deploymentmanager2/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/README.md b/gen/deploymentmanager2/README.md new file mode 100644 index 0000000000..6c7063603c --- /dev/null +++ b/gen/deploymentmanager2/README.md @@ -0,0 +1,197 @@ + +The `google-deploymentmanager2` library allows access to all features of the *Google Deployment Manager* service. + +This documentation was generated from *Deployment Manager* crate version *0.1.9+20150831*, where *20150831* is the exact revision of the *deploymentmanager:v2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. + +Everything else about the *Deployment Manager* *v2* API can be found at the +[official documentation site](https://cloud.google.com/deployment-manager/). +# Features + +Handle the following *Resources* with ease from the central [hub](http://byron.github.io/google-apis-rs/google_deploymentmanager2/struct.DeploymentManager.html) ... + +* [deployments](http://byron.github.io/google-apis-rs/google_deploymentmanager2/struct.Deployment.html) + * [*cancel preview*](http://byron.github.io/google-apis-rs/google_deploymentmanager2/struct.DeploymentCancelPreviewCall.html), [*delete*](http://byron.github.io/google-apis-rs/google_deploymentmanager2/struct.DeploymentDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google_deploymentmanager2/struct.DeploymentGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google_deploymentmanager2/struct.DeploymentInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google_deploymentmanager2/struct.DeploymentListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google_deploymentmanager2/struct.DeploymentPatchCall.html), [*stop*](http://byron.github.io/google-apis-rs/google_deploymentmanager2/struct.DeploymentStopCall.html) and [*update*](http://byron.github.io/google-apis-rs/google_deploymentmanager2/struct.DeploymentUpdateCall.html) +* [manifests](http://byron.github.io/google-apis-rs/google_deploymentmanager2/struct.Manifest.html) + * [*get*](http://byron.github.io/google-apis-rs/google_deploymentmanager2/struct.ManifestGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google_deploymentmanager2/struct.ManifestListCall.html) +* [operations](http://byron.github.io/google-apis-rs/google_deploymentmanager2/struct.Operation.html) + * [*get*](http://byron.github.io/google-apis-rs/google_deploymentmanager2/struct.OperationGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google_deploymentmanager2/struct.OperationListCall.html) +* [resources](http://byron.github.io/google-apis-rs/google_deploymentmanager2/struct.ResourceType.html) + * [*get*](http://byron.github.io/google-apis-rs/google_deploymentmanager2/struct.ResourceGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google_deploymentmanager2/struct.ResourceListCall.html) +* [types](http://byron.github.io/google-apis-rs/google_deploymentmanager2/struct.Type.html) + * [*list*](http://byron.github.io/google-apis-rs/google_deploymentmanager2/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/struct.DeploymentManager.html)** + * a central object to maintain state and allow accessing all *Activities* + * creates [*Method Builders*](http://byron.github.io/google-apis-rs/google_deploymentmanager2/trait.MethodsBuilder.html) which in turn + allow access to individual [*Call Builders*](http://byron.github.io/google-apis-rs/google_deploymentmanager2/trait.CallBuilder.html) +* **[Resources](http://byron.github.io/google-apis-rs/google_deploymentmanager2/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/trait.Part.html)** + * a collection of properties + * never directly used in *Activities* +* **[Activities](http://byron.github.io/google-apis-rs/google_deploymentmanager2/trait.CallBuilder.html)** + * operations to apply to *Resources* + +All *structures* are marked with applicable traits to further categorize them and ease browsing. + +Generally speaking, you can invoke *Activities* like this: + +```Rust,ignore +let r = hub.resource().activity(...).doit() +``` + +Or specifically ... + +```ignore +let r = hub.deployments().update(...).doit() +let r = hub.deployments().insert(...).doit() +let r = hub.deployments().cancel_preview(...).doit() +let r = hub.operations().get(...).doit() +let r = hub.deployments().patch(...).doit() +let r = hub.deployments().stop(...).doit() +let r = hub.operations().list(...).doit() +let r = hub.deployments().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-deploymentmanager2 = "*" +``` + +## A complete example + +```Rust +extern crate hyper; +extern crate yup_oauth2 as oauth2; +extern crate google_deploymentmanager2 as deploymentmanager2; +use deploymentmanager2::Deployment; +use deploymentmanager2::{Result, Error}; +use std::default::Default; +use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +use deploymentmanager2::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); +// As the method needs a request, you would usually fill it with the desired information +// into the 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(); + +// You can configure optional parameters by calling 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().update(req, "project", "deployment") + .preview(false) + .delete_policy("sed") + .create_policy("et") + .doit(); + +match result { + Err(e) => match e { + // The Error enum provides details about what exactly happened. + // You can also just use its `Debug`, `Display` or `Error` traits + Error::HttpError(_) + |Error::MissingAPIKey + |Error::MissingToken(_) + |Error::Cancelled + |Error::UploadSizeLimitExceeded(_, _) + |Error::Failure(_) + |Error::BadRequest(_) + |Error::FieldClash(_) + |Error::JsonDecodeError(_, _) => println!("{}", e), + }, + Ok(res) => println!("Success: {:?}", res), +} + +``` +## Handling Errors + +All errors produced by the system are provided either as [Result](http://byron.github.io/google-apis-rs/google_deploymentmanager2/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/trait.Delegate.html), or the [Authenticator Delegate](http://byron.github.io/google-apis-rs/google_deploymentmanager2/../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 Downloads +If a method supports downloads, the response body, which is part of the [Result](http://byron.github.io/google-apis-rs/google_deploymentmanager2/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/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/trait.Delegate.html) to the +[Method Builder](http://byron.github.io/google-apis-rs/google_deploymentmanager2/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/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/trait.RequestValue.html) and +[decodable](http://byron.github.io/google-apis-rs/google_deploymentmanager2/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/trait.Part.html) which are identifiable 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/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/trait.RequestValue.html) are moved + +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** 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/src/build.rs b/gen/deploymentmanager2/src/build.rs new file mode 100644 index 0000000000..ded7972eee --- /dev/null +++ b/gen/deploymentmanager2/src/build.rs @@ -0,0 +1,16 @@ +extern crate syntex; +extern crate serde_codegen; + +use std::env; +use std::path::Path; + +pub fn main() { + let out_dir = env::var_os("OUT_DIR").unwrap(); + + let src = Path::new("src/lib.rs.in"); + let dst = Path::new(&out_dir).join("lib.rs"); + + let mut registry = syntex::Registry::new(); + serde_codegen::register(&mut registry); + registry.expand("google-deploymentmanager2", &src, &dst).unwrap(); +} diff --git a/gen/deploymentmanager2/src/cmn.rs b/gen/deploymentmanager2/src/cmn.rs new file mode 100644 index 0000000000..0e31353ba3 --- /dev/null +++ b/gen/deploymentmanager2/src/cmn.rs @@ -0,0 +1,762 @@ +// COPY OF 'src/rust/api/cmn.rs' +// DO NOT EDIT +use std::io::{self, Read, Seek, Cursor, Write, SeekFrom}; +use std; +use std::fmt::{self, Display}; +use std::str::FromStr; +use std::error; +use std::thread::sleep_ms; + +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::h1::LINE_ENDING; +use hyper::method::Method; +use hyper::status::StatusCode; + +use serde_json as json; + +/// 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 {} + +/// Identifies types for building methods of a particular resource type +pub trait MethodsBuilder {} + +/// Identifies types which represent builders for a particular resource method +pub trait CallBuilder {} + +/// Identifies types which can be inserted and deleted. +/// Types with this trait are most commonly used by clients of this API. +pub trait Resource {} + +/// Identifies types which are used in API responses. +pub trait ResponseResult {} + +/// Identifies types which are used in API requests. +pub trait RequestValue {} + +/// Identifies types which are not actually used by the API +/// This might be a bug within the google API schema. +pub trait UnusedType {} + +/// Identifies types which are only used as part of other types, which +/// usually are carrying the `Resource` trait. +pub trait Part {} + +/// 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 {} + +/// 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 +} + +/// A utility to represent detailed errors we might see in case there are BadRequests. +/// The latter happen if the sent parameters or request structures are unsound +#[derive(Deserialize, Serialize, Debug)] +pub struct ErrorResponse { + error: ServerError, +} + +#[derive(Deserialize, Serialize, Debug)] +pub struct ServerError { + errors: Vec, + code: u16, + message: String, +} + +#[derive(Deserialize, Serialize, Debug)] +pub struct ServerMessage { + domain: String, + reason: String, + message: String, + #[serde(rename="locationType")] + location_type: Option, + location: 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 successful. That way, the delegate 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. + /// + /// If you choose to retry after a duration, the duration should be chosen using the + /// [exponential backoff algorithm](http://en.wikipedia.org/wiki/Exponential_backoff). + /// + /// Return retry information. + fn http_error(&mut self, &hyper::Error) -> 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 it as a general information about the + /// impending failure. + /// The given Error provides information about why the token couldn't be acquired in the + /// first place + fn token(&mut self, err: &error::Error) -> Option { + let _ = err; + 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/canceled, 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()`. + /// It will also be called with None after a successful upload, which allows the delegate + /// to forget the URL. That way, we will not attempt to resume an upload that has already + /// finished. + fn store_upload_url(&mut self, url: Option<&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: &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. + /// + /// If you choose to retry after a duration, the duration should be chosen using the + /// [exponential backoff algorithm](http://en.wikipedia.org/wiki/Exponential_backoff). + fn http_failure(&mut self, _: &hyper::client::Response, Option, _: 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 {} + + +#[derive(Debug)] +pub enum Error { + /// The http connection failed + HttpError(hyper::Error), + + /// 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), + + /// Represents information about a request that was not understood by the server. + /// Details are included. + BadRequest(ErrorResponse), + + /// 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(Box), + + /// 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(String, json::Error), + + /// Indicates an HTTP repsonse with a non-success status code + Failure(hyper::client::Response), +} + + +impl Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + Error::HttpError(ref err) => err.fmt(f), + Error::UploadSizeLimitExceeded(ref resource_size, ref max_size) => + writeln!(f, "The media size {} exceeds the maximum allowed upload size of {}" + , resource_size, max_size), + Error::MissingAPIKey => { + (writeln!(f, "The application's API key was not found in the configuration")).ok(); + writeln!(f, "It is used as there are no Scopes defined for this method.") + }, + Error::BadRequest(ref err) => { + try!(writeln!(f, "Bad Requst ({}): {}", err.error.code, err.error.message)); + for err in err.error.errors.iter() { + try!(writeln!(f, " {}: {}, {}{}", + err.domain, + err.message, + err.reason, + match &err.location { + &Some(ref loc) => format!("@{}", loc), + &None => String::new(), + })); + } + Ok(()) + }, + Error::MissingToken(ref err) => + writeln!(f, "Token retrieval failed with error: {}", err), + Error::Cancelled => + writeln!(f, "Operation cancelled by delegate"), + Error::FieldClash(field) => + writeln!(f, "The custom parameter '{}' is already provided natively by the CallBuilder.", field), + Error::JsonDecodeError(ref json_str, ref err) + => writeln!(f, "{}: {}", err, json_str), + Error::Failure(ref response) => + writeln!(f, "Http status indicates failure: {:?}", response), + } + } +} + +impl error::Error for Error { + fn description(&self) -> &str { + match *self { + Error::HttpError(ref err) => err.description(), + Error::JsonDecodeError(_, ref err) => err.description(), + _ => "NO DESCRIPTION POSSIBLE - use `Display.fmt()` instead" + } + } + + fn cause(&self) -> Option<&error::Error> { + match *self { + Error::HttpError(ref err) => err.cause(), + Error::JsonDecodeError(_, ref err) => err.cause(), + _ => None + } + } +} + +/// A universal result type used as return for all calls. +pub type Result = std::result::Result; + +/// 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 + 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 following macro invocation needs to be expanded, as `include!` +// doens't support external macros +// header!{ +// #[doc="The `X-Upload-Content-Type` header."] +// (XUploadContentType, "X-Upload-Content-Type") => [Mime] + +// xupload_content_type { +// test_header!( +// test1, +// vec![b"text/plain"], +// Some(HeaderField( +// vec![Mime(TopLevel::Text, SubLevel::Plain, Vec::new())] +// ))); + +// } +// } + +/// The `X-Upload-Content-Type` header. +/// +/// Generated via rustc --pretty expanded -Z unstable-options, and manually +/// processed to be more readable. +#[derive(PartialEq, Debug, Clone)] +pub struct XUploadContentType(pub Mime); + +impl ::std::ops::Deref for XUploadContentType { + type Target = Mime; + fn deref<'a>(&'a self) -> &'a Mime { &self.0 } +} +impl ::std::ops::DerefMut for XUploadContentType { + fn deref_mut<'a>(&'a mut self) -> &'a mut Mime { &mut self.0 } +} +impl Header for XUploadContentType { + fn header_name() -> &'static str { "X-Upload-Content-Type" } + fn parse_header(raw: &[Vec]) -> hyper::error::Result { + hyper::header::parsing::from_one_raw_str(raw).map(XUploadContentType) + } +} +impl HeaderFormat for XUploadContentType { + fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { + Display::fmt(&**self, f) + } +} +impl Display for XUploadContentType { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Display::fmt(&**self, f) + } +} + +#[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]) -> hyper::error::Result { + Err(hyper::error::Error::Method) + } +} + + +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]) -> hyper::error::Result { + if raw.len() > 0 { + let v = &raw[0]; + if let Ok(s) = std::str::from_utf8(v) { + const PREFIX: &'static str = "bytes "; + if s.starts_with(PREFIX) { + if let Ok(c) = ::from_str(&s[PREFIX.len()..]) { + return Ok(RangeResponseHeader(c)) + } + } + } + } + Err(hyper::error::Error::Method) + } +} + +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, 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, A> ResumableUploadHelper<'a, A> + where A: oauth2::GetToken { + + fn query_transfer_status(&mut self) -> std::result::Result> { + 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, None) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + return Err(Ok(r)) + } + }; + return Ok(h.0.last) + } + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + return Err(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() { + Ok(s) => s, + Err(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 + }; + + self.reader.seek(SeekFrom::Start(start)).unwrap(); + loop { + let request_size = match self.content_length - start { + rs if rs > chunk_size => chunk_size, + rs => rs + }; + + 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 + } + // workaround https://github.com/rust-lang/rust/issues/22252 + let res = 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(); + match res { + 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, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + } + return Some(Ok(res)) + }, + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + return Some(Err(err)) + } + } + } + } +} + +// Copy of src/rust/cli/cmn.rs +// TODO(ST): Allow sharing common code between program types +pub fn remove_json_null_values(value: &mut json::value::Value) { + match *value { + json::value::Value::Object(ref mut map) => { + let mut for_removal = Vec::new(); + + for (key, mut value) in map.iter_mut() { + if value.is_null() { + for_removal.push(key.clone()); + } else { + remove_json_null_values(&mut value); + } + } + + for key in &for_removal { + map.remove(key); + } + } + _ => {} + } +} diff --git a/gen/deploymentmanager2/src/lib.rs b/gen/deploymentmanager2/src/lib.rs new file mode 100644 index 0000000000..0afc582c37 --- /dev/null +++ b/gen/deploymentmanager2/src/lib.rs @@ -0,0 +1,201 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/api/lib.rs.mako' +// DO NOT EDIT ! + +//! This documentation was generated from *Deployment Manager* crate version *0.1.9+20150831*, where *20150831* is the exact revision of the *deploymentmanager:v2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +//! +//! Everything else about the *Deployment Manager* *v2* API can be found at the +//! [official documentation site](https://cloud.google.com/deployment-manager/). +//! The original source code is [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/deploymentmanager2). +//! # Features +//! +//! Handle the following *Resources* with ease from the central [hub](struct.DeploymentManager.html) ... +//! +//! * [deployments](struct.Deployment.html) +//! * [*cancel preview*](struct.DeploymentCancelPreviewCall.html), [*delete*](struct.DeploymentDeleteCall.html), [*get*](struct.DeploymentGetCall.html), [*insert*](struct.DeploymentInsertCall.html), [*list*](struct.DeploymentListCall.html), [*patch*](struct.DeploymentPatchCall.html), [*stop*](struct.DeploymentStopCall.html) and [*update*](struct.DeploymentUpdateCall.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* +//! * creates [*Method Builders*](trait.MethodsBuilder.html) which in turn +//! allow access to individual [*Call Builders*](trait.CallBuilder.html) +//! * **[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* +//! +//! All *structures* are marked with applicable traits to further categorize them and ease browsing. +//! +//! Generally speaking, you can invoke *Activities* like this: +//! +//! ```Rust,ignore +//! let r = hub.resource().activity(...).doit() +//! ``` +//! +//! Or specifically ... +//! +//! ```ignore +//! let r = hub.deployments().update(...).doit() +//! let r = hub.deployments().insert(...).doit() +//! let r = hub.deployments().cancel_preview(...).doit() +//! let r = hub.operations().get(...).doit() +//! let r = hub.deployments().patch(...).doit() +//! let r = hub.deployments().stop(...).doit() +//! let r = hub.operations().list(...).doit() +//! let r = hub.deployments().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-deploymentmanager2 = "*" +//! ``` +//! +//! ## A complete example +//! +//! ```test_harness,no_run +//! extern crate hyper; +//! extern crate yup_oauth2 as oauth2; +//! extern crate google_deploymentmanager2 as deploymentmanager2; +//! use deploymentmanager2::Deployment; +//! use deploymentmanager2::{Result, Error}; +//! # #[test] fn egal() { +//! use std::default::Default; +//! use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +//! use deploymentmanager2::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); +//! // As the method needs a request, you would usually fill it with the desired information +//! // into the 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(); +//! +//! // You can configure optional parameters by calling 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().update(req, "project", "deployment") +//! .preview(true) +//! .delete_policy("dolor") +//! .create_policy("et") +//! .doit(); +//! +//! match result { +//! Err(e) => match e { +//! // The Error enum provides details about what exactly happened. +//! // You can also just use its `Debug`, `Display` or `Error` traits +//! Error::HttpError(_) +//! |Error::MissingAPIKey +//! |Error::MissingToken(_) +//! |Error::Cancelled +//! |Error::UploadSizeLimitExceeded(_, _) +//! |Error::Failure(_) +//! |Error::BadRequest(_) +//! |Error::FieldClash(_) +//! |Error::JsonDecodeError(_, _) => println!("{}", e), +//! }, +//! Ok(res) => println!("Success: {:?}", res), +//! } +//! # } +//! ``` +//! ## 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 Downloads +//! 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 identifiable 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 moved +//! +//! 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 +//! +//! + +// 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)] + +include!(concat!(env!("OUT_DIR"), "/lib.rs")); \ No newline at end of file diff --git a/gen/deploymentmanager2/src/lib.rs.in b/gen/deploymentmanager2/src/lib.rs.in new file mode 100644 index 0000000000..881f878927 --- /dev/null +++ b/gen/deploymentmanager2/src/lib.rs.in @@ -0,0 +1,5474 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/api/lib.rs.in.mako' +// DO NOT EDIT ! + +extern crate hyper; +extern crate serde; +extern crate serde_json; +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 serde_json as json; +use std::io; +use std::fs; +use std::thread::sleep_ms; + +pub use cmn::{MultiPartReader, ToParts, MethodInfo, Result, Error, CallBuilder, Hub, ReadSeek, Part, + ResponseResult, RequestValue, NestedType, Delegate, DefaultDelegate, MethodsBuilder, + Resource, ErrorResponse, remove_json_null_values}; + + +// ############## +// 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, + + /// View your data across Google Cloud Platform services + CloudPlatformReadOnly, +} + +impl AsRef for Scope { + fn as_ref(&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", + Scope::CloudPlatformReadOnly => "https://www.googleapis.com/auth/cloud-platform.read-only", + } + } +} + +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 as deploymentmanager2; +/// use deploymentmanager2::Deployment; +/// use deploymentmanager2::{Result, Error}; +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use deploymentmanager2::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); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the 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(); +/// +/// // You can configure optional parameters by calling 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().update(req, "project", "deployment") +/// .preview(true) +/// .delete_policy("takimata") +/// .create_policy("justo") +/// .doit(); +/// +/// match result { +/// Err(e) => match e { +/// // The Error enum provides details about what exactly happened. +/// // You can also just use its `Debug`, `Display` or `Error` traits +/// Error::HttpError(_) +/// |Error::MissingAPIKey +/// |Error::MissingToken(_) +/// |Error::Cancelled +/// |Error::UploadSizeLimitExceeded(_, _) +/// |Error::Failure(_) +/// |Error::BadRequest(_) +/// |Error::FieldClash(_) +/// |Error::JsonDecodeError(_, _) => println!("{}", e), +/// }, +/// Ok(res) => println!("Success: {:?}", res), +/// } +/// # } +/// ``` +pub struct DeploymentManager { + client: RefCell, + auth: RefCell, + _user_agent: String, +} + +impl<'a, C, A> Hub for DeploymentManager {} + +impl<'a, C, A> DeploymentManager + where 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.9".to_string(), + } + } + + pub fn deployments(&'a self) -> DeploymentMethods<'a, C, A> { + DeploymentMethods { hub: &self } + } + pub fn manifests(&'a self) -> ManifestMethods<'a, C, A> { + ManifestMethods { hub: &self } + } + pub fn operations(&'a self) -> OperationMethods<'a, C, A> { + OperationMethods { hub: &self } + } + pub fn resources(&'a self) -> ResourceMethods<'a, C, A> { + ResourceMethods { hub: &self } + } + pub fn types(&'a self) -> TypeMethods<'a, C, 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.9`. + /// + /// 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 ### +// ########## +/// [Output Only] If warning messages are generated during processing of this resource, 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, Serialize, Deserialize)] +pub struct ResourceWarnings { + /// [Output Only] Optional human-readable details for this warning. + pub message: Option, + /// [Output Only] The warning type identifier for this warning. + pub code: Option, + /// [Output Only] Metadata for this warning in key: value format. + pub data: Option>, +} + +impl NestedType for ResourceWarnings {} +impl Part for ResourceWarnings {} + + +/// +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where 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, Serialize, Deserialize)] +pub struct ResourceType { + /// [Output Only] The evaluated properties of the resource with references expanded. Returned as serialized YAML. + #[serde(rename="finalProperties")] + pub final_properties: Option, + /// [Output Only] Timestamp when the resource was updated, in RFC3339 text format . + #[serde(rename="updateTime")] + pub update_time: Option, + /// [Output Only] The name of the resource as it appears in the YAML config. + pub name: Option, + /// [Output Only] If warning messages are generated during processing of this resource, this field will be populated. + pub warnings: Option>, + /// [Output Only] The URL of the actual resource. + pub url: Option, + /// [Output Only] If Deployment Manager is currently updating or previewing an update to this resource, the updated configuration appears here. + pub update: Option, + /// [Output Only] URL of the manifest representing the current configuration of this resource. + pub manifest: Option, + /// [Output Only] The current properties of the resource before any references have been filled in. Returned as serialized YAML. + pub properties: Option, + /// [Output Only] Timestamp when the resource was created or acquired, in RFC3339 text format . + #[serde(rename="insertTime")] + pub insert_time: Option, + /// [Output Only] The type of the resource, for example compute.v1.instance, or replicaPools.v1beta2.instanceGroupManager. + #[serde(rename="type")] + pub type_: Option, + /// [Output Only] Unique identifier for the resource; defined by the server. + pub id: Option, +} + +impl Resource for ResourceType {} +impl ResponseResult for ResourceType {} + + +/// +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where 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 deployments](struct.DeploymentStopCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct DeploymentsStopRequest { + /// Specifies a fingerprint for stop() requests. A fingerprint is a randomly generated value that must be provided in stop() requests to perform optimistic locking. This ensures optimistic concurrency so that the deployment does not have conflicting requests (e.g. if someone attempts to make a new update request while another user attempts to stop an ongoing update request, this would prevent a collision). + /// + /// The fingerprint is initially generated by Deployment Manager and changes after every request to modify a deployment. To get the latest fingerprint value, perform a get() request to a deployment. + pub fingerprint: Option, +} + +impl RequestValue for DeploymentsStopRequest {} + + +/// +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [cancel preview deployments](struct.DeploymentCancelPreviewCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct DeploymentsCancelPreviewRequest { + /// Specifies a fingerprint for cancelPreview() requests. A fingerprint is a randomly generated value that must be provided in cancelPreview() requests to perform optimistic locking. This ensures optimistic concurrency so that the deployment does not have conflicting requests (e.g. if someone attempts to make a new update request while another user attempts to cancel a preview, this would prevent one of the requests). + /// + /// The fingerprint is initially generated by Deployment Manager and changes after every request to modify a deployment. To get the latest fingerprint value, perform a get() request to a deployment. + pub fingerprint: Option, +} + +impl RequestValue for DeploymentsCancelPreviewRequest {} + + +/// 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, Serialize, Deserialize)] +pub struct ResourcesListResponse { + /// A token used to continue a truncated list request. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// Resources contained in this list response. + pub resources: Option>, +} + +impl ResponseResult for ResourcesListResponse {} + + +/// [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 ResourceUpdateWarningsData { + /// [Output Only] A key for the warning data. + pub key: Option, + /// [Output Only] A warning data value corresponding to the key. + pub value: Option, +} + +impl NestedType for ResourceUpdateWarningsData {} +impl Part for ResourceUpdateWarningsData {} + + +/// +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where 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, Serialize, Deserialize)] +pub struct Manifest { + /// [Output Only] The YAML layout for this manifest. + pub layout: Option, + /// [Output Only] The name of the manifest. + pub name: Option, + /// [Output Only] The fully-expanded configuration file, including any templates and references. + #[serde(rename="expandedConfig")] + pub expanded_config: Option, + /// [Output Only] The imported files for this manifest. + pub imports: Option>, + /// [Output Only] Timestamp when the manifest was created, in RFC3339 text format. + #[serde(rename="insertTime")] + pub insert_time: Option, + /// [Output Only] The YAML configuration for this manifest. + pub config: Option, + /// [Output Only] Unique identifier for the resource; defined by the server. + pub id: Option, + /// [Output Only] Self link for the manifest. + #[serde(rename="selfLink")] + pub self_link: Option, +} + +impl Resource for Manifest {} +impl ResponseResult for Manifest {} + + +/// +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ConfigFile { + /// The contents of the file. + pub content: Option, +} + +impl Part for ConfigFile {} + + +/// 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, Serialize, Deserialize)] +pub struct TypesListResponse { + /// A token used to continue a truncated list request. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// [Output Only] A list of resource types supported by Deployment Manager. + pub types: Option>, +} + +impl ResponseResult for TypesListResponse {} + + +/// +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct TargetConfiguration { + /// Specifies any files to import for this configuration. This can be used to import templates or other files. For example, you might import a text file in order to use the file in a template. + pub imports: Option>, + /// The configuration to use for this deployment. + pub config: Option, +} + +impl Part for TargetConfiguration {} + + +/// [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, Serialize, Deserialize)] +pub struct OperationErrorErrors { + /// [Output Only] An optional, human-readable error message. + pub message: Option, + /// [Output Only] The error type identifier for this error. + pub code: Option, + /// [Output Only] Indicates the field in the request which caused the error. This property is optional. + pub location: Option, +} + +impl NestedType for OperationErrorErrors {} +impl Part for OperationErrorErrors {} + + +/// +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ResourceUpdate { + /// [Output Only] The expanded properties of the resource with reference values expanded. Returned as serialized YAML. + #[serde(rename="finalProperties")] + pub final_properties: Option, + /// [Output Only] The state of the resource. + pub state: Option, + /// [Output Only] The intent of the resource: PREVIEW, UPDATE, or CANCEL. + pub intent: Option, + /// [Output Only] If warning messages are generated during processing of this resource, this field will be populated. + pub warnings: Option>, + /// [Output Only] If errors are generated during update of the resource, this field will be populated. + pub error: Option, + /// [Output Only] The set of updated properties for this resource, before references are expanded. Returned as serialized YAML. + pub properties: Option, + /// [Output Only] URL of the manifest representing the update configuration of this resource. + pub manifest: Option, +} + +impl Part for ResourceUpdate {} + + +/// 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, Serialize, Deserialize)] +pub struct OperationsListResponse { + /// [Output Only] A token used to continue a truncated list request. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// [Output Only] Operations contained in this list response. + pub operations: Option>, +} + +impl ResponseResult for OperationsListResponse {} + + +/// A resource 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, Serialize, Deserialize)] +pub struct Type { + /// [Output Only] Timestamp when the type was created, in RFC3339 text format. + #[serde(rename="insertTime")] + pub insert_time: Option, + /// [Output Only] Unique identifier for the resource; defined by the server. + pub id: Option, + /// [Output Only] Self link for the type. + #[serde(rename="selfLink")] + pub self_link: Option, + /// Name of the type. + pub name: Option, +} + +impl Resource for Type {} + + +/// [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, Serialize, Deserialize)] +pub struct ResourceUpdateErrorErrors { + /// [Output Only] An optional, human-readable error message. + pub message: Option, + /// [Output Only] The error type identifier for this error. + pub code: Option, + /// [Output Only] Indicates the field in the request which caused the error. This property is optional. + pub location: Option, +} + +impl NestedType for ResourceUpdateErrorErrors {} +impl Part for ResourceUpdateErrorErrors {} + + +/// +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ImportFile { + /// The contents of the file. + pub content: Option, + /// The name of the file. + pub name: Option, +} + +impl Part for ImportFile {} + + +/// [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 OperationWarningsData { + /// [Output Only] A key for the warning data. + pub key: Option, + /// [Output Only] A warning data value corresponding to the key. + pub value: Option, +} + +impl NestedType for OperationWarningsData {} +impl Part for OperationWarningsData {} + + +/// [Output Only] If errors are generated during update of the resource, 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, Serialize, Deserialize)] +pub struct ResourceUpdateError { + /// [Output Only] The array of errors encountered while processing this operation. + pub errors: Option>, +} + +impl NestedType for ResourceUpdateError {} +impl Part for ResourceUpdateError {} + + +/// [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, Serialize, Deserialize)] +pub struct OperationWarnings { + /// [Output Only] Optional human-readable details for this warning. + pub message: Option, + /// [Output Only] The warning type identifier for this warning. + pub code: Option, + /// [Output Only] Metadata for this warning in key: value format. + pub data: Option>, +} + +impl NestedType for OperationWarnings {} +impl Part for OperationWarnings {} + + +/// [Output Only] If warning messages are generated during processing of this resource, 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, Serialize, Deserialize)] +pub struct ResourceUpdateWarnings { + /// [Output Only] Optional human-readable details for this warning. + pub message: Option, + /// [Output Only] The warning type identifier for this warning. + pub code: Option, + /// [Output Only] Metadata for this warning in key: value format. + pub data: Option>, +} + +impl NestedType for ResourceUpdateWarnings {} +impl Part for ResourceUpdateWarnings {} + + +/// +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct DeploymentUpdate { + /// [Output Only] URL of the manifest representing the update configuration of this deployment. + pub manifest: Option, +} + +impl Part for DeploymentUpdate {} + + +/// [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, Serialize, Deserialize)] +pub struct OperationError { + /// [Output Only] The array of errors encountered while processing this operation. + pub errors: Option>, +} + +impl NestedType for OperationError {} +impl Part for OperationError {} + + +/// 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, Serialize, Deserialize)] +pub struct DeploymentsListResponse { + /// [Output Only] A token used to continue a truncated list request. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// [Output Only] The deployments contained in this response. + pub deployments: Option>, +} + +impl ResponseResult for DeploymentsListResponse {} + + +/// +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where 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 deployments](struct.DeploymentUpdateCall.html) (request) +/// * [get deployments](struct.DeploymentGetCall.html) (response) +/// * [insert deployments](struct.DeploymentInsertCall.html) (request) +/// * [cancel preview deployments](struct.DeploymentCancelPreviewCall.html) (none) +/// * [list deployments](struct.DeploymentListCall.html) (none) +/// * [patch deployments](struct.DeploymentPatchCall.html) (request) +/// * [stop deployments](struct.DeploymentStopCall.html) (none) +/// * [delete deployments](struct.DeploymentDeleteCall.html) (none) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Deployment { + /// 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, + /// An optional user-provided description of the deployment. + pub description: Option, + /// [Output Only] If Deployment Manager is currently updating or previewing an update to this deployment, the updated configuration appears here. + pub update: Option, + /// [Output Only] URL of the manifest representing the last manifest that was successfully deployed. + pub manifest: Option, + /// [Output Only] Timestamp when the deployment was created, in RFC3339 text format . + #[serde(rename="insertTime")] + pub insert_time: Option, + /// Provides a fingerprint to use in requests to modify a deployment, such as update(), stop(), and cancelPreview() requests. A fingerprint is a randomly generated value that must be provided with update(), stop(), and cancelPreview() requests to perform optimistic locking. This ensures optimistic concurrency so that only one request happens at a time. + /// + /// The fingerprint is initially generated by Deployment Manager and changes after every request to modify data. To get the latest fingerprint value, perform a get() request to a deployment. + pub fingerprint: Option, + /// [Output Only] The Operation that most recently ran, or is currently running, on this deployment. + pub operation: Option, + /// [Output Only] Unique identifier for the resource; defined by the server. + pub id: Option, + /// [Input Only] The parameters that define your deployment, including the deployment configuration and relevant templates. + pub target: Option, +} + +impl RequestValue for Deployment {} +impl Resource for Deployment {} +impl ResponseResult for Deployment {} + + +/// 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*). +/// +/// * [update deployments](struct.DeploymentUpdateCall.html) (response) +/// * [insert deployments](struct.DeploymentInsertCall.html) (response) +/// * [cancel preview deployments](struct.DeploymentCancelPreviewCall.html) (response) +/// * [get operations](struct.OperationGetCall.html) (response) +/// * [patch deployments](struct.DeploymentPatchCall.html) (response) +/// * [stop deployments](struct.DeploymentStopCall.html) (response) +/// * [list operations](struct.OperationListCall.html) (none) +/// * [delete deployments](struct.DeploymentDeleteCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Operation { + /// [Output Only] Status of the operation. Can be one of the following: PENDING, RUNNING, or DONE. + pub status: Option, + /// [Output Only] The time that this operation was requested. This is in RFC3339 text format. + #[serde(rename="insertTime")] + pub insert_time: Option, + /// [Output Only] If warning messages are generated during processing of the operation, this field will be populated. + pub warnings: Option>, + /// [Output Only] If errors are generated during processing of the operation, this field will be populated. + pub error: Option, + /// [Output Only] Unique target ID which identifies a particular incarnation of the target. + #[serde(rename="targetId")] + pub target_id: Option, + /// [Output Only] URL of the resource the operation is mutating. + #[serde(rename="targetLink")] + pub target_link: Option, + /// [Output Only] The time that this operation was started by the server. This is in RFC3339 text format. + #[serde(rename="startTime")] + pub start_time: Option, + /// [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(rename="clientOperationId")] + pub client_operation_id: Option, + /// [Output Only] Creation timestamp in RFC3339 text format. + #[serde(rename="creationTimestamp")] + pub creation_timestamp: Option, + /// [Output Only] Unique identifier for the resource; defined by the server. + pub id: Option, + /// [Output Only] Type of the resource. Always compute#Operation for Operation resources. + pub kind: Option, + /// [Output Only] Name of the resource. + pub name: Option, + /// [Output Only] URL of the zone where the operation resides. + pub zone: Option, + /// [Output Only] URL of the region where the operation resides. Only applicable for regional resources. + pub region: Option, + /// [Output Only] Server-defined URL for the resource. + #[serde(rename="selfLink")] + pub self_link: Option, + /// [Output Only] Type of the operation, such as insert, update, and delete. + #[serde(rename="operationType")] + pub operation_type: Option, + /// [Output Only] If the operation fails, this field contains the HTTP error message that was returned, such as NOT FOUND. + #[serde(rename="httpErrorMessage")] + pub http_error_message: Option, + /// [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 monotonically increase as the operation progresses. + pub progress: Option, + /// [Output Only] The time that this operation was completed. This is in RFC3339 text format. + #[serde(rename="endTime")] + pub end_time: Option, + /// [Output Only] If the operation fails, this field contains the HTTP error message that was returned, such as 404. + #[serde(rename="httpErrorStatusCode")] + pub http_error_status_code: Option, + /// [Output Only] An optional textual description of the current status of the operation. + #[serde(rename="statusMessage")] + pub status_message: Option, + /// [Output Only] User who requested the operation, for example: user@example.com. + pub user: Option, +} + +impl Resource for Operation {} +impl ResponseResult for Operation {} + + +/// 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, Serialize, Deserialize)] +pub struct ManifestsListResponse { + /// [Output Only] A token used to continue a truncated list request. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// [Output Only] Manifests contained in this list response. + pub manifests: Option>, +} + +impl ResponseResult for ManifestsListResponse {} + + +/// [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 ResourceWarningsData { + /// [Output Only] A key for the warning data. + pub key: Option, + /// [Output Only] A warning data value corresponding to the key. + pub value: Option, +} + +impl NestedType for ResourceWarningsData {} +impl Part for ResourceWarningsData {} + + + +// ################### +// 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 as deploymentmanager2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use deploymentmanager2::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, A> + where C: 'a, A: 'a { + + hub: &'a DeploymentManager, +} + +impl<'a, C, A> MethodsBuilder for OperationMethods<'a, C, A> {} + +impl<'a, C, A> OperationMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Gets information about a specific operation. + /// + /// # Arguments + /// + /// * `project` - The project ID for this request. + /// * `operation` - The name of the operation for this request. + pub fn get(&self, project: &str, operation: &str) -> OperationGetCall<'a, C, 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. + /// + /// # Arguments + /// + /// * `project` - The project ID for this request. + pub fn list(&self, project: &str) -> OperationListCall<'a, C, A> { + OperationListCall { + 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 *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 as deploymentmanager2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use deploymentmanager2::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, A> + where C: 'a, A: 'a { + + hub: &'a DeploymentManager, +} + +impl<'a, C, A> MethodsBuilder for ManifestMethods<'a, C, A> {} + +impl<'a, C, A> ManifestMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Lists all manifests for a given deployment. + /// + /// # Arguments + /// + /// * `project` - The project ID for this request. + /// * `deployment` - The name of the deployment for this request. + pub fn list(&self, project: &str, deployment: &str) -> ManifestListCall<'a, C, A> { + ManifestListCall { + hub: self.hub, + _project: project.to_string(), + _deployment: deployment.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: + /// + /// Gets information about a specific manifest. + /// + /// # Arguments + /// + /// * `project` - The project ID for this request. + /// * `deployment` - The name of the deployment for this request. + /// * `manifest` - The name of the manifest for this request. + pub fn get(&self, project: &str, deployment: &str, manifest: &str) -> ManifestGetCall<'a, C, 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(), + } + } +} + + + +/// 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 as deploymentmanager2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use deploymentmanager2::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, A> + where C: 'a, A: 'a { + + hub: &'a DeploymentManager, +} + +impl<'a, C, A> MethodsBuilder for TypeMethods<'a, C, A> {} + +impl<'a, C, A> TypeMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Lists all resource types for Deployment Manager. + /// + /// # Arguments + /// + /// * `project` - The project ID for this request. + pub fn list(&self, project: &str) -> TypeListCall<'a, C, A> { + TypeListCall { + 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 *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 as deploymentmanager2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use deploymentmanager2::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, A> + where C: 'a, A: 'a { + + hub: &'a DeploymentManager, +} + +impl<'a, C, A> MethodsBuilder for ResourceMethods<'a, C, A> {} + +impl<'a, C, A> ResourceMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Gets information about a single resource. + /// + /// # Arguments + /// + /// * `project` - The project ID for this request. + /// * `deployment` - The name of the deployment for this request. + /// * `resource` - The name of the resource for this request. + pub fn get(&self, project: &str, deployment: &str, resource: &str) -> ResourceGetCall<'a, C, 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. + /// + /// # Arguments + /// + /// * `project` - The project ID for this request. + /// * `deployment` - The name of the deployment for this request. + pub fn list(&self, project: &str, deployment: &str) -> ResourceListCall<'a, C, A> { + ResourceListCall { + hub: self.hub, + _project: project.to_string(), + _deployment: deployment.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 *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 as deploymentmanager2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use deploymentmanager2::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 `cancel_preview(...)`, `delete(...)`, `get(...)`, `insert(...)`, `list(...)`, `patch(...)`, `stop(...)` and `update(...)` +/// // to build up your call. +/// let rb = hub.deployments(); +/// # } +/// ``` +pub struct DeploymentMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a DeploymentManager, +} + +impl<'a, C, A> MethodsBuilder for DeploymentMethods<'a, C, A> {} + +impl<'a, C, A> DeploymentMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Updates a deployment and all of the resources described by the deployment manifest. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `project` - The project ID for this request. + /// * `deployment` - The name of the deployment for this request. + pub fn update(&self, request: Deployment, project: &str, deployment: &str) -> DeploymentUpdateCall<'a, C, A> { + DeploymentUpdateCall { + hub: self.hub, + _request: request, + _project: project.to_string(), + _deployment: deployment.to_string(), + _preview: Default::default(), + _delete_policy: Default::default(), + _create_policy: 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 deployment. + /// + /// # Arguments + /// + /// * `project` - The project ID for this request. + /// * `deployment` - The name of the deployment for this request. + pub fn get(&self, project: &str, deployment: &str) -> DeploymentGetCall<'a, C, 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: + /// + /// Creates a deployment and all of the resources described by the deployment manifest. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `project` - The project ID for this request. + pub fn insert(&self, request: Deployment, project: &str) -> DeploymentInsertCall<'a, C, A> { + DeploymentInsertCall { + hub: self.hub, + _request: request, + _project: project.to_string(), + _preview: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Cancels and removes the preview currently associated with the deployment. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `project` - The project ID for this request. + /// * `deployment` - The name of the deployment for this request. + pub fn cancel_preview(&self, request: DeploymentsCancelPreviewRequest, project: &str, deployment: &str) -> DeploymentCancelPreviewCall<'a, C, A> { + DeploymentCancelPreviewCall { + hub: self.hub, + _request: request, + _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. + /// + /// # Arguments + /// + /// * `project` - The project ID for this request. + pub fn list(&self, project: &str) -> DeploymentListCall<'a, C, A> { + DeploymentListCall { + 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: + /// + /// Updates a deployment and all of the resources described by the deployment manifest. This method supports patch semantics. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `project` - The project ID for this request. + /// * `deployment` - The name of the deployment for this request. + pub fn patch(&self, request: Deployment, project: &str, deployment: &str) -> DeploymentPatchCall<'a, C, A> { + DeploymentPatchCall { + hub: self.hub, + _request: request, + _project: project.to_string(), + _deployment: deployment.to_string(), + _preview: Default::default(), + _delete_policy: Default::default(), + _create_policy: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Stops an ongoing operation. This does not roll back any work that has already been completed, but prevents any new work from being started. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `project` - The project ID for this request. + /// * `deployment` - The name of the deployment for this request. + pub fn stop(&self, request: DeploymentsStopRequest, project: &str, deployment: &str) -> DeploymentStopCall<'a, C, A> { + DeploymentStopCall { + hub: self.hub, + _request: request, + _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: + /// + /// Deletes a deployment and all of the resources in the deployment. + /// + /// # Arguments + /// + /// * `project` - The project ID for this request. + /// * `deployment` - The name of the deployment for this request. + pub fn delete(&self, project: &str, deployment: &str) -> DeploymentDeleteCall<'a, C, A> { + DeploymentDeleteCall { + hub: self.hub, + _project: project.to_string(), + _deployment: deployment.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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_deploymentmanager2 as deploymentmanager2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use deploymentmanager2::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, A> + where C: 'a, A: 'a { + + hub: &'a DeploymentManager, + _project: String, + _operation: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for OperationGetCall<'a, C, A> {} + +impl<'a, C, A> OperationGetCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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/v2/projects/{project}/global/operations/{operation}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::NdevCloudmanReadonly.as_ref().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 ["operation", "project"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The project ID for this request. + /// + /// 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) -> OperationGetCall<'a, C, A> { + self._project = new_value.to_string(); + self + } + /// The name of the operation for this request. + /// + /// 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) -> OperationGetCall<'a, C, A> { + self._operation = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> OperationGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::NdevCloudmanReadonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_deploymentmanager2 as deploymentmanager2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use deploymentmanager2::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("sea") +/// .max_results(11) +/// .filter("dolores") +/// .doit(); +/// # } +/// ``` +pub struct OperationListCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a DeploymentManager, + _project: String, + _page_token: Option, + _max_results: Option, + _filter: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for OperationListCall<'a, C, A> {} + +impl<'a, C, A> OperationListCall<'a, C, A> where 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((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 Err(Error::FieldClash(field)); + } + } + for (name, 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/v2/projects/{project}/global/operations".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::NdevCloudmanReadonly.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The project ID for this request. + /// + /// 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) -> OperationListCall<'a, C, A> { + self._project = new_value.to_string(); + self + } + /// Specifies a page token to use. Use this parameter if you want to list the next page of results. Set pageToken to the nextPageToken returned by a previous list request. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> OperationListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Maximum count of results to be returned. + /// + /// Sets the *max results* query property to the given value. + pub fn max_results(mut self, new_value: u32) -> OperationListCall<'a, C, A> { + self._max_results = Some(new_value); + self + } + /// Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must be in the format: FIELD_NAME COMPARISON_STRING LITERAL_STRING. + /// + /// The FIELD_NAME is the name of the field you want to compare. Only atomic field types are supported (string, number, boolean). The COMPARISON_STRING must be either eq (equals) or ne (not equals). The LITERAL_STRING is the string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field. + /// + /// For example, filter=name ne example-instance. + /// + /// Sets the *filter* query property to the given value. + pub fn filter(mut self, new_value: &str) -> OperationListCall<'a, C, A> { + self._filter = Some(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> OperationListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::NdevCloudmanReadonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_deploymentmanager2 as deploymentmanager2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use deploymentmanager2::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("aliquyam") +/// .max_results(35) +/// .filter("no") +/// .doit(); +/// # } +/// ``` +pub struct ManifestListCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a DeploymentManager, + _project: String, + _deployment: String, + _page_token: Option, + _max_results: Option, + _filter: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ManifestListCall<'a, C, A> {} + +impl<'a, C, A> ManifestListCall<'a, C, A> where 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((7 + 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())); + } + if let Some(value) = self._filter { + params.push(("filter", value.to_string())); + } + for &field in ["alt", "project", "deployment", "pageToken", "maxResults", "filter"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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/v2/projects/{project}/global/deployments/{deployment}/manifests".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::NdevCloudmanReadonly.as_ref().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 ["deployment", "project"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The project ID for this request. + /// + /// 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) -> ManifestListCall<'a, C, A> { + self._project = new_value.to_string(); + self + } + /// The name of the deployment for this request. + /// + /// 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. + pub fn deployment(mut self, new_value: &str) -> ManifestListCall<'a, C, A> { + self._deployment = new_value.to_string(); + self + } + /// Specifies a page token to use. Use this parameter if you want to list the next page of results. Set pageToken to the nextPageToken returned by a previous list request. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> ManifestListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Maximum count of results to be returned. + /// + /// Sets the *max results* query property to the given value. + pub fn max_results(mut self, new_value: u32) -> ManifestListCall<'a, C, A> { + self._max_results = Some(new_value); + self + } + /// Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must be in the format: FIELD_NAME COMPARISON_STRING LITERAL_STRING. + /// + /// The FIELD_NAME is the name of the field you want to compare. Only atomic field types are supported (string, number, boolean). The COMPARISON_STRING must be either eq (equals) or ne (not equals). The LITERAL_STRING is the string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field. + /// + /// For example, filter=name ne example-instance. + /// + /// Sets the *filter* query property to the given value. + pub fn filter(mut self, new_value: &str) -> ManifestListCall<'a, C, A> { + self._filter = Some(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManifestListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::NdevCloudmanReadonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_deploymentmanager2 as deploymentmanager2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use deploymentmanager2::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, A> + where C: '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, A> CallBuilder for ManifestGetCall<'a, C, A> {} + +impl<'a, C, A> ManifestGetCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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/v2/projects/{project}/global/deployments/{deployment}/manifests/{manifest}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::NdevCloudmanReadonly.as_ref().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 ["manifest", "deployment", "project"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The project ID for this request. + /// + /// 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) -> ManifestGetCall<'a, C, A> { + self._project = new_value.to_string(); + self + } + /// The name of the deployment for this request. + /// + /// 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. + pub fn deployment(mut self, new_value: &str) -> ManifestGetCall<'a, C, A> { + self._deployment = new_value.to_string(); + self + } + /// The name of the manifest for this request. + /// + /// 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. + pub fn manifest(mut self, new_value: &str) -> ManifestGetCall<'a, C, A> { + self._manifest = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ManifestGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::NdevCloudmanReadonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Lists all resource types for Deployment Manager. +/// +/// A builder for the *list* method supported by a *type* resource. +/// It is not used directly, but through a `TypeMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_deploymentmanager2 as deploymentmanager2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use deploymentmanager2::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("diam") +/// .max_results(46) +/// .filter("Lorem") +/// .doit(); +/// # } +/// ``` +pub struct TypeListCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a DeploymentManager, + _project: String, + _page_token: Option, + _max_results: Option, + _filter: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for TypeListCall<'a, C, A> {} + +impl<'a, C, A> TypeListCall<'a, C, A> where 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((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 Err(Error::FieldClash(field)); + } + } + for (name, 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/v2/projects/{project}/global/types".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::NdevCloudmanReadonly.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The project ID for this request. + /// + /// 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) -> TypeListCall<'a, C, A> { + self._project = new_value.to_string(); + self + } + /// Specifies a page token to use. Use this parameter if you want to list the next page of results. Set pageToken to the nextPageToken returned by a previous list request. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> TypeListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Maximum count of results to be returned. + /// + /// Sets the *max results* query property to the given value. + pub fn max_results(mut self, new_value: u32) -> TypeListCall<'a, C, A> { + self._max_results = Some(new_value); + self + } + /// Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must be in the format: FIELD_NAME COMPARISON_STRING LITERAL_STRING. + /// + /// The FIELD_NAME is the name of the field you want to compare. Only atomic field types are supported (string, number, boolean). The COMPARISON_STRING must be either eq (equals) or ne (not equals). The LITERAL_STRING is the string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field. + /// + /// For example, filter=name ne example-instance. + /// + /// Sets the *filter* query property to the given value. + pub fn filter(mut self, new_value: &str) -> TypeListCall<'a, C, A> { + self._filter = Some(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> TypeListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::NdevCloudmanReadonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_deploymentmanager2 as deploymentmanager2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use deploymentmanager2::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, A> + where C: '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, A> CallBuilder for ResourceGetCall<'a, C, A> {} + +impl<'a, C, A> ResourceGetCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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/v2/projects/{project}/global/deployments/{deployment}/resources/{resource}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::NdevCloudmanReadonly.as_ref().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 ["resource", "deployment", "project"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The project ID for this request. + /// + /// 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) -> ResourceGetCall<'a, C, A> { + self._project = new_value.to_string(); + self + } + /// The name of the deployment for this request. + /// + /// 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. + pub fn deployment(mut self, new_value: &str) -> ResourceGetCall<'a, C, A> { + self._deployment = new_value.to_string(); + self + } + /// The name of the resource for this request. + /// + /// 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. + pub fn resource(mut self, new_value: &str) -> ResourceGetCall<'a, C, A> { + self._resource = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ResourceGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::NdevCloudmanReadonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_deploymentmanager2 as deploymentmanager2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use deploymentmanager2::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("eos") +/// .max_results(20) +/// .filter("sadipscing") +/// .doit(); +/// # } +/// ``` +pub struct ResourceListCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a DeploymentManager, + _project: String, + _deployment: String, + _page_token: Option, + _max_results: Option, + _filter: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ResourceListCall<'a, C, A> {} + +impl<'a, C, A> ResourceListCall<'a, C, A> where 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((7 + 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())); + } + if let Some(value) = self._filter { + params.push(("filter", value.to_string())); + } + for &field in ["alt", "project", "deployment", "pageToken", "maxResults", "filter"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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/v2/projects/{project}/global/deployments/{deployment}/resources".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::NdevCloudmanReadonly.as_ref().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 ["deployment", "project"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The project ID for this request. + /// + /// 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) -> ResourceListCall<'a, C, A> { + self._project = new_value.to_string(); + self + } + /// The name of the deployment for this request. + /// + /// 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. + pub fn deployment(mut self, new_value: &str) -> ResourceListCall<'a, C, A> { + self._deployment = new_value.to_string(); + self + } + /// Specifies a page token to use. Use this parameter if you want to list the next page of results. Set pageToken to the nextPageToken returned by a previous list request. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> ResourceListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Maximum count of results to be returned. + /// + /// Sets the *max results* query property to the given value. + pub fn max_results(mut self, new_value: u32) -> ResourceListCall<'a, C, A> { + self._max_results = Some(new_value); + self + } + /// Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must be in the format: FIELD_NAME COMPARISON_STRING LITERAL_STRING. + /// + /// The FIELD_NAME is the name of the field you want to compare. Only atomic field types are supported (string, number, boolean). The COMPARISON_STRING must be either eq (equals) or ne (not equals). The LITERAL_STRING is the string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field. + /// + /// For example, filter=name ne example-instance. + /// + /// Sets the *filter* query property to the given value. + pub fn filter(mut self, new_value: &str) -> ResourceListCall<'a, C, A> { + self._filter = Some(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ResourceListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::NdevCloudmanReadonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Updates a deployment and all of the resources described by the deployment manifest. +/// +/// A builder for the *update* method supported by a *deployment* resource. +/// It is not used directly, but through a `DeploymentMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_deploymentmanager2 as deploymentmanager2; +/// use deploymentmanager2::Deployment; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use deploymentmanager2::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(); +/// +/// // You can configure optional parameters by calling 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().update(req, "project", "deployment") +/// .preview(true) +/// .delete_policy("amet") +/// .create_policy("no") +/// .doit(); +/// # } +/// ``` +pub struct DeploymentUpdateCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a DeploymentManager, + _request: Deployment, + _project: String, + _deployment: String, + _preview: Option, + _delete_policy: Option, + _create_policy: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for DeploymentUpdateCall<'a, C, A> {} + +impl<'a, C, A> DeploymentUpdateCall<'a, C, A> where 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.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((8 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("deployment", self._deployment.to_string())); + if let Some(value) = self._preview { + params.push(("preview", value.to_string())); + } + if let Some(value) = self._delete_policy { + params.push(("deletePolicy", value.to_string())); + } + if let Some(value) = self._create_policy { + params.push(("createPolicy", value.to_string())); + } + for &field in ["alt", "project", "deployment", "preview", "deletePolicy", "createPolicy"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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/v2/projects/{project}/global/deployments/{deployment}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().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 ["deployment", "project"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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) -> DeploymentUpdateCall<'a, C, A> { + self._request = new_value; + self + } + /// The project ID for this request. + /// + /// 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) -> DeploymentUpdateCall<'a, C, A> { + self._project = new_value.to_string(); + self + } + /// The name of the deployment for this request. + /// + /// 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. + pub fn deployment(mut self, new_value: &str) -> DeploymentUpdateCall<'a, C, A> { + self._deployment = new_value.to_string(); + self + } + /// If set to true, updates the deployment and creates and updates the "shell" resources but does not actually alter or instantiate these resources. This allows you to preview what your deployment looks like. You can use this intent to preview how an update would affect your deployment. You must provide a target.config with a configuration if this is set to true. After previewing a deployment, you can deploy your resources by making a request with the update() or you can cancelPreview() to remove the preview altogether. Note that the deployment will still exist after you cancel the preview and you must separately delete this deployment if you want to remove it. + /// + /// Sets the *preview* query property to the given value. + pub fn preview(mut self, new_value: bool) -> DeploymentUpdateCall<'a, C, A> { + self._preview = Some(new_value); + self + } + /// Sets the policy to use for deleting resources. + /// + /// Sets the *delete policy* query property to the given value. + pub fn delete_policy(mut self, new_value: &str) -> DeploymentUpdateCall<'a, C, A> { + self._delete_policy = Some(new_value.to_string()); + self + } + /// Sets the policy to use for creating new resources. + /// + /// Sets the *create policy* query property to the given value. + pub fn create_policy(mut self, new_value: &str) -> DeploymentUpdateCall<'a, C, A> { + self._create_policy = Some(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DeploymentUpdateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> DeploymentUpdateCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DeploymentUpdateCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_deploymentmanager2 as deploymentmanager2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use deploymentmanager2::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, A> + where C: 'a, A: 'a { + + hub: &'a DeploymentManager, + _project: String, + _deployment: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for DeploymentGetCall<'a, C, A> {} + +impl<'a, C, A> DeploymentGetCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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/v2/projects/{project}/global/deployments/{deployment}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::NdevCloudmanReadonly.as_ref().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 ["deployment", "project"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The project ID for this request. + /// + /// 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) -> DeploymentGetCall<'a, C, A> { + self._project = new_value.to_string(); + self + } + /// The name of the deployment for this request. + /// + /// 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. + pub fn deployment(mut self, new_value: &str) -> DeploymentGetCall<'a, C, A> { + self._deployment = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DeploymentGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::NdevCloudmanReadonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_deploymentmanager2 as deploymentmanager2; +/// use deploymentmanager2::Deployment; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use deploymentmanager2::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(); +/// +/// // You can configure optional parameters by calling 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") +/// .preview(true) +/// .doit(); +/// # } +/// ``` +pub struct DeploymentInsertCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a DeploymentManager, + _request: Deployment, + _project: String, + _preview: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for DeploymentInsertCall<'a, C, A> {} + +impl<'a, C, A> DeploymentInsertCall<'a, C, A> where 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((5 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + if let Some(value) = self._preview { + params.push(("preview", value.to_string())); + } + for &field in ["alt", "project", "preview"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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/v2/projects/{project}/global/deployments".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// The project ID for this request. + /// + /// 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) -> DeploymentInsertCall<'a, C, A> { + self._project = new_value.to_string(); + self + } + /// If set to true, creates a deployment and creates "shell" resources but does not actually instantiate these resources. This allows you to preview what your deployment looks like. After previewing a deployment, you can deploy your resources by making a request with the update() method or you can use the cancelPreview() method to cancel the preview altogether. Note that the deployment will still exist after you cancel the preview and you must separately delete this deployment if you want to remove it. + /// + /// Sets the *preview* query property to the given value. + pub fn preview(mut self, new_value: bool) -> DeploymentInsertCall<'a, C, A> { + self._preview = Some(new_value); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DeploymentInsertCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Cancels and removes the preview currently associated with the deployment. +/// +/// A builder for the *cancelPreview* method supported by a *deployment* resource. +/// It is not used directly, but through a `DeploymentMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_deploymentmanager2 as deploymentmanager2; +/// use deploymentmanager2::DeploymentsCancelPreviewRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use deploymentmanager2::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 = DeploymentsCancelPreviewRequest::default(); +/// +/// // You can configure optional parameters by calling 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().cancel_preview(req, "project", "deployment") +/// .doit(); +/// # } +/// ``` +pub struct DeploymentCancelPreviewCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a DeploymentManager, + _request: DeploymentsCancelPreviewRequest, + _project: String, + _deployment: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for DeploymentCancelPreviewCall<'a, C, A> {} + +impl<'a, C, A> DeploymentCancelPreviewCall<'a, C, A> where 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.cancelPreview", + 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(("deployment", self._deployment.to_string())); + for &field in ["alt", "project", "deployment"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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/v2/projects/{project}/global/deployments/{deployment}/cancelPreview".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().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 ["deployment", "project"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: DeploymentsCancelPreviewRequest) -> DeploymentCancelPreviewCall<'a, C, A> { + self._request = new_value; + self + } + /// The project ID for this request. + /// + /// 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) -> DeploymentCancelPreviewCall<'a, C, A> { + self._project = new_value.to_string(); + self + } + /// The name of the deployment for this request. + /// + /// 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. + pub fn deployment(mut self, new_value: &str) -> DeploymentCancelPreviewCall<'a, C, A> { + self._deployment = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DeploymentCancelPreviewCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> DeploymentCancelPreviewCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DeploymentCancelPreviewCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_deploymentmanager2 as deploymentmanager2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use deploymentmanager2::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("sea") +/// .max_results(80) +/// .filter("duo") +/// .doit(); +/// # } +/// ``` +pub struct DeploymentListCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a DeploymentManager, + _project: String, + _page_token: Option, + _max_results: Option, + _filter: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for DeploymentListCall<'a, C, A> {} + +impl<'a, C, A> DeploymentListCall<'a, C, A> where 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((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 Err(Error::FieldClash(field)); + } + } + for (name, 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/v2/projects/{project}/global/deployments".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::NdevCloudmanReadonly.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The project ID for this request. + /// + /// 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) -> DeploymentListCall<'a, C, A> { + self._project = new_value.to_string(); + self + } + /// Specifies a page token to use. Use this parameter if you want to list the next page of results. Set pageToken to the nextPageToken returned by a previous list request. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> DeploymentListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Maximum count of results to be returned. + /// + /// Sets the *max results* query property to the given value. + pub fn max_results(mut self, new_value: u32) -> DeploymentListCall<'a, C, A> { + self._max_results = Some(new_value); + self + } + /// Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must be in the format: FIELD_NAME COMPARISON_STRING LITERAL_STRING. + /// + /// The FIELD_NAME is the name of the field you want to compare. Only atomic field types are supported (string, number, boolean). The COMPARISON_STRING must be either eq (equals) or ne (not equals). The LITERAL_STRING is the string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field. + /// + /// For example, filter=name ne example-instance. + /// + /// Sets the *filter* query property to the given value. + pub fn filter(mut self, new_value: &str) -> DeploymentListCall<'a, C, A> { + self._filter = Some(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DeploymentListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::NdevCloudmanReadonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Updates a deployment and all of the resources described by the deployment manifest. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *deployment* resource. +/// It is not used directly, but through a `DeploymentMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_deploymentmanager2 as deploymentmanager2; +/// use deploymentmanager2::Deployment; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use deploymentmanager2::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(); +/// +/// // You can configure optional parameters by calling 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().patch(req, "project", "deployment") +/// .preview(false) +/// .delete_policy("et") +/// .create_policy("amet") +/// .doit(); +/// # } +/// ``` +pub struct DeploymentPatchCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a DeploymentManager, + _request: Deployment, + _project: String, + _deployment: String, + _preview: Option, + _delete_policy: Option, + _create_policy: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for DeploymentPatchCall<'a, C, A> {} + +impl<'a, C, A> DeploymentPatchCall<'a, C, A> where 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.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((8 + self._additional_params.len())); + params.push(("project", self._project.to_string())); + params.push(("deployment", self._deployment.to_string())); + if let Some(value) = self._preview { + params.push(("preview", value.to_string())); + } + if let Some(value) = self._delete_policy { + params.push(("deletePolicy", value.to_string())); + } + if let Some(value) = self._create_policy { + params.push(("createPolicy", value.to_string())); + } + for &field in ["alt", "project", "deployment", "preview", "deletePolicy", "createPolicy"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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/v2/projects/{project}/global/deployments/{deployment}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().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 ["deployment", "project"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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) -> DeploymentPatchCall<'a, C, A> { + self._request = new_value; + self + } + /// The project ID for this request. + /// + /// 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) -> DeploymentPatchCall<'a, C, A> { + self._project = new_value.to_string(); + self + } + /// The name of the deployment for this request. + /// + /// 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. + pub fn deployment(mut self, new_value: &str) -> DeploymentPatchCall<'a, C, A> { + self._deployment = new_value.to_string(); + self + } + /// If set to true, updates the deployment and creates and updates the "shell" resources but does not actually alter or instantiate these resources. This allows you to preview what your deployment looks like. You can use this intent to preview how an update would affect your deployment. You must provide a target.config with a configuration if this is set to true. After previewing a deployment, you can deploy your resources by making a request with the update() or you can cancelPreview() to remove the preview altogether. Note that the deployment will still exist after you cancel the preview and you must separately delete this deployment if you want to remove it. + /// + /// Sets the *preview* query property to the given value. + pub fn preview(mut self, new_value: bool) -> DeploymentPatchCall<'a, C, A> { + self._preview = Some(new_value); + self + } + /// Sets the policy to use for deleting resources. + /// + /// Sets the *delete policy* query property to the given value. + pub fn delete_policy(mut self, new_value: &str) -> DeploymentPatchCall<'a, C, A> { + self._delete_policy = Some(new_value.to_string()); + self + } + /// Sets the policy to use for creating new resources. + /// + /// Sets the *create policy* query property to the given value. + pub fn create_policy(mut self, new_value: &str) -> DeploymentPatchCall<'a, C, A> { + self._create_policy = Some(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DeploymentPatchCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> DeploymentPatchCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DeploymentPatchCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Stops an ongoing operation. This does not roll back any work that has already been completed, but prevents any new work from being started. +/// +/// A builder for the *stop* method supported by a *deployment* resource. +/// It is not used directly, but through a `DeploymentMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_deploymentmanager2 as deploymentmanager2; +/// use deploymentmanager2::DeploymentsStopRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use deploymentmanager2::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 = DeploymentsStopRequest::default(); +/// +/// // You can configure optional parameters by calling 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().stop(req, "project", "deployment") +/// .doit(); +/// # } +/// ``` +pub struct DeploymentStopCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a DeploymentManager, + _request: DeploymentsStopRequest, + _project: String, + _deployment: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for DeploymentStopCall<'a, C, A> {} + +impl<'a, C, A> DeploymentStopCall<'a, C, A> where 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.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(("deployment", self._deployment.to_string())); + for &field in ["alt", "project", "deployment"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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/v2/projects/{project}/global/deployments/{deployment}/stop".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().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 ["deployment", "project"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: DeploymentsStopRequest) -> DeploymentStopCall<'a, C, A> { + self._request = new_value; + self + } + /// The project ID for this request. + /// + /// 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) -> DeploymentStopCall<'a, C, A> { + self._project = new_value.to_string(); + self + } + /// The name of the deployment for this request. + /// + /// 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. + pub fn deployment(mut self, new_value: &str) -> DeploymentStopCall<'a, C, A> { + self._deployment = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DeploymentStopCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> DeploymentStopCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DeploymentStopCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_deploymentmanager2 as deploymentmanager2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use deploymentmanager2::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, A> + where C: 'a, A: 'a { + + hub: &'a DeploymentManager, + _project: String, + _deployment: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for DeploymentDeleteCall<'a, C, A> {} + +impl<'a, C, A> DeploymentDeleteCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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/v2/projects/{project}/global/deployments/{deployment}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().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 ["deployment", "project"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The project ID for this request. + /// + /// 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) -> DeploymentDeleteCall<'a, C, A> { + self._project = new_value.to_string(); + self + } + /// The name of the deployment for this request. + /// + /// 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. + pub fn deployment(mut self, new_value: &str) -> DeploymentDeleteCall<'a, C, A> { + self._deployment = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DeploymentDeleteCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + diff --git a/gen/deploymentmanager2_beta2-cli/Cargo.toml b/gen/deploymentmanager2_beta2-cli/Cargo.toml index cbb7cfa1fc..7334dbfa23 100644 --- a/gen/deploymentmanager2_beta2-cli/Cargo.toml +++ b/gen/deploymentmanager2_beta2-cli/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-deploymentmanager2_beta2-cli" -version = "0.3.2+20150715" +version = "0.3.2+20150831" authors = ["Sebastian Thiel "] description = "A complete library to interact with Deployment Manager (protocol v2beta2)" repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/deploymentmanager2_beta2-cli" diff --git a/gen/deploymentmanager2_beta2-cli/README.md b/gen/deploymentmanager2_beta2-cli/README.md index faefc6112b..00eae34916 100644 --- a/gen/deploymentmanager2_beta2-cli/README.md +++ b/gen/deploymentmanager2_beta2-cli/README.md @@ -24,7 +24,7 @@ Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/ma # Usage -This documentation was generated from the *Deployment Manager* API at revision *20150715*. The CLI is at version *0.3.2*. +This documentation was generated from the *Deployment Manager* API at revision *20150831*. The CLI is at version *0.3.2*. ```bash deploymentmanager2-beta2 [options] diff --git a/gen/deploymentmanager2_beta2-cli/mkdocs.yml b/gen/deploymentmanager2_beta2-cli/mkdocs.yml index ece76265c2..f3d1db932f 100644 --- a/gen/deploymentmanager2_beta2-cli/mkdocs.yml +++ b/gen/deploymentmanager2_beta2-cli/mkdocs.yml @@ -1,4 +1,4 @@ -site_name: Deployment Manager v0.3.2+20150715 +site_name: Deployment Manager v0.3.2+20150831 site_url: http://byron.github.io/google-apis-rs/google-deploymentmanager2_beta2-cli site_description: Write integrating applications with bcore diff --git a/gen/deploymentmanager2_beta2-cli/src/main.rs b/gen/deploymentmanager2_beta2-cli/src/main.rs index e51806072a..fa7d429e6d 100644 --- a/gen/deploymentmanager2_beta2-cli/src/main.rs +++ b/gen/deploymentmanager2_beta2-cli/src/main.rs @@ -1478,7 +1478,7 @@ fn main() { let mut app = App::new("deploymentmanager2-beta2") .author("Sebastian Thiel ") - .version("0.3.2+20150715") + .version("0.3.2+20150831") .about("The Deployment Manager API allows users to declaratively configure, deploy and run complex solutions on the Google Cloud Platform.") .after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_deploymentmanager2_beta2_cli") .arg(Arg::with_name("url") diff --git a/gen/deploymentmanager2_beta2/Cargo.toml b/gen/deploymentmanager2_beta2/Cargo.toml index cd467b50f1..1a928390cb 100644 --- a/gen/deploymentmanager2_beta2/Cargo.toml +++ b/gen/deploymentmanager2_beta2/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-deploymentmanager2_beta2" -version = "0.1.9+20150715" +version = "0.1.9+20150831" authors = ["Sebastian Thiel "] description = "A complete library to interact with Deployment Manager (protocol v2beta2)" repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/deploymentmanager2_beta2" diff --git a/gen/deploymentmanager2_beta2/README.md b/gen/deploymentmanager2_beta2/README.md index 0dbb0fdb14..ea6a547e80 100644 --- a/gen/deploymentmanager2_beta2/README.md +++ b/gen/deploymentmanager2_beta2/README.md @@ -5,7 +5,7 @@ DO NOT EDIT ! --> The `google-deploymentmanager2_beta2` library allows access to all features of the *Google Deployment Manager* service. -This documentation was generated from *Deployment Manager* crate version *0.1.9+20150715*, where *20150715* is the exact revision of the *deploymentmanager:v2beta2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +This documentation was generated from *Deployment Manager* crate version *0.1.9+20150831*, where *20150831* is the exact revision of the *deploymentmanager:v2beta2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. Everything else about the *Deployment Manager* *v2_beta2* API can be found at the [official documentation site](https://developers.google.com/deployment-manager/). diff --git a/gen/deploymentmanager2_beta2/src/lib.rs b/gen/deploymentmanager2_beta2/src/lib.rs index 5892c6ab4f..fd91a8c952 100644 --- a/gen/deploymentmanager2_beta2/src/lib.rs +++ b/gen/deploymentmanager2_beta2/src/lib.rs @@ -2,7 +2,7 @@ // This file was generated automatically from 'src/mako/api/lib.rs.mako' // DO NOT EDIT ! -//! This documentation was generated from *Deployment Manager* crate version *0.1.9+20150715*, where *20150715* is the exact revision of the *deploymentmanager:v2beta2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +//! This documentation was generated from *Deployment Manager* crate version *0.1.9+20150831*, where *20150831* is the exact revision of the *deploymentmanager:v2beta2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. //! //! Everything else about the *Deployment Manager* *v2_beta2* API can be found at the //! [official documentation site](https://developers.google.com/deployment-manager/). diff --git a/gen/deploymentmanager2_beta2/src/lib.rs.in b/gen/deploymentmanager2_beta2/src/lib.rs.in index 7d07ef2f84..d2be83ff46 100644 --- a/gen/deploymentmanager2_beta2/src/lib.rs.in +++ b/gen/deploymentmanager2_beta2/src/lib.rs.in @@ -43,6 +43,9 @@ pub enum Scope { /// View and manage your Google Cloud Platform management resources and deployment status information NdevCloudman, + + /// View your data across Google Cloud Platform services + CloudPlatformReadOnly, } impl AsRef for Scope { @@ -51,6 +54,7 @@ impl AsRef for Scope { 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", + Scope::CloudPlatformReadOnly => "https://www.googleapis.com/auth/cloud-platform.read-only", } } } @@ -280,6 +284,14 @@ impl Part for OperationWarnings {} /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct Type { + /// [Output Only] Timestamp when the type was created, in RFC3339 text format. + #[serde(rename="insertTime")] + pub insert_time: Option, + /// [Output Only] Unique identifier for the resource; defined by the server. + pub id: Option, + /// [Output Only] Self link for the type. + #[serde(rename="selfLink")] + pub self_link: Option, /// Name of the type. pub name: Option, } @@ -573,7 +585,7 @@ pub struct Operation { pub zone: Option, /// [Output Only] URL of the region where the operation resides. Only applicable for regional resources. pub region: Option, - /// [Output Only] Server defined URL for the resource. + /// [Output Only] Server-defined URL for the resource. #[serde(rename="selfLink")] pub self_link: Option, /// [Output Only] Type of the operation, such as insert, update, and delete. @@ -614,7 +626,7 @@ pub struct ResourceUpdate { pub state: Option, /// [Output Only] List of all errors encountered while trying to enact update.intent. pub errors: Option>, - /// [Output Only] The intent of the resource, PREVIEW, UPDATE, or CANCEL. + /// [Output Only] The intent of the resource: PREVIEW, UPDATE, or CANCEL. pub intent: Option, /// [Output Only] The set of updated properties for this resource, before references are expanded. Returned as serialized YAML. pub properties: Option, @@ -1593,14 +1605,11 @@ impl<'a, C, A> OperationListCall<'a, C, A> where C: BorrowMut, A: self._max_results = Some(new_value); self } - /// Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must contain the following: - /// FIELD_NAME COMPARISON_STRING LITERAL_STRING - /// - /// - FIELD_NAME: The name of the field you want to compare. The field name must be valid for the type of resource being filtered. Only atomic field types are supported (string, number, boolean). Array and object fields are not currently supported. - /// - COMPARISON_STRING: The comparison string, either eq (equals) or ne (not equals). - /// - LITERAL_STRING: The literal string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field. For example, you can filter by the name of a resource: - /// filter=name ne example-instance - /// The above filter returns only results whose name field does not equal example-instance. You can also enclose your literal string in single, double, or no quotes. + /// Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must be in the format: FIELD_NAME COMPARISON_STRING LITERAL_STRING. + /// + /// The FIELD_NAME is the name of the field you want to compare. Only atomic field types are supported (string, number, boolean). The COMPARISON_STRING must be either eq (equals) or ne (not equals). The LITERAL_STRING is the string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field. + /// + /// For example, filter=name ne example-instance. /// /// Sets the *filter* query property to the given value. pub fn filter(mut self, new_value: &str) -> OperationListCall<'a, C, A> { @@ -1884,14 +1893,11 @@ impl<'a, C, A> ManifestListCall<'a, C, A> where C: BorrowMut, A: self._max_results = Some(new_value); self } - /// Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must contain the following: - /// FIELD_NAME COMPARISON_STRING LITERAL_STRING - /// - /// - FIELD_NAME: The name of the field you want to compare. The field name must be valid for the type of resource being filtered. Only atomic field types are supported (string, number, boolean). Array and object fields are not currently supported. - /// - COMPARISON_STRING: The comparison string, either eq (equals) or ne (not equals). - /// - LITERAL_STRING: The literal string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field. For example, you can filter by the name of a resource: - /// filter=name ne example-instance - /// The above filter returns only results whose name field does not equal example-instance. You can also enclose your literal string in single, double, or no quotes. + /// Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must be in the format: FIELD_NAME COMPARISON_STRING LITERAL_STRING. + /// + /// The FIELD_NAME is the name of the field you want to compare. Only atomic field types are supported (string, number, boolean). The COMPARISON_STRING must be either eq (equals) or ne (not equals). The LITERAL_STRING is the string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field. + /// + /// For example, filter=name ne example-instance. /// /// Sets the *filter* query property to the given value. pub fn filter(mut self, new_value: &str) -> ManifestListCall<'a, C, A> { @@ -2695,14 +2701,11 @@ impl<'a, C, A> ResourceListCall<'a, C, A> where C: BorrowMut, A: self._max_results = Some(new_value); self } - /// Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must contain the following: - /// FIELD_NAME COMPARISON_STRING LITERAL_STRING - /// - /// - FIELD_NAME: The name of the field you want to compare. The field name must be valid for the type of resource being filtered. Only atomic field types are supported (string, number, boolean). Array and object fields are not currently supported. - /// - COMPARISON_STRING: The comparison string, either eq (equals) or ne (not equals). - /// - LITERAL_STRING: The literal string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field. For example, you can filter by the name of a resource: - /// filter=name ne example-instance - /// The above filter returns only results whose name field does not equal example-instance. You can also enclose your literal string in single, double, or no quotes. + /// Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must be in the format: FIELD_NAME COMPARISON_STRING LITERAL_STRING. + /// + /// The FIELD_NAME is the name of the field you want to compare. Only atomic field types are supported (string, number, boolean). The COMPARISON_STRING must be either eq (equals) or ne (not equals). The LITERAL_STRING is the string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field. + /// + /// For example, filter=name ne example-instance. /// /// Sets the *filter* query property to the given value. pub fn filter(mut self, new_value: &str) -> ResourceListCall<'a, C, A> { @@ -2974,14 +2977,11 @@ impl<'a, C, A> TypeListCall<'a, C, A> where C: BorrowMut, A: oaut self._max_results = Some(new_value); self } - /// Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must contain the following: - /// FIELD_NAME COMPARISON_STRING LITERAL_STRING - /// - /// - FIELD_NAME: The name of the field you want to compare. The field name must be valid for the type of resource being filtered. Only atomic field types are supported (string, number, boolean). Array and object fields are not currently supported. - /// - COMPARISON_STRING: The comparison string, either eq (equals) or ne (not equals). - /// - LITERAL_STRING: The literal string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field. For example, you can filter by the name of a resource: - /// filter=name ne example-instance - /// The above filter returns only results whose name field does not equal example-instance. You can also enclose your literal string in single, double, or no quotes. + /// Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must be in the format: FIELD_NAME COMPARISON_STRING LITERAL_STRING. + /// + /// The FIELD_NAME is the name of the field you want to compare. Only atomic field types are supported (string, number, boolean). The COMPARISON_STRING must be either eq (equals) or ne (not equals). The LITERAL_STRING is the string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field. + /// + /// For example, filter=name ne example-instance. /// /// Sets the *filter* query property to the given value. pub fn filter(mut self, new_value: &str) -> TypeListCall<'a, C, A> { @@ -4083,14 +4083,11 @@ impl<'a, C, A> DeploymentListCall<'a, C, A> where C: BorrowMut, A self._max_results = Some(new_value); self } - /// Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must contain the following: - /// FIELD_NAME COMPARISON_STRING LITERAL_STRING - /// - /// - FIELD_NAME: The name of the field you want to compare. The field name must be valid for the type of resource being filtered. Only atomic field types are supported (string, number, boolean). Array and object fields are not currently supported. - /// - COMPARISON_STRING: The comparison string, either eq (equals) or ne (not equals). - /// - LITERAL_STRING: The literal string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field. For example, you can filter by the name of a resource: - /// filter=name ne example-instance - /// The above filter returns only results whose name field does not equal example-instance. You can also enclose your literal string in single, double, or no quotes. + /// Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must be in the format: FIELD_NAME COMPARISON_STRING LITERAL_STRING. + /// + /// The FIELD_NAME is the name of the field you want to compare. Only atomic field types are supported (string, number, boolean). The COMPARISON_STRING must be either eq (equals) or ne (not equals). The LITERAL_STRING is the string value to filter to. The literal value must be valid for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field. + /// + /// For example, filter=name ne example-instance. /// /// Sets the *filter* query property to the given value. pub fn filter(mut self, new_value: &str) -> DeploymentListCall<'a, C, A> { diff --git a/gen/dfareporting2d1-cli/Cargo.toml b/gen/dfareporting2d1-cli/Cargo.toml index 3b5d0acaf7..5d68380fde 100644 --- a/gen/dfareporting2d1-cli/Cargo.toml +++ b/gen/dfareporting2d1-cli/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-dfareporting2d1-cli" -version = "0.3.2+20150326" +version = "0.3.2+20150717" authors = ["Sebastian Thiel "] description = "A complete library to interact with dfareporting (protocol v2.1)" repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/dfareporting2d1-cli" diff --git a/gen/dfareporting2d1-cli/README.md b/gen/dfareporting2d1-cli/README.md index e6b9ddcd24..49d2b15f3f 100644 --- a/gen/dfareporting2d1-cli/README.md +++ b/gen/dfareporting2d1-cli/README.md @@ -24,7 +24,7 @@ Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/ma # Usage -This documentation was generated from the *dfareporting* API at revision *20150326*. The CLI is at version *0.3.2*. +This documentation was generated from the *dfareporting* API at revision *20150717*. The CLI is at version *0.3.2*. ```bash dfareporting2d1 [options] diff --git a/gen/dfareporting2d1-cli/mkdocs.yml b/gen/dfareporting2d1-cli/mkdocs.yml index 6a1c08c425..7a5956e509 100644 --- a/gen/dfareporting2d1-cli/mkdocs.yml +++ b/gen/dfareporting2d1-cli/mkdocs.yml @@ -1,4 +1,4 @@ -site_name: dfareporting v0.3.2+20150326 +site_name: dfareporting v0.3.2+20150717 site_url: http://byron.github.io/google-apis-rs/google-dfareporting2d1-cli site_description: Write integrating applications with bcore diff --git a/gen/dfareporting2d1-cli/src/main.rs b/gen/dfareporting2d1-cli/src/main.rs index 0b6af48271..ea4b749fb9 100644 --- a/gen/dfareporting2d1-cli/src/main.rs +++ b/gen/dfareporting2d1-cli/src/main.rs @@ -22314,7 +22314,7 @@ fn main() { let mut app = App::new("dfareporting2d1") .author("Sebastian Thiel ") - .version("0.3.2+20150326") + .version("0.3.2+20150717") .about("Manage your DoubleClick Campaign Manager ad campaigns and reports.") .after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_dfareporting2d1_cli") .arg(Arg::with_name("url") diff --git a/gen/dfareporting2d1/Cargo.toml b/gen/dfareporting2d1/Cargo.toml index df505b84cf..d2d564dd5e 100644 --- a/gen/dfareporting2d1/Cargo.toml +++ b/gen/dfareporting2d1/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-dfareporting2d1" -version = "0.1.9+20150326" +version = "0.1.9+20150717" authors = ["Sebastian Thiel "] description = "A complete library to interact with dfareporting (protocol v2.1)" repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/dfareporting2d1" diff --git a/gen/dfareporting2d1/README.md b/gen/dfareporting2d1/README.md index dd9d064fb9..2abbf26843 100644 --- a/gen/dfareporting2d1/README.md +++ b/gen/dfareporting2d1/README.md @@ -5,7 +5,7 @@ DO NOT EDIT ! --> The `google-dfareporting2d1` library allows access to all features of the *Google dfareporting* service. -This documentation was generated from *dfareporting* crate version *0.1.9+20150326*, where *20150326* is the exact revision of the *dfareporting:v2.1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +This documentation was generated from *dfareporting* crate version *0.1.9+20150717*, where *20150717* is the exact revision of the *dfareporting:v2.1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. Everything else about the *dfareporting* *v2d1* API can be found at the [official documentation site](https://developers.google.com/doubleclick-advertisers/reporting/). diff --git a/gen/dfareporting2d1/src/lib.rs b/gen/dfareporting2d1/src/lib.rs index cb49836814..3776eb91f0 100644 --- a/gen/dfareporting2d1/src/lib.rs +++ b/gen/dfareporting2d1/src/lib.rs @@ -2,7 +2,7 @@ // This file was generated automatically from 'src/mako/api/lib.rs.mako' // DO NOT EDIT ! -//! This documentation was generated from *dfareporting* crate version *0.1.9+20150326*, where *20150326* is the exact revision of the *dfareporting:v2.1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +//! This documentation was generated from *dfareporting* crate version *0.1.9+20150717*, where *20150717* is the exact revision of the *dfareporting:v2.1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. //! //! Everything else about the *dfareporting* *v2d1* API can be found at the //! [official documentation site](https://developers.google.com/doubleclick-advertisers/reporting/). diff --git a/gen/dfareporting2d1/src/lib.rs.in b/gen/dfareporting2d1/src/lib.rs.in index ff9be0bfc3..c4279f26a2 100644 --- a/gen/dfareporting2d1/src/lib.rs.in +++ b/gen/dfareporting2d1/src/lib.rs.in @@ -835,7 +835,7 @@ pub struct TagSettings { impl Part for TagSettings {} -/// Contains properties of a targetable remarketing list. Remarketing enables you to create lists of users who have performed specific actions on a site, then target ads to members of those lists. This resource is a read-only view of a remarketing list to be used to faciliate targeting ads to specific lists. Remarketing lists that are owned by your advertisers and those that are shared to your advertisers or account are accessible via this resource. To manage remarketing lists that are owned by your advertisers, use the RemarketingList resource. +/// Contains properties of a targetable remarketing list. Remarketing enables you to create lists of users who have performed specific actions on a site, then target ads to members of those lists. This resource is a read-only view of a remarketing list to be used to faciliate targeting ads to specific lists. Remarketing lists that are owned by your advertisers and those that are shared to your advertisers or account are accessible via this resource. To manage remarketing lists that are owned by your advertisers, use the RemarketingLists resource. /// /// # Activities /// @@ -4232,7 +4232,7 @@ pub struct SitesListResponse { pub next_page_token: Option, /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#sitesListResponse". pub kind: Option, - /// Site collection + /// Site collection. pub sites: Option>, } @@ -4287,7 +4287,7 @@ impl Resource for PostalCode {} impl ResponseResult for PostalCode {} -/// Contains properties of a remarketing list. Remarketing enables you to create lists of users who have performed specific actions on a site, then target ads to members of those lists. This resource can be used to manage remarketing lists that are owned by your advertisers. To see all remarketing lists that are visible to your advertisers, including those that are shared to your advertiser or account, use the TargetableRemarketingList resource. +/// Contains properties of a remarketing list. Remarketing enables you to create lists of users who have performed specific actions on a site, then target ads to members of those lists. This resource can be used to manage remarketing lists that are owned by your advertisers. To see all remarketing lists that are visible to your advertisers, including those that are shared to your advertiser or account, use the TargetableRemarketingLists resource. /// /// # Activities /// @@ -6261,7 +6261,7 @@ pub struct EventTag { 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. + /// Whether this tag is SSL-compliant or not. This is a read-only field. #[serde(rename="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. @@ -21128,10 +21128,10 @@ impl<'a, C, A> CreativeAssetInsertCall<'a, C, A> where C: BorrowMut EventTagListCall<'a, C, A> where C: BorrowMut, A: self._event_tag_types.push(new_value.to_string()); self } - /// 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. + /// Select only enabled event tags. What is considered enabled or disabled depends on the definitionsOnly parameter. 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. /// /// Sets the *enabled* query property to the given value. pub fn enabled(mut self, new_value: bool) -> EventTagListCall<'a, C, A> { self._enabled = Some(new_value); self } - /// 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. + /// Examine only the specified campaign or advertiser's event tags for matching selector criteria. When set to false, the parent advertiser and parent campaign of the specified ad or campaign is examined as well. In addition, when set to false, the status field is examined as well, along with the enabledByDefault field. This parameter can not be set to true when adId is specified as ads do not define their own even tags. /// /// Sets the *definitions only* query property to the given value. pub fn definitions_only(mut self, new_value: bool) -> EventTagListCall<'a, C, A> { diff --git a/gen/dfareporting2d2-cli/Cargo.toml b/gen/dfareporting2d2-cli/Cargo.toml new file mode 100644 index 0000000000..00344c1d34 --- /dev/null +++ b/gen/dfareporting2d2-cli/Cargo.toml @@ -0,0 +1,35 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-dfareporting2d2-cli" +version = "0.3.2+20150717" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with dfareporting (protocol v2.2)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/dfareporting2d2-cli" +homepage = "https://developers.google.com/doubleclick-advertisers/reporting/" +documentation = "http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli" +license = "MIT" +keywords = ["dfareporting", "google", "cli"] + +[[bin]] +name = "dfareporting2d2" + +[dependencies] +hyper = ">= 0.6.8" +mime = "0.1.0" +serde = ">= 0.6.0" +serde_json = ">= 0.6.0" +yup-oauth2 = "*" +strsim = "*" +yup-hyper-mock = ">=1.0.0" +clap = ">= 1.0.3" + +[build-dependencies] +syntex = { version = "*" } +serde_codegen = { version = "*" } + + +[dependencies.google-dfareporting2d2] +path = "../dfareporting2d2" diff --git a/gen/dfareporting2d2-cli/LICENSE.md b/gen/dfareporting2d2-cli/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/dfareporting2d2-cli/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/dfareporting2d2-cli/README.md b/gen/dfareporting2d2-cli/README.md new file mode 100644 index 0000000000..ca851ca0a9 --- /dev/null +++ b/gen/dfareporting2d2-cli/README.md @@ -0,0 +1,359 @@ + +The `dfareporting2d2` command-line interface *(CLI)* allows to use most features of the *Google dfareporting* service from the comfort of your terminal. + +By default all output is printed to standard out, but flags can be set to direct it into a file independent of your shell's +capabilities. Errors will be printed to standard error, and cause the program's exit code to be non-zero. + +If data-structures are requested, these will be returned as pretty-printed JSON, to be useful as input to other tools. + +Everything else about the *dfareporting* API can be found at the +[official documentation site](https://developers.google.com/doubleclick-advertisers/reporting/). + +# Downloads + +You can download the pre-compiled 64bit binaries for the following platforms: + +* ![icon](http://megaicons.net/static/img/icons_sizes/6/140/16/ubuntu-icon.png) [ubuntu](http://dl.byronimo.de/google.rs/cli/0.3.2/ubuntu/dfareporting2d2.tar.gz) +* ![icon](http://hydra-media.cursecdn.com/wow.gamepedia.com/a/a2/Apple-icon-16x16.png?version=25ddd67ac3dd3b634478e3978b76cb74) [osx](http://dl.byronimo.de/google.rs/cli/0.3.2/osx/dfareporting2d2.tar.gz) + +Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/dfareporting2d2-cli). + +# Usage + +This documentation was generated from the *dfareporting* API at revision *20150717*. The CLI is at version *0.3.2*. + +```bash +dfareporting2d2 [options] + account-active-ad-summaries + get [-p ]... [-o ] + account-permission-groups + get [-p ]... [-o ] + list [-p ]... [-o ] + account-permissions + get [-p ]... [-o ] + list [-p ]... [-o ] + account-user-profiles + get [-p ]... [-o ] + insert (-r )... [-p ]... [-o ] + list [-p ]... [-o ] + patch (-r )... [-p ]... [-o ] + update (-r )... [-p ]... [-o ] + accounts + get [-p ]... [-o ] + list [-p ]... [-o ] + patch (-r )... [-p ]... [-o ] + update (-r )... [-p ]... [-o ] + ads + get [-p ]... [-o ] + insert (-r )... [-p ]... [-o ] + list [-p ]... [-o ] + patch (-r )... [-p ]... [-o ] + update (-r )... [-p ]... [-o ] + advertiser-groups + delete [-p ]... + get [-p ]... [-o ] + insert (-r )... [-p ]... [-o ] + list [-p ]... [-o ] + patch (-r )... [-p ]... [-o ] + update (-r )... [-p ]... [-o ] + advertisers + get [-p ]... [-o ] + insert (-r )... [-p ]... [-o ] + list [-p ]... [-o ] + patch (-r )... [-p ]... [-o ] + update (-r )... [-p ]... [-o ] + browsers + list [-p ]... [-o ] + campaign-creative-associations + insert (-r )... [-p ]... [-o ] + list [-p ]... [-o ] + campaigns + get [-p ]... [-o ] + insert (-r )... [-p ]... [-o ] + list [-p ]... [-o ] + patch (-r )... [-p ]... [-o ] + update (-r )... [-p ]... [-o ] + change-logs + get [-p ]... [-o ] + list [-p ]... [-o ] + cities + list [-p ]... [-o ] + connection-types + get [-p ]... [-o ] + list [-p ]... [-o ] + content-categories + delete [-p ]... + get [-p ]... [-o ] + insert (-r )... [-p ]... [-o ] + list [-p ]... [-o ] + patch (-r )... [-p ]... [-o ] + update (-r )... [-p ]... [-o ] + countries + get [-p ]... [-o ] + list [-p ]... [-o ] + creative-assets + insert (-r )... (-u (simple|resumable) -f [-m ]) [-p ]... [-o ] + creative-field-values + delete [-p ]... + get [-p ]... [-o ] + insert (-r )... [-p ]... [-o ] + list [-p ]... [-o ] + patch (-r )... [-p ]... [-o ] + update (-r )... [-p ]... [-o ] + creative-fields + delete [-p ]... + get [-p ]... [-o ] + insert (-r )... [-p ]... [-o ] + list [-p ]... [-o ] + patch (-r )... [-p ]... [-o ] + update (-r )... [-p ]... [-o ] + creative-groups + get [-p ]... [-o ] + insert (-r )... [-p ]... [-o ] + list [-p ]... [-o ] + patch (-r )... [-p ]... [-o ] + update (-r )... [-p ]... [-o ] + creatives + get [-p ]... [-o ] + insert (-r )... [-p ]... [-o ] + list [-p ]... [-o ] + patch (-r )... [-p ]... [-o ] + update (-r )... [-p ]... [-o ] + dimension-values + query (-r )... [-p ]... [-o ] + directory-site-contacts + get [-p ]... [-o ] + list [-p ]... [-o ] + directory-sites + get [-p ]... [-o ] + insert (-r )... [-p ]... [-o ] + list [-p ]... [-o ] + event-tags + delete [-p ]... + get [-p ]... [-o ] + insert (-r )... [-p ]... [-o ] + list [-p ]... [-o ] + patch (-r )... [-p ]... [-o ] + update (-r )... [-p ]... [-o ] + files + get [-p ]... [-o ] + list [-p ]... [-o ] + floodlight-activities + delete [-p ]... + generatetag [-p ]... [-o ] + get [-p ]... [-o ] + insert (-r )... [-p ]... [-o ] + list [-p ]... [-o ] + patch (-r )... [-p ]... [-o ] + update (-r )... [-p ]... [-o ] + floodlight-activity-groups + delete [-p ]... + get [-p ]... [-o ] + insert (-r )... [-p ]... [-o ] + list [-p ]... [-o ] + patch (-r )... [-p ]... [-o ] + update (-r )... [-p ]... [-o ] + floodlight-configurations + get [-p ]... [-o ] + list [-p ]... [-o ] + patch (-r )... [-p ]... [-o ] + update (-r )... [-p ]... [-o ] + inventory-items + get [-p ]... [-o ] + list [-p ]... [-o ] + landing-pages + delete [-p ]... + get [-p ]... [-o ] + insert (-r )... [-p ]... [-o ] + list [-p ]... [-o ] + patch (-r )... [-p ]... [-o ] + update (-r )... [-p ]... [-o ] + metros + list [-p ]... [-o ] + mobile-carriers + get [-p ]... [-o ] + list [-p ]... [-o ] + operating-system-versions + get [-p ]... [-o ] + list [-p ]... [-o ] + operating-systems + get [-p ]... [-o ] + list [-p ]... [-o ] + order-documents + get [-p ]... [-o ] + list [-p ]... [-o ] + orders + get [-p ]... [-o ] + list [-p ]... [-o ] + placement-groups + get [-p ]... [-o ] + insert (-r )... [-p ]... [-o ] + list [-p ]... [-o ] + patch (-r )... [-p ]... [-o ] + update (-r )... [-p ]... [-o ] + placement-strategies + delete [-p ]... + get [-p ]... [-o ] + insert (-r )... [-p ]... [-o ] + list [-p ]... [-o ] + patch (-r )... [-p ]... [-o ] + update (-r )... [-p ]... [-o ] + placements + generatetags [-p ]... [-o ] + get [-p ]... [-o ] + insert (-r )... [-p ]... [-o ] + list [-p ]... [-o ] + patch (-r )... [-p ]... [-o ] + update (-r )... [-p ]... [-o ] + platform-types + get [-p ]... [-o ] + list [-p ]... [-o ] + postal-codes + get [-p ]... [-o ] + list [-p ]... [-o ] + projects + get [-p ]... [-o ] + list [-p ]... [-o ] + regions + list [-p ]... [-o ] + remarketing-list-shares + get [-p ]... [-o ] + patch (-r )... [-p ]... [-o ] + update (-r )... [-p ]... [-o ] + remarketing-lists + get [-p ]... [-o ] + insert (-r )... [-p ]... [-o ] + list [-p ]... [-o ] + patch (-r )... [-p ]... [-o ] + update (-r )... [-p ]... [-o ] + reports + compatible-fields-query (-r )... [-p ]... [-o ] + delete [-p ]... + files-get [-p ]... [-o ] + files-list [-p ]... [-o ] + get [-p ]... [-o ] + insert (-r )... [-p ]... [-o ] + list [-p ]... [-o ] + patch (-r )... [-p ]... [-o ] + run [-p ]... [-o ] + update (-r )... [-p ]... [-o ] + sites + get [-p ]... [-o ] + insert (-r )... [-p ]... [-o ] + list [-p ]... [-o ] + patch (-r )... [-p ]... [-o ] + update (-r )... [-p ]... [-o ] + sizes + get [-p ]... [-o ] + insert (-r )... [-p ]... [-o ] + list [-p ]... [-o ] + subaccounts + get [-p ]... [-o ] + insert (-r )... [-p ]... [-o ] + list [-p ]... [-o ] + patch (-r )... [-p ]... [-o ] + update (-r )... [-p ]... [-o ] + targetable-remarketing-lists + get [-p ]... [-o ] + list [-p ]... [-o ] + user-profiles + get [-p ]... [-o ] + list [-p ]... [-o ] + user-role-permission-groups + get [-p ]... [-o ] + list [-p ]... [-o ] + user-role-permissions + get [-p ]... [-o ] + list [-p ]... [-o ] + user-roles + delete [-p ]... + get [-p ]... [-o ] + insert (-r )... [-p ]... [-o ] + list [-p ]... [-o ] + patch (-r )... [-p ]... [-o ] + update (-r )... [-p ]... [-o ] + dfareporting2d2 --help + +Configuration: + [--scope ]... + Specify the authentication a method should be executed in. Each scope + requires the user to grant this application permission to use it. + If unset, it defaults to the shortest scope url for a particular method. + --config-dir + A directory into which we will store our persistent data. Defaults to + a user-writable directory that we will create during the first invocation. + [default: ~/.google-service-cli] + --debug + Output all server communication to standard error. `tx` and `rx` are placed + into the same stream. + --debug-auth + Output all communication related to authentication to standard error. `tx` + and `rx` are placed into the same stream. + +``` + +# Configuration + +The program will store all persistent data in the `~/.google-service-cli` directory in *JSON* files prefixed with `dfareporting2d2-`. You can change the directory used to store configuration with the `--config-dir` flag on a per-invocation basis. + +More information about the various kinds of persistent data are given in the following paragraphs. + +# Authentication + +Most APIs require a user to authenticate any request. If this is the case, the [scope][scopes] determines the +set of permissions granted. The granularity of these is usually no more than *read-only* or *full-access*. + +If not set, the system will automatically select the smallest feasible scope, e.g. when invoking a +method that is read-only, it will ask only for a read-only scope. +You may use the `--scope` flag to specify a scope directly. +All applicable scopes are documented in the respective method's CLI documentation. + +The first time a scope is used, the user is asked for permission. Follow the instructions given +by the CLI to grant permissions, or to decline. + +If a scope was authenticated by the user, the respective information will be stored as *JSON* in the configuration +directory, e.g. `~/.google-service-cli/dfareporting2d2-token-.json`. No manual management of these tokens +is necessary. + +To revoke granted authentication, please refer to the [official documentation][revoke-access]. + +# Application Secrets + +In order to allow any application to use Google services, it will need to be registered using the +[Google Developer Console][google-dev-console]. APIs the application may use are then enabled for it +one by one. Most APIs can be used for free and have a daily quota. + +To allow more comfortable usage of the CLI without forcing anyone to register an own application, the CLI +comes with a default application secret that is configured accordingly. This also means that heavy usage +all around the world may deplete the daily quota. + +You can workaround this limitation by putting your own secrets file at this location: +`~/.google-service-cli/dfareporting2d2-secret.json`, assuming that the required *dfareporting* API +was enabled for it. Such a secret file can be downloaded in the *Google Developer Console* at +*APIs & auth -> Credentials -> Download JSON* and used as is. + +Learn more about how to setup Google projects and enable APIs using the [official documentation][google-project-new]. + + +# Debugging + +Even though the CLI does its best to provide usable error messages, sometimes it might be desirable to know +what exactly led to a particular issue. This is done by allowing all client-server communication to be +output to standard error *as-is*. + +The `--debug` flag will print all client-server communication to standard error, whereas the `--debug-auth` flag +will cause all communication related to authentication to standard error. +If the `--debug` flag is set, error-results will be debug-printed, possibly yielding more information about the +issue at hand. + +You may consider redirecting standard error into a file for ease of use, e.g. `dfareporting2d2 --debug [options] 2>debug.txt`. + + +[scopes]: https://developers.google.com/+/api/oauth#scopes +[revoke-access]: http://webapps.stackexchange.com/a/30849 +[google-dev-console]: https://console.developers.google.com/ +[google-project-new]: https://developers.google.com/console/help/new/ \ No newline at end of file diff --git a/gen/dfareporting2d2-cli/mkdocs.yml b/gen/dfareporting2d2-cli/mkdocs.yml new file mode 100644 index 0000000000..4ed6ed6506 --- /dev/null +++ b/gen/dfareporting2d2-cli/mkdocs.yml @@ -0,0 +1,209 @@ +site_name: dfareporting v0.3.2+20150717 +site_url: http://byron.github.io/google-apis-rs/google-dfareporting2d2-cli +site_description: Write integrating applications with bcore + +repo_url: https://github.com/Byron/google-apis-rs/tree/master/gen/dfareporting2d2-cli + +docs_dir: docs +site_dir: build_html + +pages: +- ['index.md', 'Home'] +- ['account-active-ad-summaries_get.md', 'Account Active Ad Summaries', 'Get'] +- ['account-permission-groups_get.md', 'Account Permission Groups', 'Get'] +- ['account-permission-groups_list.md', 'Account Permission Groups', 'List'] +- ['account-permissions_get.md', 'Account Permissions', 'Get'] +- ['account-permissions_list.md', 'Account Permissions', 'List'] +- ['account-user-profiles_get.md', 'Account User Profiles', 'Get'] +- ['account-user-profiles_insert.md', 'Account User Profiles', 'Insert'] +- ['account-user-profiles_list.md', 'Account User Profiles', 'List'] +- ['account-user-profiles_patch.md', 'Account User Profiles', 'Patch'] +- ['account-user-profiles_update.md', 'Account User Profiles', 'Update'] +- ['accounts_get.md', 'Accounts', 'Get'] +- ['accounts_list.md', 'Accounts', 'List'] +- ['accounts_patch.md', 'Accounts', 'Patch'] +- ['accounts_update.md', 'Accounts', 'Update'] +- ['ads_get.md', 'Ads', 'Get'] +- ['ads_insert.md', 'Ads', 'Insert'] +- ['ads_list.md', 'Ads', 'List'] +- ['ads_patch.md', 'Ads', 'Patch'] +- ['ads_update.md', 'Ads', 'Update'] +- ['advertiser-groups_delete.md', 'Advertiser Groups', 'Delete'] +- ['advertiser-groups_get.md', 'Advertiser Groups', 'Get'] +- ['advertiser-groups_insert.md', 'Advertiser Groups', 'Insert'] +- ['advertiser-groups_list.md', 'Advertiser Groups', 'List'] +- ['advertiser-groups_patch.md', 'Advertiser Groups', 'Patch'] +- ['advertiser-groups_update.md', 'Advertiser Groups', 'Update'] +- ['advertisers_get.md', 'Advertisers', 'Get'] +- ['advertisers_insert.md', 'Advertisers', 'Insert'] +- ['advertisers_list.md', 'Advertisers', 'List'] +- ['advertisers_patch.md', 'Advertisers', 'Patch'] +- ['advertisers_update.md', 'Advertisers', 'Update'] +- ['browsers_list.md', 'Browsers', 'List'] +- ['campaign-creative-associations_insert.md', 'Campaign Creative Associations', 'Insert'] +- ['campaign-creative-associations_list.md', 'Campaign Creative Associations', 'List'] +- ['campaigns_get.md', 'Campaigns', 'Get'] +- ['campaigns_insert.md', 'Campaigns', 'Insert'] +- ['campaigns_list.md', 'Campaigns', 'List'] +- ['campaigns_patch.md', 'Campaigns', 'Patch'] +- ['campaigns_update.md', 'Campaigns', 'Update'] +- ['change-logs_get.md', 'Change Logs', 'Get'] +- ['change-logs_list.md', 'Change Logs', 'List'] +- ['cities_list.md', 'Cities', 'List'] +- ['connection-types_get.md', 'Connection Types', 'Get'] +- ['connection-types_list.md', 'Connection Types', 'List'] +- ['content-categories_delete.md', 'Content Categories', 'Delete'] +- ['content-categories_get.md', 'Content Categories', 'Get'] +- ['content-categories_insert.md', 'Content Categories', 'Insert'] +- ['content-categories_list.md', 'Content Categories', 'List'] +- ['content-categories_patch.md', 'Content Categories', 'Patch'] +- ['content-categories_update.md', 'Content Categories', 'Update'] +- ['countries_get.md', 'Countries', 'Get'] +- ['countries_list.md', 'Countries', 'List'] +- ['creative-assets_insert.md', 'Creative Assets', 'Insert'] +- ['creative-field-values_delete.md', 'Creative Field Values', 'Delete'] +- ['creative-field-values_get.md', 'Creative Field Values', 'Get'] +- ['creative-field-values_insert.md', 'Creative Field Values', 'Insert'] +- ['creative-field-values_list.md', 'Creative Field Values', 'List'] +- ['creative-field-values_patch.md', 'Creative Field Values', 'Patch'] +- ['creative-field-values_update.md', 'Creative Field Values', 'Update'] +- ['creative-fields_delete.md', 'Creative Fields', 'Delete'] +- ['creative-fields_get.md', 'Creative Fields', 'Get'] +- ['creative-fields_insert.md', 'Creative Fields', 'Insert'] +- ['creative-fields_list.md', 'Creative Fields', 'List'] +- ['creative-fields_patch.md', 'Creative Fields', 'Patch'] +- ['creative-fields_update.md', 'Creative Fields', 'Update'] +- ['creative-groups_get.md', 'Creative Groups', 'Get'] +- ['creative-groups_insert.md', 'Creative Groups', 'Insert'] +- ['creative-groups_list.md', 'Creative Groups', 'List'] +- ['creative-groups_patch.md', 'Creative Groups', 'Patch'] +- ['creative-groups_update.md', 'Creative Groups', 'Update'] +- ['creatives_get.md', 'Creatives', 'Get'] +- ['creatives_insert.md', 'Creatives', 'Insert'] +- ['creatives_list.md', 'Creatives', 'List'] +- ['creatives_patch.md', 'Creatives', 'Patch'] +- ['creatives_update.md', 'Creatives', 'Update'] +- ['dimension-values_query.md', 'Dimension Values', 'Query'] +- ['directory-site-contacts_get.md', 'Directory Site Contacts', 'Get'] +- ['directory-site-contacts_list.md', 'Directory Site Contacts', 'List'] +- ['directory-sites_get.md', 'Directory Sites', 'Get'] +- ['directory-sites_insert.md', 'Directory Sites', 'Insert'] +- ['directory-sites_list.md', 'Directory Sites', 'List'] +- ['event-tags_delete.md', 'Event Tags', 'Delete'] +- ['event-tags_get.md', 'Event Tags', 'Get'] +- ['event-tags_insert.md', 'Event Tags', 'Insert'] +- ['event-tags_list.md', 'Event Tags', 'List'] +- ['event-tags_patch.md', 'Event Tags', 'Patch'] +- ['event-tags_update.md', 'Event Tags', 'Update'] +- ['files_get.md', 'Files', 'Get'] +- ['files_list.md', 'Files', 'List'] +- ['floodlight-activities_delete.md', 'Floodlight Activities', 'Delete'] +- ['floodlight-activities_generatetag.md', 'Floodlight Activities', 'Generatetag'] +- ['floodlight-activities_get.md', 'Floodlight Activities', 'Get'] +- ['floodlight-activities_insert.md', 'Floodlight Activities', 'Insert'] +- ['floodlight-activities_list.md', 'Floodlight Activities', 'List'] +- ['floodlight-activities_patch.md', 'Floodlight Activities', 'Patch'] +- ['floodlight-activities_update.md', 'Floodlight Activities', 'Update'] +- ['floodlight-activity-groups_delete.md', 'Floodlight Activity Groups', 'Delete'] +- ['floodlight-activity-groups_get.md', 'Floodlight Activity Groups', 'Get'] +- ['floodlight-activity-groups_insert.md', 'Floodlight Activity Groups', 'Insert'] +- ['floodlight-activity-groups_list.md', 'Floodlight Activity Groups', 'List'] +- ['floodlight-activity-groups_patch.md', 'Floodlight Activity Groups', 'Patch'] +- ['floodlight-activity-groups_update.md', 'Floodlight Activity Groups', 'Update'] +- ['floodlight-configurations_get.md', 'Floodlight Configurations', 'Get'] +- ['floodlight-configurations_list.md', 'Floodlight Configurations', 'List'] +- ['floodlight-configurations_patch.md', 'Floodlight Configurations', 'Patch'] +- ['floodlight-configurations_update.md', 'Floodlight Configurations', 'Update'] +- ['inventory-items_get.md', 'Inventory Items', 'Get'] +- ['inventory-items_list.md', 'Inventory Items', 'List'] +- ['landing-pages_delete.md', 'Landing Pages', 'Delete'] +- ['landing-pages_get.md', 'Landing Pages', 'Get'] +- ['landing-pages_insert.md', 'Landing Pages', 'Insert'] +- ['landing-pages_list.md', 'Landing Pages', 'List'] +- ['landing-pages_patch.md', 'Landing Pages', 'Patch'] +- ['landing-pages_update.md', 'Landing Pages', 'Update'] +- ['metros_list.md', 'Metros', 'List'] +- ['mobile-carriers_get.md', 'Mobile Carriers', 'Get'] +- ['mobile-carriers_list.md', 'Mobile Carriers', 'List'] +- ['operating-system-versions_get.md', 'Operating System Versions', 'Get'] +- ['operating-system-versions_list.md', 'Operating System Versions', 'List'] +- ['operating-systems_get.md', 'Operating Systems', 'Get'] +- ['operating-systems_list.md', 'Operating Systems', 'List'] +- ['order-documents_get.md', 'Order Documents', 'Get'] +- ['order-documents_list.md', 'Order Documents', 'List'] +- ['orders_get.md', 'Orders', 'Get'] +- ['orders_list.md', 'Orders', 'List'] +- ['placement-groups_get.md', 'Placement Groups', 'Get'] +- ['placement-groups_insert.md', 'Placement Groups', 'Insert'] +- ['placement-groups_list.md', 'Placement Groups', 'List'] +- ['placement-groups_patch.md', 'Placement Groups', 'Patch'] +- ['placement-groups_update.md', 'Placement Groups', 'Update'] +- ['placement-strategies_delete.md', 'Placement Strategies', 'Delete'] +- ['placement-strategies_get.md', 'Placement Strategies', 'Get'] +- ['placement-strategies_insert.md', 'Placement Strategies', 'Insert'] +- ['placement-strategies_list.md', 'Placement Strategies', 'List'] +- ['placement-strategies_patch.md', 'Placement Strategies', 'Patch'] +- ['placement-strategies_update.md', 'Placement Strategies', 'Update'] +- ['placements_generatetags.md', 'Placements', 'Generatetags'] +- ['placements_get.md', 'Placements', 'Get'] +- ['placements_insert.md', 'Placements', 'Insert'] +- ['placements_list.md', 'Placements', 'List'] +- ['placements_patch.md', 'Placements', 'Patch'] +- ['placements_update.md', 'Placements', 'Update'] +- ['platform-types_get.md', 'Platform Types', 'Get'] +- ['platform-types_list.md', 'Platform Types', 'List'] +- ['postal-codes_get.md', 'Postal Codes', 'Get'] +- ['postal-codes_list.md', 'Postal Codes', 'List'] +- ['projects_get.md', 'Projects', 'Get'] +- ['projects_list.md', 'Projects', 'List'] +- ['regions_list.md', 'Regions', 'List'] +- ['remarketing-list-shares_get.md', 'Remarketing List Shares', 'Get'] +- ['remarketing-list-shares_patch.md', 'Remarketing List Shares', 'Patch'] +- ['remarketing-list-shares_update.md', 'Remarketing List Shares', 'Update'] +- ['remarketing-lists_get.md', 'Remarketing Lists', 'Get'] +- ['remarketing-lists_insert.md', 'Remarketing Lists', 'Insert'] +- ['remarketing-lists_list.md', 'Remarketing Lists', 'List'] +- ['remarketing-lists_patch.md', 'Remarketing Lists', 'Patch'] +- ['remarketing-lists_update.md', 'Remarketing Lists', 'Update'] +- ['reports_compatible-fields-query.md', 'Reports', 'Compatible Fields Query'] +- ['reports_delete.md', 'Reports', 'Delete'] +- ['reports_files-get.md', 'Reports', 'Files Get'] +- ['reports_files-list.md', 'Reports', 'Files List'] +- ['reports_get.md', 'Reports', 'Get'] +- ['reports_insert.md', 'Reports', 'Insert'] +- ['reports_list.md', 'Reports', 'List'] +- ['reports_patch.md', 'Reports', 'Patch'] +- ['reports_run.md', 'Reports', 'Run'] +- ['reports_update.md', 'Reports', 'Update'] +- ['sites_get.md', 'Sites', 'Get'] +- ['sites_insert.md', 'Sites', 'Insert'] +- ['sites_list.md', 'Sites', 'List'] +- ['sites_patch.md', 'Sites', 'Patch'] +- ['sites_update.md', 'Sites', 'Update'] +- ['sizes_get.md', 'Sizes', 'Get'] +- ['sizes_insert.md', 'Sizes', 'Insert'] +- ['sizes_list.md', 'Sizes', 'List'] +- ['subaccounts_get.md', 'Subaccounts', 'Get'] +- ['subaccounts_insert.md', 'Subaccounts', 'Insert'] +- ['subaccounts_list.md', 'Subaccounts', 'List'] +- ['subaccounts_patch.md', 'Subaccounts', 'Patch'] +- ['subaccounts_update.md', 'Subaccounts', 'Update'] +- ['targetable-remarketing-lists_get.md', 'Targetable Remarketing Lists', 'Get'] +- ['targetable-remarketing-lists_list.md', 'Targetable Remarketing Lists', 'List'] +- ['user-profiles_get.md', 'User Profiles', 'Get'] +- ['user-profiles_list.md', 'User Profiles', 'List'] +- ['user-role-permission-groups_get.md', 'User Role Permission Groups', 'Get'] +- ['user-role-permission-groups_list.md', 'User Role Permission Groups', 'List'] +- ['user-role-permissions_get.md', 'User Role Permissions', 'Get'] +- ['user-role-permissions_list.md', 'User Role Permissions', 'List'] +- ['user-roles_delete.md', 'User Roles', 'Delete'] +- ['user-roles_get.md', 'User Roles', 'Get'] +- ['user-roles_insert.md', 'User Roles', 'Insert'] +- ['user-roles_list.md', 'User Roles', 'List'] +- ['user-roles_patch.md', 'User Roles', 'Patch'] +- ['user-roles_update.md', 'User Roles', 'Update'] + +theme: readthedocs + +copyright: Copyright © 2015, `Sebastian Thiel` + diff --git a/gen/dfareporting2d2-cli/src/cmn.rs b/gen/dfareporting2d2-cli/src/cmn.rs new file mode 100644 index 0000000000..8358f156fa --- /dev/null +++ b/gen/dfareporting2d2-cli/src/cmn.rs @@ -0,0 +1,721 @@ +// COPY OF 'src/rust/cli/cmn.rs' +// DO NOT EDIT +use oauth2::{ApplicationSecret, ConsoleApplicationSecret, TokenStorage, Token}; +use serde_json as json; +use serde_json::value::Value; +use mime::Mime; +use clap::{App, SubCommand}; +use strsim; + +use std::fs; +use std::env; +use std::io; +use std::fmt; +use std::path::{Path, PathBuf}; +use std::str::FromStr; +use std::string::ToString; +use std::io::{Write, Read, stdout}; + +use std::default::Default; + +const FIELD_SEP: char = '.'; + + +pub enum ComplexType { + Pod, + Vec, + Map, +} + + // Null, + // Bool(bool), + // I64(i64), + // U64(u64), + // F64(f64), + // String(String), + +pub enum JsonType { + Boolean, + Int, + Uint, + Float, + String, +} + +pub struct JsonTypeInfo { + pub jtype: JsonType, + pub ctype: ComplexType, +} + +// Based on @erickt user comment. Thanks for the idea ! +// Remove all keys whose values are null from given value (changed in place) +pub fn remove_json_null_values(value: &mut Value) { + match *value { + Value::Object(ref mut map) => { + let mut for_removal = Vec::new(); + + for (key, mut value) in map.iter_mut() { + if value.is_null() { + for_removal.push(key.clone()); + } else { + remove_json_null_values(&mut value); + } + } + + for key in &for_removal { + map.remove(key); + } + } + _ => {} + } +} + +fn did_you_mean<'a>(v: &str, possible_values: &[&'a str]) -> Option<&'a str> { + + let mut candidate: Option<(f64, &str)> = None; + for pv in possible_values { + let confidence = strsim::jaro_winkler(v, pv); + if confidence > 0.8 && (candidate.is_none() || (candidate.as_ref().unwrap().0 < confidence)) { + candidate = Some((confidence, pv)); + } + } + match candidate { + None => None, + Some((_, candidate)) => Some(candidate), + } +} + +pub enum CallType { + Upload(UploadProtocol), + Standard, +} + +arg_enum!{ + pub enum UploadProtocol { + Simple, + Resumable + } +} + +impl AsRef for UploadProtocol { + fn as_ref(&self) -> &str { + match *self { + UploadProtocol::Simple => "simple", + UploadProtocol::Resumable => "resumable" + } + } +} + +impl AsRef for CallType { + fn as_ref(&self) -> &str { + match *self { + CallType::Upload(ref proto) => proto.as_ref(), + CallType::Standard => "standard-request" + } + } +} + +#[derive(Clone, Default)] +pub struct FieldCursor(Vec); + +impl ToString for FieldCursor { + fn to_string(&self) -> String { + self.0.join(".") + } +} + +impl From<&'static str> for FieldCursor { + fn from(value: &'static str) -> FieldCursor { + let mut res = FieldCursor::default(); + res.set(value).unwrap(); + res + } +} + +impl FieldCursor { + pub fn set(&mut self, value: &str) -> Result<(), CLIError> { + if value.len() == 0 { + return Err(CLIError::Field(FieldError::Empty)) + } + + let mut first_is_field_sep = false; + let mut char_count: usize = 0; + let mut last_c = FIELD_SEP; + let mut num_conscutive_field_seps = 0; + + let mut field = String::new(); + let mut fields = self.0.clone(); + + let push_field = |fs: &mut Vec, f: &mut String| { + if f.len() > 0 { + fs.push(f.clone()); + f.truncate(0); + } + }; + + for (cid, c) in value.chars().enumerate() { + char_count += 1; + + if c == FIELD_SEP { + if cid == 0 { + first_is_field_sep = true; + } + num_conscutive_field_seps += 1; + if cid > 0 && last_c == FIELD_SEP { + if fields.pop().is_none() { + return Err(CLIError::Field(FieldError::PopOnEmpty(value.to_string()))) + } + } else { + push_field(&mut fields, &mut field); + } + } else { + num_conscutive_field_seps = 0; + if cid == 1 { + if first_is_field_sep { + fields.truncate(0); + } + } + field.push(c); + } + + last_c = c; + } + + push_field(&mut fields, &mut field); + + if char_count == 1 && first_is_field_sep { + fields.truncate(0); + } + if char_count > 1 && num_conscutive_field_seps == 1 { + return Err(CLIError::Field(FieldError::TrailingFieldSep(value.to_string()))) + } + + self.0 = fields; + Ok(()) + } + + pub fn did_you_mean(value: &str, possible_values: &[&str]) -> Option { + if value.len() == 0 { + return None + } + + let mut last_c = FIELD_SEP; + + let mut field = String::new(); + let mut output = String::new(); + + let push_field = |fs: &mut String, f: &mut String| { + if f.len() > 0 { + fs.push_str( + match did_you_mean(&f, possible_values) { + Some(candidate) => candidate, + None => &f, + }); + f.truncate(0); + } + }; + + for (cid, c) in value.chars().enumerate() { + if c == FIELD_SEP { + if last_c != FIELD_SEP { + push_field(&mut output, &mut field); + } + output.push(c); + } else { + field.push(c); + } + + last_c = c; + } + + push_field(&mut output, &mut field); + + if &output == value { + None + } else { + Some(output) + } + } + + pub fn set_json_value(&self, mut object: &mut Value, + value: &str, type_info: JsonTypeInfo, + err: &mut InvalidOptionsError, + orig_cursor: &FieldCursor) { + assert!(self.0.len() > 0); + + for field in &self.0[..self.0.len()-1] { + let tmp = object; + object = + match *tmp { + Value::Object(ref mut mapping) => { + mapping.entry(field.to_owned()).or_insert( + Value::Object(Default::default()) + ) + }, + _ => panic!("We don't expect non-object Values here ...") + }; + } + + match *object { + Value::Object(ref mut mapping) => { + let field = &self.0[self.0.len()-1]; + let to_jval = + |value: &str, jtype: JsonType, err: &mut InvalidOptionsError| + -> Value { + match jtype { + JsonType::Boolean => + Value::Bool(arg_from_str(value, err, &field, "boolean")), + JsonType::Int => + Value::I64(arg_from_str(value, err, &field, "int")), + JsonType::Uint => + Value::U64(arg_from_str(value, err, &field, "uint")), + JsonType::Float => + Value::F64(arg_from_str(value, err, &field, "float")), + JsonType::String => + Value::String(value.to_owned()), + } + }; + + match type_info.ctype { + ComplexType::Pod => { + if mapping.insert(field.to_owned(), to_jval(value, type_info.jtype, err)).is_some() { + err.issues.push(CLIError::Field(FieldError::Duplicate(orig_cursor.to_string()))); + } + }, + ComplexType::Vec => { + match *mapping.entry(field.to_owned()) + .or_insert(Value::Array(Default::default())) { + Value::Array(ref mut values) => values.push(to_jval(value, type_info.jtype, err)), + _ => unreachable!() + } + }, + ComplexType::Map => { + let (key, value) = parse_kv_arg(value, err, true); + let jval = to_jval(value.unwrap_or(""), type_info.jtype, err); + + match *mapping.entry(field.to_owned()) + .or_insert(Value::Object(Default::default())) { + Value::Object(ref mut value_map) => { + if value_map.insert(key.to_owned(), jval).is_some() { + err.issues.push(CLIError::Field(FieldError::Duplicate(orig_cursor.to_string()))); + } + } + _ => unreachable!() + } + } + } + }, + _ => unreachable!() + } + } + + pub fn num_fields(&self) -> usize { + self.0.len() + } +} + +pub fn parse_kv_arg<'a>(kv: &'a str, err: &mut InvalidOptionsError, for_hashmap: bool) + -> (&'a str, Option<&'a str>) { + let mut add_err = || err.issues.push(CLIError::InvalidKeyValueSyntax(kv.to_string(),for_hashmap)); + match kv.find('=') { + None => { + add_err(); + return (kv, None) + }, + Some(pos) => { + let key = &kv[..pos]; + if kv.len() <= pos + 1 { + add_err(); + return (key, Some("")) + } + (key, Some(&kv[pos+1..])) + } + } +} + +pub fn calltype_from_str(name: &str, valid_protocols: Vec, err: &mut InvalidOptionsError) -> CallType { + CallType::Upload( + match UploadProtocol::from_str(name) { + Ok(up) => up, + Err(msg) => { + err.issues.push(CLIError::InvalidUploadProtocol(name.to_string(), valid_protocols)); + UploadProtocol::Simple + } + }) +} + +pub fn input_file_from_opts(file_path: &str, err: &mut InvalidOptionsError) -> Option { + match fs::File::open(file_path) { + Ok(f) => Some(f), + Err(io_err) => { + err.issues.push(CLIError::Input(InputError::IOError((file_path.to_string(), io_err)))); + None + } + } +} + +pub fn input_mime_from_opts(mime: &str, err: &mut InvalidOptionsError) -> Option { + match mime.parse() { + Ok(m) => Some(m), + Err(_) => { + err.issues.push(CLIError::Input(InputError::Mime(mime.to_string()))); + None + } + } +} + +pub fn writer_from_opts(arg: Option<&str>) -> Result, io::Error> { + let f = arg.unwrap_or("-"); + match f { + "-" => Ok(Box::new(stdout())), + _ => match fs::OpenOptions::new().create(true).write(true).open(f) { + Ok(f) => Ok(Box::new(f)), + Err(io_err) => Err(io_err), + } + } +} + + +pub fn arg_from_str<'a, T>(arg: &str, err: &mut InvalidOptionsError, + arg_name: &'a str, + arg_type: &'a str) -> T + where T: FromStr + Default, + ::Err: fmt::Display { + match FromStr::from_str(arg) { + Err(perr) => { + err.issues.push( + CLIError::ParseError(arg_name.to_owned(), arg_type.to_owned(), arg.to_string(), format!("{}", perr)) + ); + Default::default() + }, + Ok(v) => v, + } +} + +pub struct JsonTokenStorage { + pub program_name: &'static str, + pub db_dir: String, +} + +impl JsonTokenStorage { + fn path(&self, scope_hash: u64) -> PathBuf { + Path::new(&self.db_dir).join(&format!("{}-token-{}.json", self.program_name, scope_hash)) + } +} + +impl TokenStorage for JsonTokenStorage { + type Error = json::Error; + + // NOTE: logging might be interesting, currently we swallow all errors + fn set(&mut self, scope_hash: u64, _: &Vec<&str>, token: Option) -> Result<(), json::Error> { + match token { + None => { + match fs::remove_file(self.path(scope_hash)) { + Err(err) => + match err.kind() { + io::ErrorKind::NotFound => Ok(()), + _ => Err(json::Error::IoError(err)) + }, + Ok(_) => Ok(()), + } + } + Some(token) => { + match fs::OpenOptions::new().create(true).write(true).open(&self.path(scope_hash)) { + Ok(mut f) => { + match json::to_writer_pretty(&mut f, &token) { + Ok(_) => Ok(()), + Err(serde_err) => Err(serde_err), + } + }, + Err(io_err) => Err(json::Error::IoError(io_err)) + } + } + } + } + + fn get(&self, scope_hash: u64, _: &Vec<&str>) -> Result, json::Error> { + match fs::File::open(&self.path(scope_hash)) { + Ok(mut f) => { + match json::de::from_reader(f) { + Ok(token) => Ok(Some(token)), + Err(err) => Err(err), + } + }, + Err(io_err) => { + match io_err.kind() { + io::ErrorKind::NotFound => Ok(None), + _ => Err(json::Error::IoError(io_err)) + } + } + } + } +} + + +#[derive(Debug)] +pub enum ApplicationSecretError { + DecoderError((String, json::Error)), + FormatError(String), +} + +impl fmt::Display for ApplicationSecretError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + ApplicationSecretError::DecoderError((ref path, ref err)) + => writeln!(f, "Could not decode file at '{}' with error: {}.", + path, err), + ApplicationSecretError::FormatError(ref path) + => writeln!(f, "'installed' field is unset in secret file at '{}'.", + path), + } + } +} + +#[derive(Debug)] +pub enum ConfigurationError { + DirectoryCreationFailed((String, io::Error)), + DirectoryUnset, + HomeExpansionFailed(String), + Secret(ApplicationSecretError), + IOError((String, io::Error)), +} + +impl fmt::Display for ConfigurationError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + ConfigurationError::DirectoryCreationFailed((ref dir, ref err)) + => writeln!(f, "Directory '{}' could not be created with error: {}.", dir, err), + ConfigurationError::DirectoryUnset + => writeln!(f, "--config-dir was unset or empty."), + ConfigurationError::HomeExpansionFailed(ref dir) + => writeln!(f, "Couldn't find HOME directory of current user, failed to expand '{}'.", dir), + ConfigurationError::Secret(ref err) + => writeln!(f, "Secret -> {}", err), + ConfigurationError::IOError((ref path, ref err)) + => writeln!(f, "IO operation failed on path '{}' with error: {}.", path, err), + } + } +} + +#[derive(Debug)] +pub enum InputError { + IOError((String, io::Error)), + Mime(String), +} + +impl fmt::Display for InputError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + InputError::IOError((ref file_path, ref io_err)) + => writeln!(f, "Failed to open '{}' for reading with error: {}.", file_path, io_err), + InputError::Mime(ref mime) + => writeln!(f, "'{}' is not a known mime-type.", mime), + } + } +} + +#[derive(Debug)] +pub enum FieldError { + PopOnEmpty(String), + TrailingFieldSep(String), + Unknown(String, Option, Option), + Duplicate(String), + Empty, +} + + +impl fmt::Display for FieldError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + FieldError::PopOnEmpty(ref field) + => writeln!(f, "'{}': Cannot move up on empty field cursor.", field), + FieldError::TrailingFieldSep(ref field) + => writeln!(f, "'{}': Single field separator may not be last character.", field), + FieldError::Unknown(ref field, ref suggestion, ref value) => { + let suffix = + match *suggestion { + Some(ref s) => { + let kv = + match *value { + Some(ref v) => format!("{}={}", s, v), + None => s.clone(), + }; + format!(" Did you mean '{}' ?", kv) + }, + None => String::new(), + }; + writeln!(f, "Field '{}' does not exist.{}", field, suffix) + }, + FieldError::Duplicate(ref cursor) + => writeln!(f, "Value at '{}' was already set", cursor), + FieldError::Empty + => writeln!(f, "Field names must not be empty."), + } + } +} + + +#[derive(Debug)] +pub enum CLIError { + Configuration(ConfigurationError), + ParseError(String, String, String, String), + UnknownParameter(String, Vec<&'static str>), + InvalidUploadProtocol(String, Vec), + InvalidKeyValueSyntax(String, bool), + Input(InputError), + Field(FieldError), + MissingCommandError, + MissingMethodError(String), +} + +impl fmt::Display for CLIError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + CLIError::Configuration(ref err) => write!(f, "Configuration -> {}", err), + CLIError::Input(ref err) => write!(f, "Input -> {}", err), + CLIError::Field(ref err) => write!(f, "Field -> {}", err), + CLIError::InvalidUploadProtocol(ref proto_name, ref valid_names) + => writeln!(f, "'{}' is not a valid upload protocol. Choose from one of {}.", proto_name, valid_names.join(", ")), + CLIError::ParseError(ref arg_name, ref type_name, ref value, ref err_desc) + => writeln!(f, "Failed to parse argument '{}' with value '{}' as {} with error: {}.", + arg_name, value, type_name, err_desc), + CLIError::UnknownParameter(ref param_name, ref possible_values) => { + let mut suffix = + match did_you_mean(param_name, &possible_values) { + Some(v) => format!(" Did you mean '{}' ?", v), + None => String::new(), + }; + write!(f, "Parameter '{}' is unknown.{}\n", param_name, suffix) + }, + CLIError::InvalidKeyValueSyntax(ref kv, is_hashmap) => { + let hashmap_info = if is_hashmap { "hashmap " } else { "" }; + writeln!(f, "'{}' does not match {}pattern =.", kv, hashmap_info) + }, + CLIError::MissingCommandError => writeln!(f, "Please specify the main sub-command."), + CLIError::MissingMethodError(ref cmd) => writeln!(f, "Please specify the method to call on the '{}' command.", cmd), + } + } +} + +#[derive(Debug)] +pub struct InvalidOptionsError { + pub issues: Vec, + pub exit_code: i32, +} + +impl fmt::Display for InvalidOptionsError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + for issue in &self.issues { + try!(issue.fmt(f)); + } + Ok(()) + } +} + +impl InvalidOptionsError { + pub fn single(err: CLIError, exit_code: i32) -> InvalidOptionsError { + InvalidOptionsError { + issues: vec![err], + exit_code: exit_code, + } + } + + pub fn new() -> InvalidOptionsError { + InvalidOptionsError { + issues: Vec::new(), + exit_code: 1, + } + } +} + +pub fn assure_config_dir_exists(dir: &str) -> Result { + let trdir = dir.trim(); + if trdir.len() == 0 { + return Err(CLIError::Configuration(ConfigurationError::DirectoryUnset)) + } + + let expanded_config_dir = + if trdir.as_bytes()[0] == b'~' { + match env::var("HOME").ok().or(env::var("UserProfile").ok()) { + None => return Err(CLIError::Configuration(ConfigurationError::HomeExpansionFailed(trdir.to_string()))), + Some(mut user) => { + user.push_str(&trdir[1..]); + user + } + } + } else { + trdir.to_string() + }; + + if let Err(err) = fs::create_dir(&expanded_config_dir) { + if err.kind() != io::ErrorKind::AlreadyExists { + return Err(CLIError::Configuration( + ConfigurationError::DirectoryCreationFailed((expanded_config_dir, err)))) + } + } + + Ok(expanded_config_dir) +} + +pub fn application_secret_from_directory(dir: &str, + secret_basename: &str, + json_console_secret: &str) + -> Result { + let secret_path = Path::new(dir).join(secret_basename); + let secret_str = || secret_path.as_path().to_str().unwrap().to_string(); + let secret_io_error = |io_err: io::Error| { + Err(CLIError::Configuration(ConfigurationError::IOError( + (secret_str(), io_err) + ))) + }; + + for _ in 0..2 { + match fs::File::open(&secret_path) { + Err(mut err) => { + if err.kind() == io::ErrorKind::NotFound { + // Write our built-in one - user may adjust the written file at will + + err = match fs::OpenOptions::new().create(true).write(true).open(&secret_path) { + Err(cfe) => cfe, + Ok(mut f) => { + // Assure we convert 'ugly' json string into pretty one + let console_secret: ConsoleApplicationSecret + = json::from_str(json_console_secret).unwrap(); + match json::to_writer_pretty(&mut f, &console_secret) { + Err(serde_err) => match serde_err { + json::Error::IoError(err) => err, + _ => panic!("Unexpected serde error: {:#?}", serde_err) + }, + Ok(_) => continue, + } + } + }; + // fall through to IO error handling + } + return secret_io_error(err) + }, + Ok(mut f) => { + match json::de::from_reader::<_, ConsoleApplicationSecret>(f) { + Err(json::Error::IoError(err)) => + return secret_io_error(err), + Err(json_err) => + return Err(CLIError::Configuration( + ConfigurationError::Secret( + ApplicationSecretError::DecoderError( + (secret_str(), json_err) + )))), + Ok(console_secret) => + match console_secret.installed { + Some(secret) => return Ok(secret), + None => return Err( + CLIError::Configuration( + ConfigurationError::Secret( + ApplicationSecretError::FormatError(secret_str()) + ))) + }, + } + } + } + } + unreachable!(); +} diff --git a/gen/dfareporting2d2-cli/src/main.rs b/gen/dfareporting2d2-cli/src/main.rs new file mode 100644 index 0000000000..196cb4c69c --- /dev/null +++ b/gen/dfareporting2d2-cli/src/main.rs @@ -0,0 +1,22441 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/cli/main.rs.mako' +// DO NOT EDIT ! +#![allow(unused_variables, unused_imports, dead_code, unused_mut)] + +#[macro_use] +extern crate clap; +extern crate yup_oauth2 as oauth2; +extern crate yup_hyper_mock as mock; +extern crate serde; +extern crate serde_json; +extern crate hyper; +extern crate mime; +extern crate strsim; +extern crate google_dfareporting2d2 as api; + +use std::env; +use std::io::{self, Write}; +use clap::{App, SubCommand, Arg}; + +mod cmn; + +use cmn::{InvalidOptionsError, CLIError, JsonTokenStorage, arg_from_str, writer_from_opts, parse_kv_arg, + input_file_from_opts, input_mime_from_opts, FieldCursor, FieldError, CallType, UploadProtocol, + calltype_from_str, remove_json_null_values, ComplexType, JsonType, JsonTypeInfo}; + +use std::default::Default; +use std::str::FromStr; + +use oauth2::{Authenticator, DefaultAuthenticatorDelegate}; +use serde_json as json; +use clap::ArgMatches; + +enum DoitError { + IoError(String, io::Error), + ApiError(api::Error), +} + +struct Engine<'n, 'a> { + opt: ArgMatches<'n, 'a>, + hub: api::Dfareporting>, + gp: Vec<&'static str>, + gpm: Vec<(&'static str, &'static str)>, +} + + +impl<'n, 'a> Engine<'n, 'a> { + fn _account_active_ad_summaries_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.account_active_ad_summaries().get(opt.value_of("profile-id").unwrap_or(""), opt.value_of("summary-account-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _account_permission_groups_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.account_permission_groups().get(opt.value_of("profile-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _account_permission_groups_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.account_permission_groups().list(opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _account_permissions_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.account_permissions().get(opt.value_of("profile-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _account_permissions_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.account_permissions().list(opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _account_user_profiles_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.account_user_profiles().get(opt.value_of("profile-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _account_user_profiles_insert(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "subaccount-id" => Some(("subaccountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "user-role-filter.object-ids" => Some(("userRoleFilter.objectIds", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "user-role-filter.status" => Some(("userRoleFilter.status", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "user-role-filter.kind" => Some(("userRoleFilter.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "locale" => Some(("locale", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "site-filter.object-ids" => Some(("siteFilter.objectIds", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "site-filter.status" => Some(("siteFilter.status", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "site-filter.kind" => Some(("siteFilter.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "comments" => Some(("comments", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "trafficker-type" => Some(("traffickerType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-filter.object-ids" => Some(("advertiserFilter.objectIds", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "advertiser-filter.status" => Some(("advertiserFilter.status", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-filter.kind" => Some(("advertiserFilter.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-filter.object-ids" => Some(("campaignFilter.objectIds", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "campaign-filter.status" => Some(("campaignFilter.status", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-filter.kind" => Some(("campaignFilter.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "email" => Some(("email", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "user-role-id" => Some(("userRoleId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "user-access-type" => Some(("userAccessType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "active" => Some(("active", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "active", "advertiser-filter", "campaign-filter", "comments", "email", "id", "kind", "locale", "name", "object-ids", "site-filter", "status", "subaccount-id", "trafficker-type", "user-access-type", "user-role-filter", "user-role-id"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::AccountUserProfile = json::value::from_value(object).unwrap(); + let mut call = self.hub.account_user_profiles().insert(request, opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _account_user_profiles_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.account_user_profiles().list(opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "user-role-id" => { + call = call.user_role_id(value.unwrap_or("")); + }, + "subaccount-id" => { + call = call.subaccount_id(value.unwrap_or("")); + }, + "sort-order" => { + call = call.sort_order(value.unwrap_or("")); + }, + "sort-field" => { + call = call.sort_field(value.unwrap_or("")); + }, + "search-string" => { + call = call.search_string(value.unwrap_or("")); + }, + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "max-results" => { + call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer")); + }, + "ids" => { + call = call.add_ids(value.unwrap_or("")); + }, + "active" => { + call = call.active(arg_from_str(value.unwrap_or("false"), err, "active", "boolean")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["search-string", "subaccount-id", "sort-field", "ids", "max-results", "page-token", "user-role-id", "sort-order", "active"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _account_user_profiles_patch(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "subaccount-id" => Some(("subaccountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "user-role-filter.object-ids" => Some(("userRoleFilter.objectIds", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "user-role-filter.status" => Some(("userRoleFilter.status", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "user-role-filter.kind" => Some(("userRoleFilter.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "locale" => Some(("locale", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "site-filter.object-ids" => Some(("siteFilter.objectIds", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "site-filter.status" => Some(("siteFilter.status", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "site-filter.kind" => Some(("siteFilter.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "comments" => Some(("comments", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "trafficker-type" => Some(("traffickerType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-filter.object-ids" => Some(("advertiserFilter.objectIds", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "advertiser-filter.status" => Some(("advertiserFilter.status", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-filter.kind" => Some(("advertiserFilter.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-filter.object-ids" => Some(("campaignFilter.objectIds", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "campaign-filter.status" => Some(("campaignFilter.status", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-filter.kind" => Some(("campaignFilter.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "email" => Some(("email", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "user-role-id" => Some(("userRoleId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "user-access-type" => Some(("userAccessType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "active" => Some(("active", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "active", "advertiser-filter", "campaign-filter", "comments", "email", "id", "kind", "locale", "name", "object-ids", "site-filter", "status", "subaccount-id", "trafficker-type", "user-access-type", "user-role-filter", "user-role-id"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::AccountUserProfile = json::value::from_value(object).unwrap(); + let mut call = self.hub.account_user_profiles().patch(request, opt.value_of("profile-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _account_user_profiles_update(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "subaccount-id" => Some(("subaccountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "user-role-filter.object-ids" => Some(("userRoleFilter.objectIds", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "user-role-filter.status" => Some(("userRoleFilter.status", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "user-role-filter.kind" => Some(("userRoleFilter.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "locale" => Some(("locale", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "site-filter.object-ids" => Some(("siteFilter.objectIds", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "site-filter.status" => Some(("siteFilter.status", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "site-filter.kind" => Some(("siteFilter.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "comments" => Some(("comments", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "trafficker-type" => Some(("traffickerType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-filter.object-ids" => Some(("advertiserFilter.objectIds", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "advertiser-filter.status" => Some(("advertiserFilter.status", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-filter.kind" => Some(("advertiserFilter.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-filter.object-ids" => Some(("campaignFilter.objectIds", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "campaign-filter.status" => Some(("campaignFilter.status", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-filter.kind" => Some(("campaignFilter.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "email" => Some(("email", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "user-role-id" => Some(("userRoleId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "user-access-type" => Some(("userAccessType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "active" => Some(("active", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "active", "advertiser-filter", "campaign-filter", "comments", "email", "id", "kind", "locale", "name", "object-ids", "site-filter", "status", "subaccount-id", "trafficker-type", "user-access-type", "user-role-filter", "user-role-id"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::AccountUserProfile = json::value::from_value(object).unwrap(); + let mut call = self.hub.account_user_profiles().update(request, opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _accounts_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.accounts().get(opt.value_of("profile-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _accounts_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.accounts().list(opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "sort-order" => { + call = call.sort_order(value.unwrap_or("")); + }, + "sort-field" => { + call = call.sort_field(value.unwrap_or("")); + }, + "search-string" => { + call = call.search_string(value.unwrap_or("")); + }, + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "max-results" => { + call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer")); + }, + "ids" => { + call = call.add_ids(value.unwrap_or("")); + }, + "active" => { + call = call.active(arg_from_str(value.unwrap_or("false"), err, "active", "boolean")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["search-string", "sort-field", "ids", "max-results", "page-token", "sort-order", "active"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _accounts_patch(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "teaser-size-limit" => Some(("teaserSizeLimit", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "active-view-opt-out" => Some(("activeViewOptOut", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "description" => Some(("description", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "maximum-image-size" => Some(("maximumImageSize", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "locale" => Some(("locale", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "default-creative-size-id" => Some(("defaultCreativeSizeId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "account-permission-ids" => Some(("accountPermissionIds", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "account-profile" => Some(("accountProfile", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "nielsen-ocr-enabled" => Some(("nielsenOcrEnabled", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "reports-configuration.report-generation-time-zone-id" => Some(("reportsConfiguration.reportGenerationTimeZoneId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "reports-configuration.exposure-to-conversion-enabled" => Some(("reportsConfiguration.exposureToConversionEnabled", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "reports-configuration.lookback-configuration.click-duration" => Some(("reportsConfiguration.lookbackConfiguration.clickDuration", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "reports-configuration.lookback-configuration.post-impression-activities-duration" => Some(("reportsConfiguration.lookbackConfiguration.postImpressionActivitiesDuration", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "currency-id" => Some(("currencyId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "active" => Some(("active", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "comscore-vce-enabled" => Some(("comscoreVceEnabled", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "active-ads-limit-tier" => Some(("activeAdsLimitTier", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "country-id" => Some(("countryId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "available-permission-ids" => Some(("availablePermissionIds", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-permission-ids", "account-profile", "active", "active-ads-limit-tier", "active-view-opt-out", "available-permission-ids", "click-duration", "comscore-vce-enabled", "country-id", "currency-id", "default-creative-size-id", "description", "exposure-to-conversion-enabled", "id", "kind", "locale", "lookback-configuration", "maximum-image-size", "name", "nielsen-ocr-enabled", "post-impression-activities-duration", "report-generation-time-zone-id", "reports-configuration", "teaser-size-limit"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::Account = json::value::from_value(object).unwrap(); + let mut call = self.hub.accounts().patch(request, opt.value_of("profile-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _accounts_update(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "teaser-size-limit" => Some(("teaserSizeLimit", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "active-view-opt-out" => Some(("activeViewOptOut", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "description" => Some(("description", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "maximum-image-size" => Some(("maximumImageSize", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "locale" => Some(("locale", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "default-creative-size-id" => Some(("defaultCreativeSizeId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "account-permission-ids" => Some(("accountPermissionIds", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "account-profile" => Some(("accountProfile", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "nielsen-ocr-enabled" => Some(("nielsenOcrEnabled", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "reports-configuration.report-generation-time-zone-id" => Some(("reportsConfiguration.reportGenerationTimeZoneId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "reports-configuration.exposure-to-conversion-enabled" => Some(("reportsConfiguration.exposureToConversionEnabled", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "reports-configuration.lookback-configuration.click-duration" => Some(("reportsConfiguration.lookbackConfiguration.clickDuration", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "reports-configuration.lookback-configuration.post-impression-activities-duration" => Some(("reportsConfiguration.lookbackConfiguration.postImpressionActivitiesDuration", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "currency-id" => Some(("currencyId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "active" => Some(("active", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "comscore-vce-enabled" => Some(("comscoreVceEnabled", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "active-ads-limit-tier" => Some(("activeAdsLimitTier", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "country-id" => Some(("countryId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "available-permission-ids" => Some(("availablePermissionIds", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-permission-ids", "account-profile", "active", "active-ads-limit-tier", "active-view-opt-out", "available-permission-ids", "click-duration", "comscore-vce-enabled", "country-id", "currency-id", "default-creative-size-id", "description", "exposure-to-conversion-enabled", "id", "kind", "locale", "lookback-configuration", "maximum-image-size", "name", "nielsen-ocr-enabled", "post-impression-activities-duration", "report-generation-time-zone-id", "reports-configuration", "teaser-size-limit"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::Account = json::value::from_value(object).unwrap(); + let mut call = self.hub.accounts().update(request, opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _ads_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.ads().get(opt.value_of("profile-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _ads_insert(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "click-through-url-suffix-properties.click-through-url-suffix" => Some(("clickThroughUrlSuffixProperties.clickThroughUrlSuffix", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "click-through-url-suffix-properties.override-inherited-suffix" => Some(("clickThroughUrlSuffixProperties.overrideInheritedSuffix", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "campaign-id" => Some(("campaignId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id" => Some(("advertiserId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "geo-targeting.exclude-countries" => Some(("geoTargeting.excludeCountries", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "delivery-schedule.priority" => Some(("deliverySchedule.priority", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "delivery-schedule.hard-cutoff" => Some(("deliverySchedule.hardCutoff", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "delivery-schedule.frequency-cap.duration" => Some(("deliverySchedule.frequencyCap.duration", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "delivery-schedule.frequency-cap.impressions" => Some(("deliverySchedule.frequencyCap.impressions", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "delivery-schedule.impression-ratio" => Some(("deliverySchedule.impressionRatio", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.kind" => Some(("advertiserIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.value" => Some(("advertiserIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.dimension-name" => Some(("advertiserIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.etag" => Some(("advertiserIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.match-type" => Some(("advertiserIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.id" => Some(("advertiserIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "archived" => Some(("archived", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "creative-rotation.weight-calculation-strategy" => Some(("creativeRotation.weightCalculationStrategy", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "creative-rotation.creative-optimization-configuration-id" => Some(("creativeRotation.creativeOptimizationConfigurationId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "creative-rotation.type" => Some(("creativeRotation.type", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "click-through-url.computed-click-through-url" => Some(("clickThroughUrl.computedClickThroughUrl", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "click-through-url.custom-click-through-url" => Some(("clickThroughUrl.customClickThroughUrl", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "click-through-url.landing-page-id" => Some(("clickThroughUrl.landingPageId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "click-through-url.default-landing-page" => Some(("clickThroughUrl.defaultLandingPage", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "comments" => Some(("comments", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "remarketing-list-expression.expression" => Some(("remarketingListExpression.expression", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.kind" => Some(("idDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.value" => Some(("idDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.dimension-name" => Some(("idDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.etag" => Some(("idDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.match-type" => Some(("idDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.id" => Some(("idDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "size.width" => Some(("size.width", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "size.kind" => Some(("size.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "size.iab" => Some(("size.iab", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "size.id" => Some(("size.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "size.height" => Some(("size.height", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "type" => Some(("type", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "ssl-required" => Some(("sslRequired", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "audience-segment-id" => Some(("audienceSegmentId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "key-value-targeting-expression.expression" => Some(("keyValueTargetingExpression.expression", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.kind" => Some(("campaignIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.value" => Some(("campaignIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.dimension-name" => Some(("campaignIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.etag" => Some(("campaignIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.match-type" => Some(("campaignIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.id" => Some(("campaignIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "default-click-through-event-tag-properties.override-inherited-event-tag" => Some(("defaultClickThroughEventTagProperties.overrideInheritedEventTag", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "default-click-through-event-tag-properties.default-click-through-event-tag-id" => Some(("defaultClickThroughEventTagProperties.defaultClickThroughEventTagId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "create-info.time" => Some(("createInfo.time", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "start-time" => Some(("startTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "active" => Some(("active", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "compatibility" => Some(("compatibility", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "subaccount-id" => Some(("subaccountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "day-part-targeting.user-local-time" => Some(("dayPartTargeting.userLocalTime", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "day-part-targeting.hours-of-day" => Some(("dayPartTargeting.hoursOfDay", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Vec })), + "day-part-targeting.days-of-week" => Some(("dayPartTargeting.daysOfWeek", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "last-modified-info.time" => Some(("lastModifiedInfo.time", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "ssl-compliant" => Some(("sslCompliant", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "end-time" => Some(("endTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "dynamic-click-tracker" => Some(("dynamicClickTracker", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "active", "advertiser-id", "advertiser-id-dimension-value", "archived", "audience-segment-id", "campaign-id", "campaign-id-dimension-value", "click-through-url", "click-through-url-suffix", "click-through-url-suffix-properties", "comments", "compatibility", "computed-click-through-url", "create-info", "creative-optimization-configuration-id", "creative-rotation", "custom-click-through-url", "day-part-targeting", "days-of-week", "default-click-through-event-tag-id", "default-click-through-event-tag-properties", "default-landing-page", "delivery-schedule", "dimension-name", "duration", "dynamic-click-tracker", "end-time", "etag", "exclude-countries", "expression", "frequency-cap", "geo-targeting", "hard-cutoff", "height", "hours-of-day", "iab", "id", "id-dimension-value", "impression-ratio", "impressions", "key-value-targeting-expression", "kind", "landing-page-id", "last-modified-info", "match-type", "name", "override-inherited-event-tag", "override-inherited-suffix", "priority", "remarketing-list-expression", "size", "ssl-compliant", "ssl-required", "start-time", "subaccount-id", "time", "type", "user-local-time", "value", "weight-calculation-strategy", "width"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::Ad = json::value::from_value(object).unwrap(); + let mut call = self.hub.ads().insert(request, opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _ads_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.ads().list(opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "type" => { + call = call.add_type(value.unwrap_or("")); + }, + "ssl-required" => { + call = call.ssl_required(arg_from_str(value.unwrap_or("false"), err, "ssl-required", "boolean")); + }, + "ssl-compliant" => { + call = call.ssl_compliant(arg_from_str(value.unwrap_or("false"), err, "ssl-compliant", "boolean")); + }, + "sort-order" => { + call = call.sort_order(value.unwrap_or("")); + }, + "sort-field" => { + call = call.sort_field(value.unwrap_or("")); + }, + "size-ids" => { + call = call.add_size_ids(value.unwrap_or("")); + }, + "search-string" => { + call = call.search_string(value.unwrap_or("")); + }, + "remarketing-list-ids" => { + call = call.add_remarketing_list_ids(value.unwrap_or("")); + }, + "placement-ids" => { + call = call.add_placement_ids(value.unwrap_or("")); + }, + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "overridden-event-tag-id" => { + call = call.overridden_event_tag_id(value.unwrap_or("")); + }, + "max-results" => { + call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer")); + }, + "landing-page-ids" => { + call = call.add_landing_page_ids(value.unwrap_or("")); + }, + "ids" => { + call = call.add_ids(value.unwrap_or("")); + }, + "dynamic-click-tracker" => { + call = call.dynamic_click_tracker(arg_from_str(value.unwrap_or("false"), err, "dynamic-click-tracker", "boolean")); + }, + "creative-type" => { + call = call.creative_type(value.unwrap_or("")); + }, + "creative-optimization-configuration-ids" => { + call = call.add_creative_optimization_configuration_ids(value.unwrap_or("")); + }, + "creative-ids" => { + call = call.add_creative_ids(value.unwrap_or("")); + }, + "compatibility" => { + call = call.compatibility(value.unwrap_or("")); + }, + "campaign-ids" => { + call = call.add_campaign_ids(value.unwrap_or("")); + }, + "audience-segment-ids" => { + call = call.add_audience_segment_ids(value.unwrap_or("")); + }, + "archived" => { + call = call.archived(arg_from_str(value.unwrap_or("false"), err, "archived", "boolean")); + }, + "advertiser-id" => { + call = call.advertiser_id(value.unwrap_or("")); + }, + "active" => { + call = call.active(arg_from_str(value.unwrap_or("false"), err, "active", "boolean")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["landing-page-ids", "overridden-event-tag-id", "campaign-ids", "archived", "creative-optimization-configuration-ids", "ssl-compliant", "size-ids", "page-token", "sort-order", "type", "ssl-required", "creative-ids", "max-results", "creative-type", "placement-ids", "active", "compatibility", "advertiser-id", "search-string", "sort-field", "audience-segment-ids", "ids", "remarketing-list-ids", "dynamic-click-tracker"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _ads_patch(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "click-through-url-suffix-properties.click-through-url-suffix" => Some(("clickThroughUrlSuffixProperties.clickThroughUrlSuffix", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "click-through-url-suffix-properties.override-inherited-suffix" => Some(("clickThroughUrlSuffixProperties.overrideInheritedSuffix", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "campaign-id" => Some(("campaignId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id" => Some(("advertiserId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "geo-targeting.exclude-countries" => Some(("geoTargeting.excludeCountries", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "delivery-schedule.priority" => Some(("deliverySchedule.priority", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "delivery-schedule.hard-cutoff" => Some(("deliverySchedule.hardCutoff", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "delivery-schedule.frequency-cap.duration" => Some(("deliverySchedule.frequencyCap.duration", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "delivery-schedule.frequency-cap.impressions" => Some(("deliverySchedule.frequencyCap.impressions", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "delivery-schedule.impression-ratio" => Some(("deliverySchedule.impressionRatio", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.kind" => Some(("advertiserIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.value" => Some(("advertiserIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.dimension-name" => Some(("advertiserIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.etag" => Some(("advertiserIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.match-type" => Some(("advertiserIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.id" => Some(("advertiserIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "archived" => Some(("archived", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "creative-rotation.weight-calculation-strategy" => Some(("creativeRotation.weightCalculationStrategy", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "creative-rotation.creative-optimization-configuration-id" => Some(("creativeRotation.creativeOptimizationConfigurationId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "creative-rotation.type" => Some(("creativeRotation.type", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "click-through-url.computed-click-through-url" => Some(("clickThroughUrl.computedClickThroughUrl", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "click-through-url.custom-click-through-url" => Some(("clickThroughUrl.customClickThroughUrl", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "click-through-url.landing-page-id" => Some(("clickThroughUrl.landingPageId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "click-through-url.default-landing-page" => Some(("clickThroughUrl.defaultLandingPage", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "comments" => Some(("comments", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "remarketing-list-expression.expression" => Some(("remarketingListExpression.expression", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.kind" => Some(("idDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.value" => Some(("idDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.dimension-name" => Some(("idDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.etag" => Some(("idDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.match-type" => Some(("idDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.id" => Some(("idDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "size.width" => Some(("size.width", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "size.kind" => Some(("size.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "size.iab" => Some(("size.iab", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "size.id" => Some(("size.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "size.height" => Some(("size.height", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "type" => Some(("type", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "ssl-required" => Some(("sslRequired", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "audience-segment-id" => Some(("audienceSegmentId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "key-value-targeting-expression.expression" => Some(("keyValueTargetingExpression.expression", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.kind" => Some(("campaignIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.value" => Some(("campaignIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.dimension-name" => Some(("campaignIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.etag" => Some(("campaignIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.match-type" => Some(("campaignIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.id" => Some(("campaignIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "default-click-through-event-tag-properties.override-inherited-event-tag" => Some(("defaultClickThroughEventTagProperties.overrideInheritedEventTag", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "default-click-through-event-tag-properties.default-click-through-event-tag-id" => Some(("defaultClickThroughEventTagProperties.defaultClickThroughEventTagId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "create-info.time" => Some(("createInfo.time", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "start-time" => Some(("startTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "active" => Some(("active", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "compatibility" => Some(("compatibility", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "subaccount-id" => Some(("subaccountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "day-part-targeting.user-local-time" => Some(("dayPartTargeting.userLocalTime", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "day-part-targeting.hours-of-day" => Some(("dayPartTargeting.hoursOfDay", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Vec })), + "day-part-targeting.days-of-week" => Some(("dayPartTargeting.daysOfWeek", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "last-modified-info.time" => Some(("lastModifiedInfo.time", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "ssl-compliant" => Some(("sslCompliant", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "end-time" => Some(("endTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "dynamic-click-tracker" => Some(("dynamicClickTracker", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "active", "advertiser-id", "advertiser-id-dimension-value", "archived", "audience-segment-id", "campaign-id", "campaign-id-dimension-value", "click-through-url", "click-through-url-suffix", "click-through-url-suffix-properties", "comments", "compatibility", "computed-click-through-url", "create-info", "creative-optimization-configuration-id", "creative-rotation", "custom-click-through-url", "day-part-targeting", "days-of-week", "default-click-through-event-tag-id", "default-click-through-event-tag-properties", "default-landing-page", "delivery-schedule", "dimension-name", "duration", "dynamic-click-tracker", "end-time", "etag", "exclude-countries", "expression", "frequency-cap", "geo-targeting", "hard-cutoff", "height", "hours-of-day", "iab", "id", "id-dimension-value", "impression-ratio", "impressions", "key-value-targeting-expression", "kind", "landing-page-id", "last-modified-info", "match-type", "name", "override-inherited-event-tag", "override-inherited-suffix", "priority", "remarketing-list-expression", "size", "ssl-compliant", "ssl-required", "start-time", "subaccount-id", "time", "type", "user-local-time", "value", "weight-calculation-strategy", "width"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::Ad = json::value::from_value(object).unwrap(); + let mut call = self.hub.ads().patch(request, opt.value_of("profile-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _ads_update(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "click-through-url-suffix-properties.click-through-url-suffix" => Some(("clickThroughUrlSuffixProperties.clickThroughUrlSuffix", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "click-through-url-suffix-properties.override-inherited-suffix" => Some(("clickThroughUrlSuffixProperties.overrideInheritedSuffix", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "campaign-id" => Some(("campaignId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id" => Some(("advertiserId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "geo-targeting.exclude-countries" => Some(("geoTargeting.excludeCountries", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "delivery-schedule.priority" => Some(("deliverySchedule.priority", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "delivery-schedule.hard-cutoff" => Some(("deliverySchedule.hardCutoff", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "delivery-schedule.frequency-cap.duration" => Some(("deliverySchedule.frequencyCap.duration", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "delivery-schedule.frequency-cap.impressions" => Some(("deliverySchedule.frequencyCap.impressions", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "delivery-schedule.impression-ratio" => Some(("deliverySchedule.impressionRatio", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.kind" => Some(("advertiserIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.value" => Some(("advertiserIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.dimension-name" => Some(("advertiserIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.etag" => Some(("advertiserIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.match-type" => Some(("advertiserIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.id" => Some(("advertiserIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "archived" => Some(("archived", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "creative-rotation.weight-calculation-strategy" => Some(("creativeRotation.weightCalculationStrategy", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "creative-rotation.creative-optimization-configuration-id" => Some(("creativeRotation.creativeOptimizationConfigurationId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "creative-rotation.type" => Some(("creativeRotation.type", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "click-through-url.computed-click-through-url" => Some(("clickThroughUrl.computedClickThroughUrl", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "click-through-url.custom-click-through-url" => Some(("clickThroughUrl.customClickThroughUrl", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "click-through-url.landing-page-id" => Some(("clickThroughUrl.landingPageId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "click-through-url.default-landing-page" => Some(("clickThroughUrl.defaultLandingPage", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "comments" => Some(("comments", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "remarketing-list-expression.expression" => Some(("remarketingListExpression.expression", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.kind" => Some(("idDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.value" => Some(("idDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.dimension-name" => Some(("idDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.etag" => Some(("idDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.match-type" => Some(("idDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.id" => Some(("idDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "size.width" => Some(("size.width", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "size.kind" => Some(("size.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "size.iab" => Some(("size.iab", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "size.id" => Some(("size.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "size.height" => Some(("size.height", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "type" => Some(("type", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "ssl-required" => Some(("sslRequired", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "audience-segment-id" => Some(("audienceSegmentId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "key-value-targeting-expression.expression" => Some(("keyValueTargetingExpression.expression", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.kind" => Some(("campaignIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.value" => Some(("campaignIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.dimension-name" => Some(("campaignIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.etag" => Some(("campaignIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.match-type" => Some(("campaignIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.id" => Some(("campaignIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "default-click-through-event-tag-properties.override-inherited-event-tag" => Some(("defaultClickThroughEventTagProperties.overrideInheritedEventTag", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "default-click-through-event-tag-properties.default-click-through-event-tag-id" => Some(("defaultClickThroughEventTagProperties.defaultClickThroughEventTagId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "create-info.time" => Some(("createInfo.time", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "start-time" => Some(("startTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "active" => Some(("active", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "compatibility" => Some(("compatibility", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "subaccount-id" => Some(("subaccountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "day-part-targeting.user-local-time" => Some(("dayPartTargeting.userLocalTime", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "day-part-targeting.hours-of-day" => Some(("dayPartTargeting.hoursOfDay", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Vec })), + "day-part-targeting.days-of-week" => Some(("dayPartTargeting.daysOfWeek", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "last-modified-info.time" => Some(("lastModifiedInfo.time", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "ssl-compliant" => Some(("sslCompliant", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "end-time" => Some(("endTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "dynamic-click-tracker" => Some(("dynamicClickTracker", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "active", "advertiser-id", "advertiser-id-dimension-value", "archived", "audience-segment-id", "campaign-id", "campaign-id-dimension-value", "click-through-url", "click-through-url-suffix", "click-through-url-suffix-properties", "comments", "compatibility", "computed-click-through-url", "create-info", "creative-optimization-configuration-id", "creative-rotation", "custom-click-through-url", "day-part-targeting", "days-of-week", "default-click-through-event-tag-id", "default-click-through-event-tag-properties", "default-landing-page", "delivery-schedule", "dimension-name", "duration", "dynamic-click-tracker", "end-time", "etag", "exclude-countries", "expression", "frequency-cap", "geo-targeting", "hard-cutoff", "height", "hours-of-day", "iab", "id", "id-dimension-value", "impression-ratio", "impressions", "key-value-targeting-expression", "kind", "landing-page-id", "last-modified-info", "match-type", "name", "override-inherited-event-tag", "override-inherited-suffix", "priority", "remarketing-list-expression", "size", "ssl-compliant", "ssl-required", "start-time", "subaccount-id", "time", "type", "user-local-time", "value", "weight-calculation-strategy", "width"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::Ad = json::value::from_value(object).unwrap(); + let mut call = self.hub.ads().update(request, opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _advertiser_groups_delete(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.advertiser_groups().delete(opt.value_of("profile-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok(mut response) => { + Ok(()) + } + } + } + } + + fn _advertiser_groups_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.advertiser_groups().get(opt.value_of("profile-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _advertiser_groups_insert(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "id", "kind", "name"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::AdvertiserGroup = json::value::from_value(object).unwrap(); + let mut call = self.hub.advertiser_groups().insert(request, opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _advertiser_groups_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.advertiser_groups().list(opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "sort-order" => { + call = call.sort_order(value.unwrap_or("")); + }, + "sort-field" => { + call = call.sort_field(value.unwrap_or("")); + }, + "search-string" => { + call = call.search_string(value.unwrap_or("")); + }, + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "max-results" => { + call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer")); + }, + "ids" => { + call = call.add_ids(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["search-string", "sort-field", "ids", "max-results", "page-token", "sort-order"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _advertiser_groups_patch(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "id", "kind", "name"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::AdvertiserGroup = json::value::from_value(object).unwrap(); + let mut call = self.hub.advertiser_groups().patch(request, opt.value_of("profile-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _advertiser_groups_update(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "id", "kind", "name"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::AdvertiserGroup = json::value::from_value(object).unwrap(); + let mut call = self.hub.advertiser_groups().update(request, opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _advertisers_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.advertisers().get(opt.value_of("profile-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _advertisers_insert(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "status" => Some(("status", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "subaccount-id" => Some(("subaccountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "default-click-through-event-tag-id" => Some(("defaultClickThroughEventTagId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "original-floodlight-configuration-id" => Some(("originalFloodlightConfigurationId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "click-through-url-suffix" => Some(("clickThroughUrlSuffix", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-configuration-id" => Some(("floodlightConfigurationId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "suspended" => Some(("suspended", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "floodlight-configuration-id-dimension-value.kind" => Some(("floodlightConfigurationIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-configuration-id-dimension-value.value" => Some(("floodlightConfigurationIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-configuration-id-dimension-value.dimension-name" => Some(("floodlightConfigurationIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-configuration-id-dimension-value.etag" => Some(("floodlightConfigurationIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-configuration-id-dimension-value.match-type" => Some(("floodlightConfigurationIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-configuration-id-dimension-value.id" => Some(("floodlightConfigurationIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-group-id" => Some(("advertiserGroupId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.kind" => Some(("idDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.value" => Some(("idDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.dimension-name" => Some(("idDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.etag" => Some(("idDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.match-type" => Some(("idDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.id" => Some(("idDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "default-email" => Some(("defaultEmail", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "advertiser-group-id", "click-through-url-suffix", "default-click-through-event-tag-id", "default-email", "dimension-name", "etag", "floodlight-configuration-id", "floodlight-configuration-id-dimension-value", "id", "id-dimension-value", "kind", "match-type", "name", "original-floodlight-configuration-id", "status", "subaccount-id", "suspended", "value"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::Advertiser = json::value::from_value(object).unwrap(); + let mut call = self.hub.advertisers().insert(request, opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _advertisers_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.advertisers().list(opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "subaccount-id" => { + call = call.subaccount_id(value.unwrap_or("")); + }, + "status" => { + call = call.status(value.unwrap_or("")); + }, + "sort-order" => { + call = call.sort_order(value.unwrap_or("")); + }, + "sort-field" => { + call = call.sort_field(value.unwrap_or("")); + }, + "search-string" => { + call = call.search_string(value.unwrap_or("")); + }, + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "only-parent" => { + call = call.only_parent(arg_from_str(value.unwrap_or("false"), err, "only-parent", "boolean")); + }, + "max-results" => { + call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer")); + }, + "include-advertisers-without-groups-only" => { + call = call.include_advertisers_without_groups_only(arg_from_str(value.unwrap_or("false"), err, "include-advertisers-without-groups-only", "boolean")); + }, + "ids" => { + call = call.add_ids(value.unwrap_or("")); + }, + "floodlight-configuration-ids" => { + call = call.add_floodlight_configuration_ids(value.unwrap_or("")); + }, + "advertiser-group-ids" => { + call = call.add_advertiser_group_ids(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["status", "search-string", "subaccount-id", "include-advertisers-without-groups-only", "sort-field", "ids", "max-results", "page-token", "only-parent", "sort-order", "floodlight-configuration-ids", "advertiser-group-ids"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _advertisers_patch(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "status" => Some(("status", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "subaccount-id" => Some(("subaccountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "default-click-through-event-tag-id" => Some(("defaultClickThroughEventTagId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "original-floodlight-configuration-id" => Some(("originalFloodlightConfigurationId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "click-through-url-suffix" => Some(("clickThroughUrlSuffix", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-configuration-id" => Some(("floodlightConfigurationId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "suspended" => Some(("suspended", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "floodlight-configuration-id-dimension-value.kind" => Some(("floodlightConfigurationIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-configuration-id-dimension-value.value" => Some(("floodlightConfigurationIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-configuration-id-dimension-value.dimension-name" => Some(("floodlightConfigurationIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-configuration-id-dimension-value.etag" => Some(("floodlightConfigurationIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-configuration-id-dimension-value.match-type" => Some(("floodlightConfigurationIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-configuration-id-dimension-value.id" => Some(("floodlightConfigurationIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-group-id" => Some(("advertiserGroupId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.kind" => Some(("idDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.value" => Some(("idDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.dimension-name" => Some(("idDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.etag" => Some(("idDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.match-type" => Some(("idDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.id" => Some(("idDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "default-email" => Some(("defaultEmail", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "advertiser-group-id", "click-through-url-suffix", "default-click-through-event-tag-id", "default-email", "dimension-name", "etag", "floodlight-configuration-id", "floodlight-configuration-id-dimension-value", "id", "id-dimension-value", "kind", "match-type", "name", "original-floodlight-configuration-id", "status", "subaccount-id", "suspended", "value"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::Advertiser = json::value::from_value(object).unwrap(); + let mut call = self.hub.advertisers().patch(request, opt.value_of("profile-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _advertisers_update(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "status" => Some(("status", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "subaccount-id" => Some(("subaccountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "default-click-through-event-tag-id" => Some(("defaultClickThroughEventTagId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "original-floodlight-configuration-id" => Some(("originalFloodlightConfigurationId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "click-through-url-suffix" => Some(("clickThroughUrlSuffix", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-configuration-id" => Some(("floodlightConfigurationId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "suspended" => Some(("suspended", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "floodlight-configuration-id-dimension-value.kind" => Some(("floodlightConfigurationIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-configuration-id-dimension-value.value" => Some(("floodlightConfigurationIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-configuration-id-dimension-value.dimension-name" => Some(("floodlightConfigurationIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-configuration-id-dimension-value.etag" => Some(("floodlightConfigurationIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-configuration-id-dimension-value.match-type" => Some(("floodlightConfigurationIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-configuration-id-dimension-value.id" => Some(("floodlightConfigurationIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-group-id" => Some(("advertiserGroupId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.kind" => Some(("idDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.value" => Some(("idDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.dimension-name" => Some(("idDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.etag" => Some(("idDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.match-type" => Some(("idDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.id" => Some(("idDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "default-email" => Some(("defaultEmail", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "advertiser-group-id", "click-through-url-suffix", "default-click-through-event-tag-id", "default-email", "dimension-name", "etag", "floodlight-configuration-id", "floodlight-configuration-id-dimension-value", "id", "id-dimension-value", "kind", "match-type", "name", "original-floodlight-configuration-id", "status", "subaccount-id", "suspended", "value"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::Advertiser = json::value::from_value(object).unwrap(); + let mut call = self.hub.advertisers().update(request, opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _browsers_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.browsers().list(opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _campaign_creative_associations_insert(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "creative-id" => Some(("creativeId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["creative-id", "kind"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::CampaignCreativeAssociation = json::value::from_value(object).unwrap(); + let mut call = self.hub.campaign_creative_associations().insert(request, opt.value_of("profile-id").unwrap_or(""), opt.value_of("campaign-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _campaign_creative_associations_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.campaign_creative_associations().list(opt.value_of("profile-id").unwrap_or(""), opt.value_of("campaign-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "sort-order" => { + call = call.sort_order(value.unwrap_or("")); + }, + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "max-results" => { + call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["page-token", "sort-order", "max-results"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _campaigns_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.campaigns().get(opt.value_of("profile-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _campaigns_insert(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "comment" => Some(("comment", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "start-date" => Some(("startDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "end-date" => Some(("endDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "click-through-url-suffix-properties.click-through-url-suffix" => Some(("clickThroughUrlSuffixProperties.clickThroughUrlSuffix", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "click-through-url-suffix-properties.override-inherited-suffix" => Some(("clickThroughUrlSuffixProperties.overrideInheritedSuffix", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "advertiser-id" => Some(("advertiserId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.kind" => Some(("advertiserIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.value" => Some(("advertiserIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.dimension-name" => Some(("advertiserIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.etag" => Some(("advertiserIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.match-type" => Some(("advertiserIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.id" => Some(("advertiserIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "creative-optimization-configuration.optimization-model" => Some(("creativeOptimizationConfiguration.optimizationModel", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "creative-optimization-configuration.id" => Some(("creativeOptimizationConfiguration.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "creative-optimization-configuration.name" => Some(("creativeOptimizationConfiguration.name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "trafficker-emails" => Some(("traffickerEmails", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "archived" => Some(("archived", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "external-id" => Some(("externalId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-group-id" => Some(("advertiserGroupId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.kind" => Some(("idDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.value" => Some(("idDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.dimension-name" => Some(("idDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.etag" => Some(("idDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.match-type" => Some(("idDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.id" => Some(("idDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "billing-invoice-code" => Some(("billingInvoiceCode", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "comscore-vce-enabled" => Some(("comscoreVceEnabled", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "creative-group-ids" => Some(("creativeGroupIds", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "default-click-through-event-tag-properties.override-inherited-event-tag" => Some(("defaultClickThroughEventTagProperties.overrideInheritedEventTag", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "default-click-through-event-tag-properties.default-click-through-event-tag-id" => Some(("defaultClickThroughEventTagProperties.defaultClickThroughEventTagId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "create-info.time" => Some(("createInfo.time", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "subaccount-id" => Some(("subaccountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "lookback-configuration.click-duration" => Some(("lookbackConfiguration.clickDuration", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "lookback-configuration.post-impression-activities-duration" => Some(("lookbackConfiguration.postImpressionActivitiesDuration", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "nielsen-ocr-enabled" => Some(("nielsenOcrEnabled", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "last-modified-info.time" => Some(("lastModifiedInfo.time", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "advertiser-group-id", "advertiser-id", "advertiser-id-dimension-value", "archived", "billing-invoice-code", "click-duration", "click-through-url-suffix", "click-through-url-suffix-properties", "comment", "comscore-vce-enabled", "create-info", "creative-group-ids", "creative-optimization-configuration", "default-click-through-event-tag-id", "default-click-through-event-tag-properties", "dimension-name", "end-date", "etag", "external-id", "id", "id-dimension-value", "kind", "last-modified-info", "lookback-configuration", "match-type", "name", "nielsen-ocr-enabled", "optimization-model", "override-inherited-event-tag", "override-inherited-suffix", "post-impression-activities-duration", "start-date", "subaccount-id", "time", "trafficker-emails", "value"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::Campaign = json::value::from_value(object).unwrap(); + let mut call = self.hub.campaigns().insert(request, opt.value_of("profile-id").unwrap_or(""), opt.value_of("default-landing-page-name").unwrap_or(""), opt.value_of("default-landing-page-url").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _campaigns_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.campaigns().list(opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "subaccount-id" => { + call = call.subaccount_id(value.unwrap_or("")); + }, + "sort-order" => { + call = call.sort_order(value.unwrap_or("")); + }, + "sort-field" => { + call = call.sort_field(value.unwrap_or("")); + }, + "search-string" => { + call = call.search_string(value.unwrap_or("")); + }, + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "overridden-event-tag-id" => { + call = call.overridden_event_tag_id(value.unwrap_or("")); + }, + "max-results" => { + call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer")); + }, + "ids" => { + call = call.add_ids(value.unwrap_or("")); + }, + "excluded-ids" => { + call = call.add_excluded_ids(value.unwrap_or("")); + }, + "at-least-one-optimization-activity" => { + call = call.at_least_one_optimization_activity(arg_from_str(value.unwrap_or("false"), err, "at-least-one-optimization-activity", "boolean")); + }, + "archived" => { + call = call.archived(arg_from_str(value.unwrap_or("false"), err, "archived", "boolean")); + }, + "advertiser-ids" => { + call = call.add_advertiser_ids(value.unwrap_or("")); + }, + "advertiser-group-ids" => { + call = call.add_advertiser_group_ids(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["archived", "search-string", "subaccount-id", "sort-field", "advertiser-ids", "ids", "max-results", "excluded-ids", "page-token", "advertiser-group-ids", "sort-order", "overridden-event-tag-id", "at-least-one-optimization-activity"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _campaigns_patch(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "comment" => Some(("comment", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "start-date" => Some(("startDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "end-date" => Some(("endDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "click-through-url-suffix-properties.click-through-url-suffix" => Some(("clickThroughUrlSuffixProperties.clickThroughUrlSuffix", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "click-through-url-suffix-properties.override-inherited-suffix" => Some(("clickThroughUrlSuffixProperties.overrideInheritedSuffix", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "advertiser-id" => Some(("advertiserId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.kind" => Some(("advertiserIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.value" => Some(("advertiserIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.dimension-name" => Some(("advertiserIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.etag" => Some(("advertiserIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.match-type" => Some(("advertiserIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.id" => Some(("advertiserIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "creative-optimization-configuration.optimization-model" => Some(("creativeOptimizationConfiguration.optimizationModel", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "creative-optimization-configuration.id" => Some(("creativeOptimizationConfiguration.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "creative-optimization-configuration.name" => Some(("creativeOptimizationConfiguration.name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "trafficker-emails" => Some(("traffickerEmails", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "archived" => Some(("archived", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "external-id" => Some(("externalId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-group-id" => Some(("advertiserGroupId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.kind" => Some(("idDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.value" => Some(("idDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.dimension-name" => Some(("idDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.etag" => Some(("idDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.match-type" => Some(("idDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.id" => Some(("idDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "billing-invoice-code" => Some(("billingInvoiceCode", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "comscore-vce-enabled" => Some(("comscoreVceEnabled", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "creative-group-ids" => Some(("creativeGroupIds", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "default-click-through-event-tag-properties.override-inherited-event-tag" => Some(("defaultClickThroughEventTagProperties.overrideInheritedEventTag", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "default-click-through-event-tag-properties.default-click-through-event-tag-id" => Some(("defaultClickThroughEventTagProperties.defaultClickThroughEventTagId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "create-info.time" => Some(("createInfo.time", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "subaccount-id" => Some(("subaccountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "lookback-configuration.click-duration" => Some(("lookbackConfiguration.clickDuration", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "lookback-configuration.post-impression-activities-duration" => Some(("lookbackConfiguration.postImpressionActivitiesDuration", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "nielsen-ocr-enabled" => Some(("nielsenOcrEnabled", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "last-modified-info.time" => Some(("lastModifiedInfo.time", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "advertiser-group-id", "advertiser-id", "advertiser-id-dimension-value", "archived", "billing-invoice-code", "click-duration", "click-through-url-suffix", "click-through-url-suffix-properties", "comment", "comscore-vce-enabled", "create-info", "creative-group-ids", "creative-optimization-configuration", "default-click-through-event-tag-id", "default-click-through-event-tag-properties", "dimension-name", "end-date", "etag", "external-id", "id", "id-dimension-value", "kind", "last-modified-info", "lookback-configuration", "match-type", "name", "nielsen-ocr-enabled", "optimization-model", "override-inherited-event-tag", "override-inherited-suffix", "post-impression-activities-duration", "start-date", "subaccount-id", "time", "trafficker-emails", "value"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::Campaign = json::value::from_value(object).unwrap(); + let mut call = self.hub.campaigns().patch(request, opt.value_of("profile-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _campaigns_update(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "comment" => Some(("comment", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "start-date" => Some(("startDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "end-date" => Some(("endDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "click-through-url-suffix-properties.click-through-url-suffix" => Some(("clickThroughUrlSuffixProperties.clickThroughUrlSuffix", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "click-through-url-suffix-properties.override-inherited-suffix" => Some(("clickThroughUrlSuffixProperties.overrideInheritedSuffix", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "advertiser-id" => Some(("advertiserId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.kind" => Some(("advertiserIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.value" => Some(("advertiserIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.dimension-name" => Some(("advertiserIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.etag" => Some(("advertiserIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.match-type" => Some(("advertiserIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.id" => Some(("advertiserIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "creative-optimization-configuration.optimization-model" => Some(("creativeOptimizationConfiguration.optimizationModel", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "creative-optimization-configuration.id" => Some(("creativeOptimizationConfiguration.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "creative-optimization-configuration.name" => Some(("creativeOptimizationConfiguration.name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "trafficker-emails" => Some(("traffickerEmails", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "archived" => Some(("archived", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "external-id" => Some(("externalId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-group-id" => Some(("advertiserGroupId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.kind" => Some(("idDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.value" => Some(("idDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.dimension-name" => Some(("idDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.etag" => Some(("idDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.match-type" => Some(("idDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.id" => Some(("idDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "billing-invoice-code" => Some(("billingInvoiceCode", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "comscore-vce-enabled" => Some(("comscoreVceEnabled", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "creative-group-ids" => Some(("creativeGroupIds", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "default-click-through-event-tag-properties.override-inherited-event-tag" => Some(("defaultClickThroughEventTagProperties.overrideInheritedEventTag", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "default-click-through-event-tag-properties.default-click-through-event-tag-id" => Some(("defaultClickThroughEventTagProperties.defaultClickThroughEventTagId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "create-info.time" => Some(("createInfo.time", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "subaccount-id" => Some(("subaccountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "lookback-configuration.click-duration" => Some(("lookbackConfiguration.clickDuration", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "lookback-configuration.post-impression-activities-duration" => Some(("lookbackConfiguration.postImpressionActivitiesDuration", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "nielsen-ocr-enabled" => Some(("nielsenOcrEnabled", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "last-modified-info.time" => Some(("lastModifiedInfo.time", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "advertiser-group-id", "advertiser-id", "advertiser-id-dimension-value", "archived", "billing-invoice-code", "click-duration", "click-through-url-suffix", "click-through-url-suffix-properties", "comment", "comscore-vce-enabled", "create-info", "creative-group-ids", "creative-optimization-configuration", "default-click-through-event-tag-id", "default-click-through-event-tag-properties", "dimension-name", "end-date", "etag", "external-id", "id", "id-dimension-value", "kind", "last-modified-info", "lookback-configuration", "match-type", "name", "nielsen-ocr-enabled", "optimization-model", "override-inherited-event-tag", "override-inherited-suffix", "post-impression-activities-duration", "start-date", "subaccount-id", "time", "trafficker-emails", "value"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::Campaign = json::value::from_value(object).unwrap(); + let mut call = self.hub.campaigns().update(request, opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _change_logs_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.change_logs().get(opt.value_of("profile-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _change_logs_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.change_logs().list(opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "user-profile-ids" => { + call = call.add_user_profile_ids(value.unwrap_or("")); + }, + "search-string" => { + call = call.search_string(value.unwrap_or("")); + }, + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "object-type" => { + call = call.object_type(value.unwrap_or("")); + }, + "object-ids" => { + call = call.add_object_ids(value.unwrap_or("")); + }, + "min-change-time" => { + call = call.min_change_time(value.unwrap_or("")); + }, + "max-results" => { + call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer")); + }, + "max-change-time" => { + call = call.max_change_time(value.unwrap_or("")); + }, + "ids" => { + call = call.add_ids(value.unwrap_or("")); + }, + "action" => { + call = call.action(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["min-change-time", "search-string", "max-change-time", "user-profile-ids", "ids", "max-results", "object-ids", "page-token", "action", "object-type"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _cities_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.cities().list(opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "region-dart-ids" => { + call = call.add_region_dart_ids(value.unwrap_or("")); + }, + "name-prefix" => { + call = call.name_prefix(value.unwrap_or("")); + }, + "dart-ids" => { + call = call.add_dart_ids(value.unwrap_or("")); + }, + "country-dart-ids" => { + call = call.add_country_dart_ids(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["dart-ids", "country-dart-ids", "region-dart-ids", "name-prefix"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _connection_types_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.connection_types().get(opt.value_of("profile-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _connection_types_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.connection_types().list(opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _content_categories_delete(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.content_categories().delete(opt.value_of("profile-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok(mut response) => { + Ok(()) + } + } + } + } + + fn _content_categories_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.content_categories().get(opt.value_of("profile-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _content_categories_insert(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "id", "kind", "name"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::ContentCategory = json::value::from_value(object).unwrap(); + let mut call = self.hub.content_categories().insert(request, opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _content_categories_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.content_categories().list(opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "sort-order" => { + call = call.sort_order(value.unwrap_or("")); + }, + "sort-field" => { + call = call.sort_field(value.unwrap_or("")); + }, + "search-string" => { + call = call.search_string(value.unwrap_or("")); + }, + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "max-results" => { + call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer")); + }, + "ids" => { + call = call.add_ids(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["search-string", "sort-field", "ids", "max-results", "page-token", "sort-order"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _content_categories_patch(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "id", "kind", "name"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::ContentCategory = json::value::from_value(object).unwrap(); + let mut call = self.hub.content_categories().patch(request, opt.value_of("profile-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _content_categories_update(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "id", "kind", "name"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::ContentCategory = json::value::from_value(object).unwrap(); + let mut call = self.hub.content_categories().update(request, opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _countries_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.countries().get(opt.value_of("profile-id").unwrap_or(""), opt.value_of("dart-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _countries_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.countries().list(opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _creative_assets_insert(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "warned-validation-rules" => Some(("warnedValidationRules", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "detected-features" => Some(("detectedFeatures", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "asset-identifier.type" => Some(("assetIdentifier.type", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "asset-identifier.name" => Some(("assetIdentifier.name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["asset-identifier", "detected-features", "kind", "name", "type", "warned-validation-rules"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::CreativeAssetMetadata = json::value::from_value(object).unwrap(); + let mut call = self.hub.creative_assets().insert(request, opt.value_of("profile-id").unwrap_or(""), opt.value_of("advertiser-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let vals = opt.values_of("mode").unwrap(); + let protocol = calltype_from_str(vals[0], ["simple", "resumable"].iter().map(|&v| v.to_string()).collect(), err); + let mut input_file = input_file_from_opts(vals[1], err); + let mime_type = input_mime_from_opts(opt.value_of("mime").unwrap_or("application/octet-stream"), err); + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Upload(UploadProtocol::Simple) => call.upload(input_file.unwrap(), mime_type.unwrap()), + CallType::Upload(UploadProtocol::Resumable) => call.upload_resumable(input_file.unwrap(), mime_type.unwrap()), + CallType::Standard => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _creative_field_values_delete(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.creative_field_values().delete(opt.value_of("profile-id").unwrap_or(""), opt.value_of("creative-field-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok(mut response) => { + Ok(()) + } + } + } + } + + fn _creative_field_values_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.creative_field_values().get(opt.value_of("profile-id").unwrap_or(""), opt.value_of("creative-field-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _creative_field_values_insert(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "value" => Some(("value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["id", "kind", "value"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::CreativeFieldValue = json::value::from_value(object).unwrap(); + let mut call = self.hub.creative_field_values().insert(request, opt.value_of("profile-id").unwrap_or(""), opt.value_of("creative-field-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _creative_field_values_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.creative_field_values().list(opt.value_of("profile-id").unwrap_or(""), opt.value_of("creative-field-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "sort-order" => { + call = call.sort_order(value.unwrap_or("")); + }, + "sort-field" => { + call = call.sort_field(value.unwrap_or("")); + }, + "search-string" => { + call = call.search_string(value.unwrap_or("")); + }, + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "max-results" => { + call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer")); + }, + "ids" => { + call = call.add_ids(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["search-string", "sort-field", "ids", "max-results", "page-token", "sort-order"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _creative_field_values_patch(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "value" => Some(("value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["id", "kind", "value"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::CreativeFieldValue = json::value::from_value(object).unwrap(); + let mut call = self.hub.creative_field_values().patch(request, opt.value_of("profile-id").unwrap_or(""), opt.value_of("creative-field-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _creative_field_values_update(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "value" => Some(("value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["id", "kind", "value"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::CreativeFieldValue = json::value::from_value(object).unwrap(); + let mut call = self.hub.creative_field_values().update(request, opt.value_of("profile-id").unwrap_or(""), opt.value_of("creative-field-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _creative_fields_delete(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.creative_fields().delete(opt.value_of("profile-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok(mut response) => { + Ok(()) + } + } + } + } + + fn _creative_fields_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.creative_fields().get(opt.value_of("profile-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _creative_fields_insert(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "subaccount-id" => Some(("subaccountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id" => Some(("advertiserId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.kind" => Some(("advertiserIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.value" => Some(("advertiserIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.dimension-name" => Some(("advertiserIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.etag" => Some(("advertiserIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.match-type" => Some(("advertiserIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.id" => Some(("advertiserIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "advertiser-id", "advertiser-id-dimension-value", "dimension-name", "etag", "id", "kind", "match-type", "name", "subaccount-id", "value"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::CreativeField = json::value::from_value(object).unwrap(); + let mut call = self.hub.creative_fields().insert(request, opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _creative_fields_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.creative_fields().list(opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "sort-order" => { + call = call.sort_order(value.unwrap_or("")); + }, + "sort-field" => { + call = call.sort_field(value.unwrap_or("")); + }, + "search-string" => { + call = call.search_string(value.unwrap_or("")); + }, + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "max-results" => { + call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer")); + }, + "ids" => { + call = call.add_ids(value.unwrap_or("")); + }, + "advertiser-ids" => { + call = call.add_advertiser_ids(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["search-string", "sort-field", "advertiser-ids", "ids", "max-results", "page-token", "sort-order"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _creative_fields_patch(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "subaccount-id" => Some(("subaccountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id" => Some(("advertiserId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.kind" => Some(("advertiserIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.value" => Some(("advertiserIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.dimension-name" => Some(("advertiserIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.etag" => Some(("advertiserIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.match-type" => Some(("advertiserIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.id" => Some(("advertiserIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "advertiser-id", "advertiser-id-dimension-value", "dimension-name", "etag", "id", "kind", "match-type", "name", "subaccount-id", "value"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::CreativeField = json::value::from_value(object).unwrap(); + let mut call = self.hub.creative_fields().patch(request, opt.value_of("profile-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _creative_fields_update(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "subaccount-id" => Some(("subaccountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id" => Some(("advertiserId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.kind" => Some(("advertiserIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.value" => Some(("advertiserIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.dimension-name" => Some(("advertiserIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.etag" => Some(("advertiserIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.match-type" => Some(("advertiserIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.id" => Some(("advertiserIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "advertiser-id", "advertiser-id-dimension-value", "dimension-name", "etag", "id", "kind", "match-type", "name", "subaccount-id", "value"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::CreativeField = json::value::from_value(object).unwrap(); + let mut call = self.hub.creative_fields().update(request, opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _creative_groups_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.creative_groups().get(opt.value_of("profile-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _creative_groups_insert(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "subaccount-id" => Some(("subaccountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "group-number" => Some(("groupNumber", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "advertiser-id" => Some(("advertiserId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.kind" => Some(("advertiserIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.value" => Some(("advertiserIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.dimension-name" => Some(("advertiserIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.etag" => Some(("advertiserIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.match-type" => Some(("advertiserIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.id" => Some(("advertiserIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "advertiser-id", "advertiser-id-dimension-value", "dimension-name", "etag", "group-number", "id", "kind", "match-type", "name", "subaccount-id", "value"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::CreativeGroup = json::value::from_value(object).unwrap(); + let mut call = self.hub.creative_groups().insert(request, opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _creative_groups_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.creative_groups().list(opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "sort-order" => { + call = call.sort_order(value.unwrap_or("")); + }, + "sort-field" => { + call = call.sort_field(value.unwrap_or("")); + }, + "search-string" => { + call = call.search_string(value.unwrap_or("")); + }, + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "max-results" => { + call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer")); + }, + "ids" => { + call = call.add_ids(value.unwrap_or("")); + }, + "group-number" => { + call = call.group_number(arg_from_str(value.unwrap_or("-0"), err, "group-number", "integer")); + }, + "advertiser-ids" => { + call = call.add_advertiser_ids(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["search-string", "sort-field", "advertiser-ids", "ids", "max-results", "group-number", "page-token", "sort-order"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _creative_groups_patch(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "subaccount-id" => Some(("subaccountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "group-number" => Some(("groupNumber", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "advertiser-id" => Some(("advertiserId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.kind" => Some(("advertiserIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.value" => Some(("advertiserIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.dimension-name" => Some(("advertiserIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.etag" => Some(("advertiserIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.match-type" => Some(("advertiserIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.id" => Some(("advertiserIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "advertiser-id", "advertiser-id-dimension-value", "dimension-name", "etag", "group-number", "id", "kind", "match-type", "name", "subaccount-id", "value"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::CreativeGroup = json::value::from_value(object).unwrap(); + let mut call = self.hub.creative_groups().patch(request, opt.value_of("profile-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _creative_groups_update(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "subaccount-id" => Some(("subaccountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "group-number" => Some(("groupNumber", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "advertiser-id" => Some(("advertiserId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.kind" => Some(("advertiserIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.value" => Some(("advertiserIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.dimension-name" => Some(("advertiserIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.etag" => Some(("advertiserIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.match-type" => Some(("advertiserIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.id" => Some(("advertiserIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "advertiser-id", "advertiser-id-dimension-value", "dimension-name", "etag", "group-number", "id", "kind", "match-type", "name", "subaccount-id", "value"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::CreativeGroup = json::value::from_value(object).unwrap(); + let mut call = self.hub.creative_groups().update(request, opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _creatives_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.creatives().get(opt.value_of("profile-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _creatives_insert(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "artwork-type" => Some(("artworkType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "latest-trafficked-creative-id" => Some(("latestTraffickedCreativeId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id" => Some(("advertiserId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "required-flash-plugin-version" => Some(("requiredFlashPluginVersion", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "fs-command.window-height" => Some(("fsCommand.windowHeight", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "fs-command.top" => Some(("fsCommand.top", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "fs-command.window-width" => Some(("fsCommand.windowWidth", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "fs-command.position-option" => Some(("fsCommand.positionOption", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "fs-command.left" => Some(("fsCommand.left", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "rendering-id-dimension-value.kind" => Some(("renderingIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "rendering-id-dimension-value.value" => Some(("renderingIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "rendering-id-dimension-value.dimension-name" => Some(("renderingIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "rendering-id-dimension-value.etag" => Some(("renderingIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "rendering-id-dimension-value.match-type" => Some(("renderingIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "rendering-id-dimension-value.id" => Some(("renderingIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "size.width" => Some(("size.width", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "size.kind" => Some(("size.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "size.iab" => Some(("size.iab", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "size.id" => Some(("size.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "size.height" => Some(("size.height", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "studio-trafficked-creative-id" => Some(("studioTraffickedCreativeId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "archived" => Some(("archived", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "override-css" => Some(("overrideCss", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "required-flash-version" => Some(("requiredFlashVersion", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "rendering-id" => Some(("renderingId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "video-description" => Some(("videoDescription", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "third-party-backup-image-impressions-url" => Some(("thirdPartyBackupImageImpressionsUrl", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "version" => Some(("version", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "background-color" => Some(("backgroundColor", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "custom-key-values" => Some(("customKeyValues", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "id-dimension-value.kind" => Some(("idDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.value" => Some(("idDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.dimension-name" => Some(("idDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.etag" => Some(("idDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.match-type" => Some(("idDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.id" => Some(("idDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "html-code" => Some(("htmlCode", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "type" => Some(("type", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "total-file-size" => Some(("totalFileSize", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "third-party-rich-media-impressions-url" => Some(("thirdPartyRichMediaImpressionsUrl", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "studio-advertiser-id" => Some(("studioAdvertiserId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "video-duration" => Some(("videoDuration", JsonTypeInfo { jtype: JsonType::Float, ctype: ComplexType::Pod })), + "redirect-url" => Some(("redirectUrl", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "commercial-id" => Some(("commercialId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "active" => Some(("active", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "backup-image-reporting-label" => Some(("backupImageReportingLabel", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "compatibility" => Some(("compatibility", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "ad-parameters" => Some(("adParameters", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "html-code-locked" => Some(("htmlCodeLocked", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "subaccount-id" => Some(("subaccountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "ad-tag-keys" => Some(("adTagKeys", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "convert-flash-to-html5" => Some(("convertFlashToHtml5", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "ssl-override" => Some(("sslOverride", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "last-modified-info.time" => Some(("lastModifiedInfo.time", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "backup-image-click-through-url" => Some(("backupImageClickThroughUrl", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "ssl-compliant" => Some(("sslCompliant", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "studio-creative-id" => Some(("studioCreativeId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "authoring-tool" => Some(("authoringTool", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "allow-script-access" => Some(("allowScriptAccess", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "companion-creatives" => Some(("companionCreatives", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "auto-advance-images" => Some(("auto_advance_images", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "backup-image-features" => Some(("backupImageFeatures", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "backup-image-target-window.custom-html" => Some(("backupImageTargetWindow.customHtml", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "backup-image-target-window.target-window-option" => Some(("backupImageTargetWindow.targetWindowOption", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "skippable" => Some(("skippable", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "active", "ad-parameters", "ad-tag-keys", "advertiser-id", "allow-script-access", "archived", "artwork-type", "authoring-tool", "auto-advance-images", "background-color", "backup-image-click-through-url", "backup-image-features", "backup-image-reporting-label", "backup-image-target-window", "commercial-id", "companion-creatives", "compatibility", "convert-flash-to-html5", "custom-html", "custom-key-values", "dimension-name", "etag", "fs-command", "height", "html-code", "html-code-locked", "iab", "id", "id-dimension-value", "kind", "last-modified-info", "latest-trafficked-creative-id", "left", "match-type", "name", "override-css", "position-option", "redirect-url", "rendering-id", "rendering-id-dimension-value", "required-flash-plugin-version", "required-flash-version", "size", "skippable", "ssl-compliant", "ssl-override", "studio-advertiser-id", "studio-creative-id", "studio-trafficked-creative-id", "subaccount-id", "target-window-option", "third-party-backup-image-impressions-url", "third-party-rich-media-impressions-url", "time", "top", "total-file-size", "type", "value", "version", "video-description", "video-duration", "width", "window-height", "window-width"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::Creative = json::value::from_value(object).unwrap(); + let mut call = self.hub.creatives().insert(request, opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _creatives_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.creatives().list(opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "types" => { + call = call.add_types(value.unwrap_or("")); + }, + "studio-creative-id" => { + call = call.studio_creative_id(value.unwrap_or("")); + }, + "sort-order" => { + call = call.sort_order(value.unwrap_or("")); + }, + "sort-field" => { + call = call.sort_field(value.unwrap_or("")); + }, + "size-ids" => { + call = call.add_size_ids(value.unwrap_or("")); + }, + "search-string" => { + call = call.search_string(value.unwrap_or("")); + }, + "rendering-ids" => { + call = call.add_rendering_ids(value.unwrap_or("")); + }, + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "max-results" => { + call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer")); + }, + "ids" => { + call = call.add_ids(value.unwrap_or("")); + }, + "creative-field-ids" => { + call = call.add_creative_field_ids(value.unwrap_or("")); + }, + "companion-creative-ids" => { + call = call.add_companion_creative_ids(value.unwrap_or("")); + }, + "campaign-id" => { + call = call.campaign_id(value.unwrap_or("")); + }, + "archived" => { + call = call.archived(arg_from_str(value.unwrap_or("false"), err, "archived", "boolean")); + }, + "advertiser-id" => { + call = call.advertiser_id(value.unwrap_or("")); + }, + "active" => { + call = call.active(arg_from_str(value.unwrap_or("false"), err, "active", "boolean")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["advertiser-id", "archived", "search-string", "max-results", "campaign-id", "sort-field", "rendering-ids", "ids", "studio-creative-id", "size-ids", "page-token", "sort-order", "companion-creative-ids", "active", "creative-field-ids", "types"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _creatives_patch(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "artwork-type" => Some(("artworkType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "latest-trafficked-creative-id" => Some(("latestTraffickedCreativeId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id" => Some(("advertiserId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "required-flash-plugin-version" => Some(("requiredFlashPluginVersion", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "fs-command.window-height" => Some(("fsCommand.windowHeight", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "fs-command.top" => Some(("fsCommand.top", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "fs-command.window-width" => Some(("fsCommand.windowWidth", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "fs-command.position-option" => Some(("fsCommand.positionOption", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "fs-command.left" => Some(("fsCommand.left", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "rendering-id-dimension-value.kind" => Some(("renderingIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "rendering-id-dimension-value.value" => Some(("renderingIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "rendering-id-dimension-value.dimension-name" => Some(("renderingIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "rendering-id-dimension-value.etag" => Some(("renderingIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "rendering-id-dimension-value.match-type" => Some(("renderingIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "rendering-id-dimension-value.id" => Some(("renderingIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "size.width" => Some(("size.width", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "size.kind" => Some(("size.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "size.iab" => Some(("size.iab", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "size.id" => Some(("size.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "size.height" => Some(("size.height", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "studio-trafficked-creative-id" => Some(("studioTraffickedCreativeId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "archived" => Some(("archived", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "override-css" => Some(("overrideCss", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "required-flash-version" => Some(("requiredFlashVersion", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "rendering-id" => Some(("renderingId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "video-description" => Some(("videoDescription", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "third-party-backup-image-impressions-url" => Some(("thirdPartyBackupImageImpressionsUrl", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "version" => Some(("version", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "background-color" => Some(("backgroundColor", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "custom-key-values" => Some(("customKeyValues", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "id-dimension-value.kind" => Some(("idDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.value" => Some(("idDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.dimension-name" => Some(("idDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.etag" => Some(("idDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.match-type" => Some(("idDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.id" => Some(("idDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "html-code" => Some(("htmlCode", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "type" => Some(("type", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "total-file-size" => Some(("totalFileSize", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "third-party-rich-media-impressions-url" => Some(("thirdPartyRichMediaImpressionsUrl", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "studio-advertiser-id" => Some(("studioAdvertiserId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "video-duration" => Some(("videoDuration", JsonTypeInfo { jtype: JsonType::Float, ctype: ComplexType::Pod })), + "redirect-url" => Some(("redirectUrl", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "commercial-id" => Some(("commercialId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "active" => Some(("active", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "backup-image-reporting-label" => Some(("backupImageReportingLabel", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "compatibility" => Some(("compatibility", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "ad-parameters" => Some(("adParameters", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "html-code-locked" => Some(("htmlCodeLocked", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "subaccount-id" => Some(("subaccountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "ad-tag-keys" => Some(("adTagKeys", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "convert-flash-to-html5" => Some(("convertFlashToHtml5", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "ssl-override" => Some(("sslOverride", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "last-modified-info.time" => Some(("lastModifiedInfo.time", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "backup-image-click-through-url" => Some(("backupImageClickThroughUrl", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "ssl-compliant" => Some(("sslCompliant", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "studio-creative-id" => Some(("studioCreativeId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "authoring-tool" => Some(("authoringTool", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "allow-script-access" => Some(("allowScriptAccess", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "companion-creatives" => Some(("companionCreatives", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "auto-advance-images" => Some(("auto_advance_images", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "backup-image-features" => Some(("backupImageFeatures", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "backup-image-target-window.custom-html" => Some(("backupImageTargetWindow.customHtml", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "backup-image-target-window.target-window-option" => Some(("backupImageTargetWindow.targetWindowOption", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "skippable" => Some(("skippable", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "active", "ad-parameters", "ad-tag-keys", "advertiser-id", "allow-script-access", "archived", "artwork-type", "authoring-tool", "auto-advance-images", "background-color", "backup-image-click-through-url", "backup-image-features", "backup-image-reporting-label", "backup-image-target-window", "commercial-id", "companion-creatives", "compatibility", "convert-flash-to-html5", "custom-html", "custom-key-values", "dimension-name", "etag", "fs-command", "height", "html-code", "html-code-locked", "iab", "id", "id-dimension-value", "kind", "last-modified-info", "latest-trafficked-creative-id", "left", "match-type", "name", "override-css", "position-option", "redirect-url", "rendering-id", "rendering-id-dimension-value", "required-flash-plugin-version", "required-flash-version", "size", "skippable", "ssl-compliant", "ssl-override", "studio-advertiser-id", "studio-creative-id", "studio-trafficked-creative-id", "subaccount-id", "target-window-option", "third-party-backup-image-impressions-url", "third-party-rich-media-impressions-url", "time", "top", "total-file-size", "type", "value", "version", "video-description", "video-duration", "width", "window-height", "window-width"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::Creative = json::value::from_value(object).unwrap(); + let mut call = self.hub.creatives().patch(request, opt.value_of("profile-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _creatives_update(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "artwork-type" => Some(("artworkType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "latest-trafficked-creative-id" => Some(("latestTraffickedCreativeId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id" => Some(("advertiserId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "required-flash-plugin-version" => Some(("requiredFlashPluginVersion", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "fs-command.window-height" => Some(("fsCommand.windowHeight", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "fs-command.top" => Some(("fsCommand.top", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "fs-command.window-width" => Some(("fsCommand.windowWidth", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "fs-command.position-option" => Some(("fsCommand.positionOption", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "fs-command.left" => Some(("fsCommand.left", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "rendering-id-dimension-value.kind" => Some(("renderingIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "rendering-id-dimension-value.value" => Some(("renderingIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "rendering-id-dimension-value.dimension-name" => Some(("renderingIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "rendering-id-dimension-value.etag" => Some(("renderingIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "rendering-id-dimension-value.match-type" => Some(("renderingIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "rendering-id-dimension-value.id" => Some(("renderingIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "size.width" => Some(("size.width", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "size.kind" => Some(("size.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "size.iab" => Some(("size.iab", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "size.id" => Some(("size.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "size.height" => Some(("size.height", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "studio-trafficked-creative-id" => Some(("studioTraffickedCreativeId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "archived" => Some(("archived", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "override-css" => Some(("overrideCss", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "required-flash-version" => Some(("requiredFlashVersion", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "rendering-id" => Some(("renderingId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "video-description" => Some(("videoDescription", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "third-party-backup-image-impressions-url" => Some(("thirdPartyBackupImageImpressionsUrl", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "version" => Some(("version", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "background-color" => Some(("backgroundColor", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "custom-key-values" => Some(("customKeyValues", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "id-dimension-value.kind" => Some(("idDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.value" => Some(("idDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.dimension-name" => Some(("idDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.etag" => Some(("idDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.match-type" => Some(("idDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.id" => Some(("idDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "html-code" => Some(("htmlCode", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "type" => Some(("type", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "total-file-size" => Some(("totalFileSize", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "third-party-rich-media-impressions-url" => Some(("thirdPartyRichMediaImpressionsUrl", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "studio-advertiser-id" => Some(("studioAdvertiserId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "video-duration" => Some(("videoDuration", JsonTypeInfo { jtype: JsonType::Float, ctype: ComplexType::Pod })), + "redirect-url" => Some(("redirectUrl", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "commercial-id" => Some(("commercialId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "active" => Some(("active", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "backup-image-reporting-label" => Some(("backupImageReportingLabel", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "compatibility" => Some(("compatibility", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "ad-parameters" => Some(("adParameters", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "html-code-locked" => Some(("htmlCodeLocked", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "subaccount-id" => Some(("subaccountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "ad-tag-keys" => Some(("adTagKeys", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "convert-flash-to-html5" => Some(("convertFlashToHtml5", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "ssl-override" => Some(("sslOverride", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "last-modified-info.time" => Some(("lastModifiedInfo.time", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "backup-image-click-through-url" => Some(("backupImageClickThroughUrl", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "ssl-compliant" => Some(("sslCompliant", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "studio-creative-id" => Some(("studioCreativeId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "authoring-tool" => Some(("authoringTool", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "allow-script-access" => Some(("allowScriptAccess", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "companion-creatives" => Some(("companionCreatives", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "auto-advance-images" => Some(("auto_advance_images", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "backup-image-features" => Some(("backupImageFeatures", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "backup-image-target-window.custom-html" => Some(("backupImageTargetWindow.customHtml", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "backup-image-target-window.target-window-option" => Some(("backupImageTargetWindow.targetWindowOption", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "skippable" => Some(("skippable", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "active", "ad-parameters", "ad-tag-keys", "advertiser-id", "allow-script-access", "archived", "artwork-type", "authoring-tool", "auto-advance-images", "background-color", "backup-image-click-through-url", "backup-image-features", "backup-image-reporting-label", "backup-image-target-window", "commercial-id", "companion-creatives", "compatibility", "convert-flash-to-html5", "custom-html", "custom-key-values", "dimension-name", "etag", "fs-command", "height", "html-code", "html-code-locked", "iab", "id", "id-dimension-value", "kind", "last-modified-info", "latest-trafficked-creative-id", "left", "match-type", "name", "override-css", "position-option", "redirect-url", "rendering-id", "rendering-id-dimension-value", "required-flash-plugin-version", "required-flash-version", "size", "skippable", "ssl-compliant", "ssl-override", "studio-advertiser-id", "studio-creative-id", "studio-trafficked-creative-id", "subaccount-id", "target-window-option", "third-party-backup-image-impressions-url", "third-party-rich-media-impressions-url", "time", "top", "total-file-size", "type", "value", "version", "video-description", "video-duration", "width", "window-height", "window-width"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::Creative = json::value::from_value(object).unwrap(); + let mut call = self.hub.creatives().update(request, opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _dimension_values_query(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "dimension-name" => Some(("dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "start-date" => Some(("startDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "end-date" => Some(("endDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["dimension-name", "end-date", "kind", "start-date"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::DimensionValueRequest = json::value::from_value(object).unwrap(); + let mut call = self.hub.dimension_values().query(request, opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "max-results" => { + call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["page-token", "max-results"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _directory_site_contacts_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.directory_site_contacts().get(opt.value_of("profile-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _directory_site_contacts_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.directory_site_contacts().list(opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "sort-order" => { + call = call.sort_order(value.unwrap_or("")); + }, + "sort-field" => { + call = call.sort_field(value.unwrap_or("")); + }, + "search-string" => { + call = call.search_string(value.unwrap_or("")); + }, + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "max-results" => { + call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer")); + }, + "ids" => { + call = call.add_ids(value.unwrap_or("")); + }, + "directory-site-ids" => { + call = call.add_directory_site_ids(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["search-string", "directory-site-ids", "sort-field", "ids", "max-results", "page-token", "sort-order"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _directory_sites_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.directory_sites().get(opt.value_of("profile-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _directory_sites_insert(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "country-id" => Some(("countryId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "description" => Some(("description", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "settings.nielsen-ocr-opt-out" => Some(("settings.nielsenOcrOptOut", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "settings.active-view-opt-out" => Some(("settings.activeViewOptOut", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "settings.dfp-settings.dfp-network-name" => Some(("settings.dfp_settings.dfp_network_name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "settings.dfp-settings.publisher-portal-only" => Some(("settings.dfp_settings.publisherPortalOnly", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "settings.dfp-settings.programmatic-placement-accepted" => Some(("settings.dfp_settings.programmaticPlacementAccepted", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "settings.dfp-settings.pub-paid-placement-accepted" => Some(("settings.dfp_settings.pubPaidPlacementAccepted", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "settings.dfp-settings.dfp-network-code" => Some(("settings.dfp_settings.dfp_network_code", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "settings.verification-tag-opt-out" => Some(("settings.verificationTagOptOut", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "settings.instream-video-placement-accepted" => Some(("settings.instream_video_placement_accepted", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "settings.interstitial-placement-accepted" => Some(("settings.interstitialPlacementAccepted", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "settings.video-active-view-opt-out" => Some(("settings.videoActiveViewOptOut", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "currency-id" => Some(("currencyId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "inpage-tag-formats" => Some(("inpageTagFormats", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "url" => Some(("url", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "parent-id" => Some(("parentId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "interstitial-tag-formats" => Some(("interstitialTagFormats", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "id-dimension-value.kind" => Some(("idDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.value" => Some(("idDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.dimension-name" => Some(("idDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.etag" => Some(("idDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.match-type" => Some(("idDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.id" => Some(("idDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "active" => Some(("active", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["active", "active-view-opt-out", "country-id", "currency-id", "description", "dfp-network-code", "dfp-network-name", "dfp-settings", "dimension-name", "etag", "id", "id-dimension-value", "inpage-tag-formats", "instream-video-placement-accepted", "interstitial-placement-accepted", "interstitial-tag-formats", "kind", "match-type", "name", "nielsen-ocr-opt-out", "parent-id", "programmatic-placement-accepted", "pub-paid-placement-accepted", "publisher-portal-only", "settings", "url", "value", "verification-tag-opt-out", "video-active-view-opt-out"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::DirectorySite = json::value::from_value(object).unwrap(); + let mut call = self.hub.directory_sites().insert(request, opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _directory_sites_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.directory_sites().list(opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "sort-order" => { + call = call.sort_order(value.unwrap_or("")); + }, + "sort-field" => { + call = call.sort_field(value.unwrap_or("")); + }, + "search-string" => { + call = call.search_string(value.unwrap_or("")); + }, + "parent-id" => { + call = call.parent_id(value.unwrap_or("")); + }, + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "max-results" => { + call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer")); + }, + "ids" => { + call = call.add_ids(value.unwrap_or("")); + }, + "dfp-network-code" => { + call = call.dfp_network_code(value.unwrap_or("")); + }, + "country-id" => { + call = call.country_id(value.unwrap_or("")); + }, + "active" => { + call = call.active(arg_from_str(value.unwrap_or("false"), err, "active", "boolean")); + }, + "accepts-publisher-paid-placements" => { + call = call.accepts_publisher_paid_placements(arg_from_str(value.unwrap_or("false"), err, "accepts-publisher-paid-placements", "boolean")); + }, + "accepts-interstitial-placements" => { + call = call.accepts_interstitial_placements(arg_from_str(value.unwrap_or("false"), err, "accepts-interstitial-placements", "boolean")); + }, + "accepts-in-stream-video-placements" => { + call = call.accepts_in_stream_video_placements(arg_from_str(value.unwrap_or("false"), err, "accepts-in-stream-video-placements", "boolean")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["accepts-interstitial-placements", "accepts-publisher-paid-placements", "search-string", "country-id", "accepts-in-stream-video-placements", "sort-field", "ids", "max-results", "page-token", "sort-order", "parent-id", "active", "dfp-network-code"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _event_tags_delete(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.event_tags().delete(opt.value_of("profile-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok(mut response) => { + Ok(()) + } + } + } + } + + fn _event_tags_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.event_tags().get(opt.value_of("profile-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _event_tags_insert(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "status" => Some(("status", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "site-ids" => Some(("siteIds", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "subaccount-id" => Some(("subaccountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id" => Some(("campaignId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "url" => Some(("url", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "ssl-compliant" => Some(("sslCompliant", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "url-escape-levels" => Some(("urlEscapeLevels", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.kind" => Some(("campaignIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.value" => Some(("campaignIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.dimension-name" => Some(("campaignIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.etag" => Some(("campaignIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.match-type" => Some(("campaignIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.id" => Some(("campaignIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "enabled-by-default" => Some(("enabledByDefault", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "advertiser-id" => Some(("advertiserId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "site-filter-type" => Some(("siteFilterType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.kind" => Some(("advertiserIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.value" => Some(("advertiserIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.dimension-name" => Some(("advertiserIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.etag" => Some(("advertiserIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.match-type" => Some(("advertiserIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.id" => Some(("advertiserIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "exclude-from-adx-requests" => Some(("excludeFromAdxRequests", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "type" => Some(("type", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "advertiser-id", "advertiser-id-dimension-value", "campaign-id", "campaign-id-dimension-value", "dimension-name", "enabled-by-default", "etag", "exclude-from-adx-requests", "id", "kind", "match-type", "name", "site-filter-type", "site-ids", "ssl-compliant", "status", "subaccount-id", "type", "url", "url-escape-levels", "value"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::EventTag = json::value::from_value(object).unwrap(); + let mut call = self.hub.event_tags().insert(request, opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _event_tags_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.event_tags().list(opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "sort-order" => { + call = call.sort_order(value.unwrap_or("")); + }, + "sort-field" => { + call = call.sort_field(value.unwrap_or("")); + }, + "search-string" => { + call = call.search_string(value.unwrap_or("")); + }, + "ids" => { + call = call.add_ids(value.unwrap_or("")); + }, + "event-tag-types" => { + call = call.add_event_tag_types(value.unwrap_or("")); + }, + "enabled" => { + call = call.enabled(arg_from_str(value.unwrap_or("false"), err, "enabled", "boolean")); + }, + "definitions-only" => { + call = call.definitions_only(arg_from_str(value.unwrap_or("false"), err, "definitions-only", "boolean")); + }, + "campaign-id" => { + call = call.campaign_id(value.unwrap_or("")); + }, + "advertiser-id" => { + call = call.advertiser_id(value.unwrap_or("")); + }, + "ad-id" => { + call = call.ad_id(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["search-string", "campaign-id", "sort-field", "enabled", "ids", "advertiser-id", "ad-id", "sort-order", "event-tag-types", "definitions-only"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _event_tags_patch(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "status" => Some(("status", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "site-ids" => Some(("siteIds", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "subaccount-id" => Some(("subaccountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id" => Some(("campaignId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "url" => Some(("url", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "ssl-compliant" => Some(("sslCompliant", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "url-escape-levels" => Some(("urlEscapeLevels", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.kind" => Some(("campaignIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.value" => Some(("campaignIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.dimension-name" => Some(("campaignIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.etag" => Some(("campaignIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.match-type" => Some(("campaignIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.id" => Some(("campaignIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "enabled-by-default" => Some(("enabledByDefault", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "advertiser-id" => Some(("advertiserId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "site-filter-type" => Some(("siteFilterType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.kind" => Some(("advertiserIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.value" => Some(("advertiserIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.dimension-name" => Some(("advertiserIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.etag" => Some(("advertiserIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.match-type" => Some(("advertiserIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.id" => Some(("advertiserIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "exclude-from-adx-requests" => Some(("excludeFromAdxRequests", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "type" => Some(("type", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "advertiser-id", "advertiser-id-dimension-value", "campaign-id", "campaign-id-dimension-value", "dimension-name", "enabled-by-default", "etag", "exclude-from-adx-requests", "id", "kind", "match-type", "name", "site-filter-type", "site-ids", "ssl-compliant", "status", "subaccount-id", "type", "url", "url-escape-levels", "value"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::EventTag = json::value::from_value(object).unwrap(); + let mut call = self.hub.event_tags().patch(request, opt.value_of("profile-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _event_tags_update(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "status" => Some(("status", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "site-ids" => Some(("siteIds", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "subaccount-id" => Some(("subaccountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id" => Some(("campaignId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "url" => Some(("url", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "ssl-compliant" => Some(("sslCompliant", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "url-escape-levels" => Some(("urlEscapeLevels", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.kind" => Some(("campaignIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.value" => Some(("campaignIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.dimension-name" => Some(("campaignIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.etag" => Some(("campaignIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.match-type" => Some(("campaignIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.id" => Some(("campaignIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "enabled-by-default" => Some(("enabledByDefault", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "advertiser-id" => Some(("advertiserId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "site-filter-type" => Some(("siteFilterType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.kind" => Some(("advertiserIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.value" => Some(("advertiserIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.dimension-name" => Some(("advertiserIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.etag" => Some(("advertiserIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.match-type" => Some(("advertiserIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.id" => Some(("advertiserIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "exclude-from-adx-requests" => Some(("excludeFromAdxRequests", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "type" => Some(("type", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "advertiser-id", "advertiser-id-dimension-value", "campaign-id", "campaign-id-dimension-value", "dimension-name", "enabled-by-default", "etag", "exclude-from-adx-requests", "id", "kind", "match-type", "name", "site-filter-type", "site-ids", "ssl-compliant", "status", "subaccount-id", "type", "url", "url-escape-levels", "value"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::EventTag = json::value::from_value(object).unwrap(); + let mut call = self.hub.event_tags().update(request, opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _files_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut download_mode = false; + let mut call = self.hub.files().get(opt.value_of("report-id").unwrap_or(""), opt.value_of("file-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + if key == "alt" && value.unwrap_or("unset") == "media" { + download_mode = true; + } + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + if !download_mode { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + } else { + io::copy(&mut response, &mut ostream).unwrap(); + ostream.flush().unwrap(); + } + Ok(()) + } + } + } + } + + fn _files_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.files().list(opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "sort-order" => { + call = call.sort_order(value.unwrap_or("")); + }, + "sort-field" => { + call = call.sort_field(value.unwrap_or("")); + }, + "scope" => { + call = call.scope(value.unwrap_or("")); + }, + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "max-results" => { + call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["sort-field", "max-results", "sort-order", "page-token", "scope"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _floodlight_activities_delete(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.floodlight_activities().delete(opt.value_of("profile-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok(mut response) => { + Ok(()) + } + } + } + } + + fn _floodlight_activities_generatetag(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.floodlight_activities().generatetag(opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "floodlight-activity-id" => { + call = call.floodlight_activity_id(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["floodlight-activity-id"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _floodlight_activities_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.floodlight_activities().get(opt.value_of("profile-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _floodlight_activities_insert(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "tag-string" => Some(("tagString", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "secure" => Some(("secure", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "floodlight-activity-group-name" => Some(("floodlightActivityGroupName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "image-tag-enabled" => Some(("imageTagEnabled", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "advertiser-id" => Some(("advertiserId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.kind" => Some(("advertiserIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.value" => Some(("advertiserIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.dimension-name" => Some(("advertiserIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.etag" => Some(("advertiserIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.match-type" => Some(("advertiserIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.id" => Some(("advertiserIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-activity-group-id" => Some(("floodlightActivityGroupId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-activity-group-tag-string" => Some(("floodlightActivityGroupTagString", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "ssl-compliant" => Some(("sslCompliant", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "floodlight-configuration-id-dimension-value.kind" => Some(("floodlightConfigurationIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-configuration-id-dimension-value.value" => Some(("floodlightConfigurationIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-configuration-id-dimension-value.dimension-name" => Some(("floodlightConfigurationIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-configuration-id-dimension-value.etag" => Some(("floodlightConfigurationIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-configuration-id-dimension-value.match-type" => Some(("floodlightConfigurationIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-configuration-id-dimension-value.id" => Some(("floodlightConfigurationIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "cache-busting-type" => Some(("cacheBustingType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "hidden" => Some(("hidden", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "ssl-required" => Some(("sslRequired", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "expected-url" => Some(("expectedUrl", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "tag-format" => Some(("tagFormat", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "subaccount-id" => Some(("subaccountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "notes" => Some(("notes", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-configuration-id" => Some(("floodlightConfigurationId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "user-defined-variable-types" => Some(("userDefinedVariableTypes", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "counting-method" => Some(("countingMethod", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.kind" => Some(("idDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.value" => Some(("idDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.dimension-name" => Some(("idDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.etag" => Some(("idDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.match-type" => Some(("idDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.id" => Some(("idDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-activity-group-type" => Some(("floodlightActivityGroupType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "advertiser-id", "advertiser-id-dimension-value", "cache-busting-type", "counting-method", "dimension-name", "etag", "expected-url", "floodlight-activity-group-id", "floodlight-activity-group-name", "floodlight-activity-group-tag-string", "floodlight-activity-group-type", "floodlight-configuration-id", "floodlight-configuration-id-dimension-value", "hidden", "id", "id-dimension-value", "image-tag-enabled", "kind", "match-type", "name", "notes", "secure", "ssl-compliant", "ssl-required", "subaccount-id", "tag-format", "tag-string", "user-defined-variable-types", "value"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::FloodlightActivity = json::value::from_value(object).unwrap(); + let mut call = self.hub.floodlight_activities().insert(request, opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _floodlight_activities_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.floodlight_activities().list(opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "tag-string" => { + call = call.tag_string(value.unwrap_or("")); + }, + "sort-order" => { + call = call.sort_order(value.unwrap_or("")); + }, + "sort-field" => { + call = call.sort_field(value.unwrap_or("")); + }, + "search-string" => { + call = call.search_string(value.unwrap_or("")); + }, + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "max-results" => { + call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer")); + }, + "ids" => { + call = call.add_ids(value.unwrap_or("")); + }, + "floodlight-configuration-id" => { + call = call.floodlight_configuration_id(value.unwrap_or("")); + }, + "floodlight-activity-group-type" => { + call = call.floodlight_activity_group_type(value.unwrap_or("")); + }, + "floodlight-activity-group-tag-string" => { + call = call.floodlight_activity_group_tag_string(value.unwrap_or("")); + }, + "floodlight-activity-group-name" => { + call = call.floodlight_activity_group_name(value.unwrap_or("")); + }, + "floodlight-activity-group-ids" => { + call = call.add_floodlight_activity_group_ids(value.unwrap_or("")); + }, + "advertiser-id" => { + call = call.advertiser_id(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["floodlight-activity-group-ids", "search-string", "floodlight-activity-group-name", "sort-field", "floodlight-configuration-id", "ids", "max-results", "advertiser-id", "page-token", "sort-order", "tag-string", "floodlight-activity-group-tag-string", "floodlight-activity-group-type"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _floodlight_activities_patch(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "tag-string" => Some(("tagString", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "secure" => Some(("secure", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "floodlight-activity-group-name" => Some(("floodlightActivityGroupName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "image-tag-enabled" => Some(("imageTagEnabled", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "advertiser-id" => Some(("advertiserId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.kind" => Some(("advertiserIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.value" => Some(("advertiserIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.dimension-name" => Some(("advertiserIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.etag" => Some(("advertiserIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.match-type" => Some(("advertiserIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.id" => Some(("advertiserIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-activity-group-id" => Some(("floodlightActivityGroupId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-activity-group-tag-string" => Some(("floodlightActivityGroupTagString", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "ssl-compliant" => Some(("sslCompliant", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "floodlight-configuration-id-dimension-value.kind" => Some(("floodlightConfigurationIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-configuration-id-dimension-value.value" => Some(("floodlightConfigurationIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-configuration-id-dimension-value.dimension-name" => Some(("floodlightConfigurationIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-configuration-id-dimension-value.etag" => Some(("floodlightConfigurationIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-configuration-id-dimension-value.match-type" => Some(("floodlightConfigurationIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-configuration-id-dimension-value.id" => Some(("floodlightConfigurationIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "cache-busting-type" => Some(("cacheBustingType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "hidden" => Some(("hidden", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "ssl-required" => Some(("sslRequired", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "expected-url" => Some(("expectedUrl", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "tag-format" => Some(("tagFormat", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "subaccount-id" => Some(("subaccountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "notes" => Some(("notes", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-configuration-id" => Some(("floodlightConfigurationId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "user-defined-variable-types" => Some(("userDefinedVariableTypes", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "counting-method" => Some(("countingMethod", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.kind" => Some(("idDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.value" => Some(("idDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.dimension-name" => Some(("idDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.etag" => Some(("idDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.match-type" => Some(("idDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.id" => Some(("idDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-activity-group-type" => Some(("floodlightActivityGroupType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "advertiser-id", "advertiser-id-dimension-value", "cache-busting-type", "counting-method", "dimension-name", "etag", "expected-url", "floodlight-activity-group-id", "floodlight-activity-group-name", "floodlight-activity-group-tag-string", "floodlight-activity-group-type", "floodlight-configuration-id", "floodlight-configuration-id-dimension-value", "hidden", "id", "id-dimension-value", "image-tag-enabled", "kind", "match-type", "name", "notes", "secure", "ssl-compliant", "ssl-required", "subaccount-id", "tag-format", "tag-string", "user-defined-variable-types", "value"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::FloodlightActivity = json::value::from_value(object).unwrap(); + let mut call = self.hub.floodlight_activities().patch(request, opt.value_of("profile-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _floodlight_activities_update(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "tag-string" => Some(("tagString", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "secure" => Some(("secure", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "floodlight-activity-group-name" => Some(("floodlightActivityGroupName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "image-tag-enabled" => Some(("imageTagEnabled", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "advertiser-id" => Some(("advertiserId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.kind" => Some(("advertiserIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.value" => Some(("advertiserIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.dimension-name" => Some(("advertiserIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.etag" => Some(("advertiserIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.match-type" => Some(("advertiserIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.id" => Some(("advertiserIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-activity-group-id" => Some(("floodlightActivityGroupId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-activity-group-tag-string" => Some(("floodlightActivityGroupTagString", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "ssl-compliant" => Some(("sslCompliant", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "floodlight-configuration-id-dimension-value.kind" => Some(("floodlightConfigurationIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-configuration-id-dimension-value.value" => Some(("floodlightConfigurationIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-configuration-id-dimension-value.dimension-name" => Some(("floodlightConfigurationIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-configuration-id-dimension-value.etag" => Some(("floodlightConfigurationIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-configuration-id-dimension-value.match-type" => Some(("floodlightConfigurationIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-configuration-id-dimension-value.id" => Some(("floodlightConfigurationIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "cache-busting-type" => Some(("cacheBustingType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "hidden" => Some(("hidden", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "ssl-required" => Some(("sslRequired", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "expected-url" => Some(("expectedUrl", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "tag-format" => Some(("tagFormat", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "subaccount-id" => Some(("subaccountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "notes" => Some(("notes", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-configuration-id" => Some(("floodlightConfigurationId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "user-defined-variable-types" => Some(("userDefinedVariableTypes", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "counting-method" => Some(("countingMethod", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.kind" => Some(("idDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.value" => Some(("idDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.dimension-name" => Some(("idDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.etag" => Some(("idDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.match-type" => Some(("idDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.id" => Some(("idDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-activity-group-type" => Some(("floodlightActivityGroupType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "advertiser-id", "advertiser-id-dimension-value", "cache-busting-type", "counting-method", "dimension-name", "etag", "expected-url", "floodlight-activity-group-id", "floodlight-activity-group-name", "floodlight-activity-group-tag-string", "floodlight-activity-group-type", "floodlight-configuration-id", "floodlight-configuration-id-dimension-value", "hidden", "id", "id-dimension-value", "image-tag-enabled", "kind", "match-type", "name", "notes", "secure", "ssl-compliant", "ssl-required", "subaccount-id", "tag-format", "tag-string", "user-defined-variable-types", "value"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::FloodlightActivity = json::value::from_value(object).unwrap(); + let mut call = self.hub.floodlight_activities().update(request, opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _floodlight_activity_groups_delete(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.floodlight_activity_groups().delete(opt.value_of("profile-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok(mut response) => { + Ok(()) + } + } + } + } + + fn _floodlight_activity_groups_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.floodlight_activity_groups().get(opt.value_of("profile-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _floodlight_activity_groups_insert(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "subaccount-id" => Some(("subaccountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-configuration-id" => Some(("floodlightConfigurationId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id" => Some(("advertiserId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-configuration-id-dimension-value.kind" => Some(("floodlightConfigurationIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-configuration-id-dimension-value.value" => Some(("floodlightConfigurationIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-configuration-id-dimension-value.dimension-name" => Some(("floodlightConfigurationIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-configuration-id-dimension-value.etag" => Some(("floodlightConfigurationIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-configuration-id-dimension-value.match-type" => Some(("floodlightConfigurationIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-configuration-id-dimension-value.id" => Some(("floodlightConfigurationIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.kind" => Some(("idDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.value" => Some(("idDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.dimension-name" => Some(("idDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.etag" => Some(("idDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.match-type" => Some(("idDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.id" => Some(("idDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.kind" => Some(("advertiserIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.value" => Some(("advertiserIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.dimension-name" => Some(("advertiserIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.etag" => Some(("advertiserIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.match-type" => Some(("advertiserIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.id" => Some(("advertiserIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "tag-string" => Some(("tagString", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "type" => Some(("type", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "advertiser-id", "advertiser-id-dimension-value", "dimension-name", "etag", "floodlight-configuration-id", "floodlight-configuration-id-dimension-value", "id", "id-dimension-value", "kind", "match-type", "name", "subaccount-id", "tag-string", "type", "value"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::FloodlightActivityGroup = json::value::from_value(object).unwrap(); + let mut call = self.hub.floodlight_activity_groups().insert(request, opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _floodlight_activity_groups_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.floodlight_activity_groups().list(opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "type" => { + call = call.type_(value.unwrap_or("")); + }, + "sort-order" => { + call = call.sort_order(value.unwrap_or("")); + }, + "sort-field" => { + call = call.sort_field(value.unwrap_or("")); + }, + "search-string" => { + call = call.search_string(value.unwrap_or("")); + }, + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "max-results" => { + call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer")); + }, + "ids" => { + call = call.add_ids(value.unwrap_or("")); + }, + "floodlight-configuration-id" => { + call = call.floodlight_configuration_id(value.unwrap_or("")); + }, + "advertiser-id" => { + call = call.advertiser_id(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["search-string", "sort-field", "floodlight-configuration-id", "ids", "max-results", "advertiser-id", "page-token", "sort-order", "type"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _floodlight_activity_groups_patch(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "subaccount-id" => Some(("subaccountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-configuration-id" => Some(("floodlightConfigurationId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id" => Some(("advertiserId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-configuration-id-dimension-value.kind" => Some(("floodlightConfigurationIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-configuration-id-dimension-value.value" => Some(("floodlightConfigurationIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-configuration-id-dimension-value.dimension-name" => Some(("floodlightConfigurationIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-configuration-id-dimension-value.etag" => Some(("floodlightConfigurationIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-configuration-id-dimension-value.match-type" => Some(("floodlightConfigurationIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-configuration-id-dimension-value.id" => Some(("floodlightConfigurationIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.kind" => Some(("idDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.value" => Some(("idDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.dimension-name" => Some(("idDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.etag" => Some(("idDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.match-type" => Some(("idDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.id" => Some(("idDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.kind" => Some(("advertiserIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.value" => Some(("advertiserIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.dimension-name" => Some(("advertiserIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.etag" => Some(("advertiserIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.match-type" => Some(("advertiserIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.id" => Some(("advertiserIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "tag-string" => Some(("tagString", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "type" => Some(("type", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "advertiser-id", "advertiser-id-dimension-value", "dimension-name", "etag", "floodlight-configuration-id", "floodlight-configuration-id-dimension-value", "id", "id-dimension-value", "kind", "match-type", "name", "subaccount-id", "tag-string", "type", "value"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::FloodlightActivityGroup = json::value::from_value(object).unwrap(); + let mut call = self.hub.floodlight_activity_groups().patch(request, opt.value_of("profile-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _floodlight_activity_groups_update(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "subaccount-id" => Some(("subaccountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-configuration-id" => Some(("floodlightConfigurationId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id" => Some(("advertiserId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-configuration-id-dimension-value.kind" => Some(("floodlightConfigurationIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-configuration-id-dimension-value.value" => Some(("floodlightConfigurationIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-configuration-id-dimension-value.dimension-name" => Some(("floodlightConfigurationIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-configuration-id-dimension-value.etag" => Some(("floodlightConfigurationIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-configuration-id-dimension-value.match-type" => Some(("floodlightConfigurationIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-configuration-id-dimension-value.id" => Some(("floodlightConfigurationIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.kind" => Some(("idDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.value" => Some(("idDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.dimension-name" => Some(("idDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.etag" => Some(("idDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.match-type" => Some(("idDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.id" => Some(("idDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.kind" => Some(("advertiserIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.value" => Some(("advertiserIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.dimension-name" => Some(("advertiserIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.etag" => Some(("advertiserIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.match-type" => Some(("advertiserIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.id" => Some(("advertiserIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "tag-string" => Some(("tagString", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "type" => Some(("type", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "advertiser-id", "advertiser-id-dimension-value", "dimension-name", "etag", "floodlight-configuration-id", "floodlight-configuration-id-dimension-value", "id", "id-dimension-value", "kind", "match-type", "name", "subaccount-id", "tag-string", "type", "value"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::FloodlightActivityGroup = json::value::from_value(object).unwrap(); + let mut call = self.hub.floodlight_activity_groups().update(request, opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _floodlight_configurations_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.floodlight_configurations().get(opt.value_of("profile-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _floodlight_configurations_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.floodlight_configurations().list(opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "ids" => { + call = call.add_ids(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["ids"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _floodlight_configurations_patch(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "natural-search-conversion-attribution-option" => Some(("naturalSearchConversionAttributionOption", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "exposure-to-conversion-enabled" => Some(("exposureToConversionEnabled", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "subaccount-id" => Some(("subaccountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "analytics-data-sharing-enabled" => Some(("analyticsDataSharingEnabled", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "lookback-configuration.click-duration" => Some(("lookbackConfiguration.clickDuration", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "lookback-configuration.post-impression-activities-duration" => Some(("lookbackConfiguration.postImpressionActivitiesDuration", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "first-day-of-week" => Some(("firstDayOfWeek", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "standard-variable-types" => Some(("standardVariableTypes", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "omniture-settings.omniture-cost-data-enabled" => Some(("omnitureSettings.omnitureCostDataEnabled", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "omniture-settings.omniture-integration-enabled" => Some(("omnitureSettings.omnitureIntegrationEnabled", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "advertiser-id" => Some(("advertiserId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "tag-settings.dynamic-tag-enabled" => Some(("tagSettings.dynamicTagEnabled", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "tag-settings.image-tag-enabled" => Some(("tagSettings.imageTagEnabled", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "in-app-attribution-tracking-enabled" => Some(("inAppAttributionTrackingEnabled", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "id-dimension-value.kind" => Some(("idDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.value" => Some(("idDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.dimension-name" => Some(("idDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.etag" => Some(("idDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.match-type" => Some(("idDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.id" => Some(("idDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.kind" => Some(("advertiserIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.value" => Some(("advertiserIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.dimension-name" => Some(("advertiserIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.etag" => Some(("advertiserIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.match-type" => Some(("advertiserIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.id" => Some(("advertiserIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "ssl-required" => Some(("sslRequired", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "advertiser-id", "advertiser-id-dimension-value", "analytics-data-sharing-enabled", "click-duration", "dimension-name", "dynamic-tag-enabled", "etag", "exposure-to-conversion-enabled", "first-day-of-week", "id", "id-dimension-value", "image-tag-enabled", "in-app-attribution-tracking-enabled", "kind", "lookback-configuration", "match-type", "natural-search-conversion-attribution-option", "omniture-cost-data-enabled", "omniture-integration-enabled", "omniture-settings", "post-impression-activities-duration", "ssl-required", "standard-variable-types", "subaccount-id", "tag-settings", "value"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::FloodlightConfiguration = json::value::from_value(object).unwrap(); + let mut call = self.hub.floodlight_configurations().patch(request, opt.value_of("profile-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _floodlight_configurations_update(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "natural-search-conversion-attribution-option" => Some(("naturalSearchConversionAttributionOption", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "exposure-to-conversion-enabled" => Some(("exposureToConversionEnabled", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "subaccount-id" => Some(("subaccountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "analytics-data-sharing-enabled" => Some(("analyticsDataSharingEnabled", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "lookback-configuration.click-duration" => Some(("lookbackConfiguration.clickDuration", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "lookback-configuration.post-impression-activities-duration" => Some(("lookbackConfiguration.postImpressionActivitiesDuration", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "first-day-of-week" => Some(("firstDayOfWeek", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "standard-variable-types" => Some(("standardVariableTypes", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "omniture-settings.omniture-cost-data-enabled" => Some(("omnitureSettings.omnitureCostDataEnabled", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "omniture-settings.omniture-integration-enabled" => Some(("omnitureSettings.omnitureIntegrationEnabled", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "advertiser-id" => Some(("advertiserId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "tag-settings.dynamic-tag-enabled" => Some(("tagSettings.dynamicTagEnabled", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "tag-settings.image-tag-enabled" => Some(("tagSettings.imageTagEnabled", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "in-app-attribution-tracking-enabled" => Some(("inAppAttributionTrackingEnabled", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "id-dimension-value.kind" => Some(("idDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.value" => Some(("idDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.dimension-name" => Some(("idDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.etag" => Some(("idDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.match-type" => Some(("idDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.id" => Some(("idDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.kind" => Some(("advertiserIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.value" => Some(("advertiserIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.dimension-name" => Some(("advertiserIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.etag" => Some(("advertiserIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.match-type" => Some(("advertiserIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.id" => Some(("advertiserIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "ssl-required" => Some(("sslRequired", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "advertiser-id", "advertiser-id-dimension-value", "analytics-data-sharing-enabled", "click-duration", "dimension-name", "dynamic-tag-enabled", "etag", "exposure-to-conversion-enabled", "first-day-of-week", "id", "id-dimension-value", "image-tag-enabled", "in-app-attribution-tracking-enabled", "kind", "lookback-configuration", "match-type", "natural-search-conversion-attribution-option", "omniture-cost-data-enabled", "omniture-integration-enabled", "omniture-settings", "post-impression-activities-duration", "ssl-required", "standard-variable-types", "subaccount-id", "tag-settings", "value"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::FloodlightConfiguration = json::value::from_value(object).unwrap(); + let mut call = self.hub.floodlight_configurations().update(request, opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _inventory_items_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.inventory_items().get(opt.value_of("profile-id").unwrap_or(""), opt.value_of("project-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _inventory_items_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.inventory_items().list(opt.value_of("profile-id").unwrap_or(""), opt.value_of("project-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "sort-order" => { + call = call.sort_order(value.unwrap_or("")); + }, + "sort-field" => { + call = call.sort_field(value.unwrap_or("")); + }, + "site-id" => { + call = call.add_site_id(value.unwrap_or("")); + }, + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "order-id" => { + call = call.add_order_id(value.unwrap_or("")); + }, + "max-results" => { + call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer")); + }, + "in-plan" => { + call = call.in_plan(arg_from_str(value.unwrap_or("false"), err, "in-plan", "boolean")); + }, + "ids" => { + call = call.add_ids(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["order-id", "sort-field", "ids", "max-results", "page-token", "in-plan", "site-id", "sort-order"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _landing_pages_delete(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.landing_pages().delete(opt.value_of("profile-id").unwrap_or(""), opt.value_of("campaign-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok(mut response) => { + Ok(()) + } + } + } + } + + fn _landing_pages_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.landing_pages().get(opt.value_of("profile-id").unwrap_or(""), opt.value_of("campaign-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _landing_pages_insert(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "default" => Some(("default", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "url" => Some(("url", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["default", "id", "kind", "name", "url"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::LandingPage = json::value::from_value(object).unwrap(); + let mut call = self.hub.landing_pages().insert(request, opt.value_of("profile-id").unwrap_or(""), opt.value_of("campaign-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _landing_pages_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.landing_pages().list(opt.value_of("profile-id").unwrap_or(""), opt.value_of("campaign-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _landing_pages_patch(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "default" => Some(("default", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "url" => Some(("url", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["default", "id", "kind", "name", "url"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::LandingPage = json::value::from_value(object).unwrap(); + let mut call = self.hub.landing_pages().patch(request, opt.value_of("profile-id").unwrap_or(""), opt.value_of("campaign-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _landing_pages_update(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "default" => Some(("default", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "url" => Some(("url", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["default", "id", "kind", "name", "url"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::LandingPage = json::value::from_value(object).unwrap(); + let mut call = self.hub.landing_pages().update(request, opt.value_of("profile-id").unwrap_or(""), opt.value_of("campaign-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _metros_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.metros().list(opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _mobile_carriers_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.mobile_carriers().get(opt.value_of("profile-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _mobile_carriers_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.mobile_carriers().list(opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _operating_system_versions_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.operating_system_versions().get(opt.value_of("profile-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _operating_system_versions_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.operating_system_versions().list(opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _operating_systems_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.operating_systems().get(opt.value_of("profile-id").unwrap_or(""), opt.value_of("dart-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _operating_systems_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.operating_systems().list(opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _order_documents_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.order_documents().get(opt.value_of("profile-id").unwrap_or(""), opt.value_of("project-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _order_documents_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.order_documents().list(opt.value_of("profile-id").unwrap_or(""), opt.value_of("project-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "sort-order" => { + call = call.sort_order(value.unwrap_or("")); + }, + "sort-field" => { + call = call.sort_field(value.unwrap_or("")); + }, + "site-id" => { + call = call.add_site_id(value.unwrap_or("")); + }, + "search-string" => { + call = call.search_string(value.unwrap_or("")); + }, + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "order-id" => { + call = call.add_order_id(value.unwrap_or("")); + }, + "max-results" => { + call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer")); + }, + "ids" => { + call = call.add_ids(value.unwrap_or("")); + }, + "approved" => { + call = call.approved(arg_from_str(value.unwrap_or("false"), err, "approved", "boolean")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["order-id", "search-string", "sort-field", "ids", "max-results", "page-token", "site-id", "sort-order", "approved"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _orders_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.orders().get(opt.value_of("profile-id").unwrap_or(""), opt.value_of("project-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _orders_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.orders().list(opt.value_of("profile-id").unwrap_or(""), opt.value_of("project-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "sort-order" => { + call = call.sort_order(value.unwrap_or("")); + }, + "sort-field" => { + call = call.sort_field(value.unwrap_or("")); + }, + "site-id" => { + call = call.add_site_id(value.unwrap_or("")); + }, + "search-string" => { + call = call.search_string(value.unwrap_or("")); + }, + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "max-results" => { + call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer")); + }, + "ids" => { + call = call.add_ids(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["search-string", "sort-field", "ids", "max-results", "page-token", "site-id", "sort-order"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _placement_groups_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.placement_groups().get(opt.value_of("profile-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _placement_groups_insert(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "comment" => Some(("comment", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "primary-placement-id" => Some(("primaryPlacementId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id" => Some(("campaignId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "directory-site-id-dimension-value.kind" => Some(("directorySiteIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "directory-site-id-dimension-value.value" => Some(("directorySiteIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "directory-site-id-dimension-value.dimension-name" => Some(("directorySiteIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "directory-site-id-dimension-value.etag" => Some(("directorySiteIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "directory-site-id-dimension-value.match-type" => Some(("directorySiteIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "directory-site-id-dimension-value.id" => Some(("directorySiteIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id" => Some(("advertiserId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "directory-site-id" => Some(("directorySiteId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "placement-group-type" => Some(("placementGroupType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.kind" => Some(("advertiserIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.value" => Some(("advertiserIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.dimension-name" => Some(("advertiserIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.etag" => Some(("advertiserIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.match-type" => Some(("advertiserIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.id" => Some(("advertiserIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "archived" => Some(("archived", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "child-placement-ids" => Some(("childPlacementIds", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "content-category-id" => Some(("contentCategoryId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "external-id" => Some(("externalId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.kind" => Some(("idDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.value" => Some(("idDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.dimension-name" => Some(("idDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.etag" => Some(("idDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.match-type" => Some(("idDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.id" => Some(("idDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "primary-placement-id-dimension-value.kind" => Some(("primaryPlacementIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "primary-placement-id-dimension-value.value" => Some(("primaryPlacementIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "primary-placement-id-dimension-value.dimension-name" => Some(("primaryPlacementIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "primary-placement-id-dimension-value.etag" => Some(("primaryPlacementIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "primary-placement-id-dimension-value.match-type" => Some(("primaryPlacementIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "primary-placement-id-dimension-value.id" => Some(("primaryPlacementIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.kind" => Some(("campaignIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.value" => Some(("campaignIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.dimension-name" => Some(("campaignIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.etag" => Some(("campaignIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.match-type" => Some(("campaignIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.id" => Some(("campaignIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "create-info.time" => Some(("createInfo.time", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "site-id" => Some(("siteId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "site-id-dimension-value.kind" => Some(("siteIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "site-id-dimension-value.value" => Some(("siteIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "site-id-dimension-value.dimension-name" => Some(("siteIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "site-id-dimension-value.etag" => Some(("siteIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "site-id-dimension-value.match-type" => Some(("siteIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "site-id-dimension-value.id" => Some(("siteIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "placement-strategy-id" => Some(("placementStrategyId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "subaccount-id" => Some(("subaccountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "last-modified-info.time" => Some(("lastModifiedInfo.time", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "pricing-schedule.start-date" => Some(("pricingSchedule.startDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "pricing-schedule.end-date" => Some(("pricingSchedule.endDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "pricing-schedule.flighted" => Some(("pricingSchedule.flighted", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "pricing-schedule.disregard-overdelivery" => Some(("pricingSchedule.disregardOverdelivery", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "pricing-schedule.pricing-type" => Some(("pricingSchedule.pricingType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "pricing-schedule.cap-cost-option" => Some(("pricingSchedule.capCostOption", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "pricing-schedule.testing-start-date" => Some(("pricingSchedule.testingStartDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "pricing-schedule.floodlight-activity-id" => Some(("pricingSchedule.floodlightActivityId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "advertiser-id", "advertiser-id-dimension-value", "archived", "campaign-id", "campaign-id-dimension-value", "cap-cost-option", "child-placement-ids", "comment", "content-category-id", "create-info", "dimension-name", "directory-site-id", "directory-site-id-dimension-value", "disregard-overdelivery", "end-date", "etag", "external-id", "flighted", "floodlight-activity-id", "id", "id-dimension-value", "kind", "last-modified-info", "match-type", "name", "placement-group-type", "placement-strategy-id", "pricing-schedule", "pricing-type", "primary-placement-id", "primary-placement-id-dimension-value", "site-id", "site-id-dimension-value", "start-date", "subaccount-id", "testing-start-date", "time", "value"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::PlacementGroup = json::value::from_value(object).unwrap(); + let mut call = self.hub.placement_groups().insert(request, opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _placement_groups_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.placement_groups().list(opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "sort-order" => { + call = call.sort_order(value.unwrap_or("")); + }, + "sort-field" => { + call = call.sort_field(value.unwrap_or("")); + }, + "site-ids" => { + call = call.add_site_ids(value.unwrap_or("")); + }, + "search-string" => { + call = call.search_string(value.unwrap_or("")); + }, + "pricing-types" => { + call = call.add_pricing_types(value.unwrap_or("")); + }, + "placement-strategy-ids" => { + call = call.add_placement_strategy_ids(value.unwrap_or("")); + }, + "placement-group-type" => { + call = call.placement_group_type(value.unwrap_or("")); + }, + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "min-start-date" => { + call = call.min_start_date(value.unwrap_or("")); + }, + "min-end-date" => { + call = call.min_end_date(value.unwrap_or("")); + }, + "max-start-date" => { + call = call.max_start_date(value.unwrap_or("")); + }, + "max-results" => { + call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer")); + }, + "max-end-date" => { + call = call.max_end_date(value.unwrap_or("")); + }, + "ids" => { + call = call.add_ids(value.unwrap_or("")); + }, + "directory-site-ids" => { + call = call.add_directory_site_ids(value.unwrap_or("")); + }, + "content-category-ids" => { + call = call.add_content_category_ids(value.unwrap_or("")); + }, + "campaign-ids" => { + call = call.add_campaign_ids(value.unwrap_or("")); + }, + "archived" => { + call = call.archived(arg_from_str(value.unwrap_or("false"), err, "archived", "boolean")); + }, + "advertiser-ids" => { + call = call.add_advertiser_ids(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["placement-strategy-ids", "site-ids", "search-string", "min-end-date", "directory-site-ids", "sort-field", "advertiser-ids", "archived", "ids", "max-results", "min-start-date", "page-token", "max-start-date", "sort-order", "placement-group-type", "pricing-types", "content-category-ids", "campaign-ids", "max-end-date"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _placement_groups_patch(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "comment" => Some(("comment", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "primary-placement-id" => Some(("primaryPlacementId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id" => Some(("campaignId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "directory-site-id-dimension-value.kind" => Some(("directorySiteIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "directory-site-id-dimension-value.value" => Some(("directorySiteIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "directory-site-id-dimension-value.dimension-name" => Some(("directorySiteIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "directory-site-id-dimension-value.etag" => Some(("directorySiteIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "directory-site-id-dimension-value.match-type" => Some(("directorySiteIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "directory-site-id-dimension-value.id" => Some(("directorySiteIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id" => Some(("advertiserId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "directory-site-id" => Some(("directorySiteId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "placement-group-type" => Some(("placementGroupType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.kind" => Some(("advertiserIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.value" => Some(("advertiserIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.dimension-name" => Some(("advertiserIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.etag" => Some(("advertiserIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.match-type" => Some(("advertiserIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.id" => Some(("advertiserIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "archived" => Some(("archived", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "child-placement-ids" => Some(("childPlacementIds", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "content-category-id" => Some(("contentCategoryId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "external-id" => Some(("externalId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.kind" => Some(("idDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.value" => Some(("idDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.dimension-name" => Some(("idDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.etag" => Some(("idDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.match-type" => Some(("idDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.id" => Some(("idDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "primary-placement-id-dimension-value.kind" => Some(("primaryPlacementIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "primary-placement-id-dimension-value.value" => Some(("primaryPlacementIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "primary-placement-id-dimension-value.dimension-name" => Some(("primaryPlacementIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "primary-placement-id-dimension-value.etag" => Some(("primaryPlacementIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "primary-placement-id-dimension-value.match-type" => Some(("primaryPlacementIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "primary-placement-id-dimension-value.id" => Some(("primaryPlacementIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.kind" => Some(("campaignIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.value" => Some(("campaignIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.dimension-name" => Some(("campaignIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.etag" => Some(("campaignIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.match-type" => Some(("campaignIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.id" => Some(("campaignIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "create-info.time" => Some(("createInfo.time", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "site-id" => Some(("siteId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "site-id-dimension-value.kind" => Some(("siteIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "site-id-dimension-value.value" => Some(("siteIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "site-id-dimension-value.dimension-name" => Some(("siteIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "site-id-dimension-value.etag" => Some(("siteIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "site-id-dimension-value.match-type" => Some(("siteIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "site-id-dimension-value.id" => Some(("siteIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "placement-strategy-id" => Some(("placementStrategyId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "subaccount-id" => Some(("subaccountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "last-modified-info.time" => Some(("lastModifiedInfo.time", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "pricing-schedule.start-date" => Some(("pricingSchedule.startDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "pricing-schedule.end-date" => Some(("pricingSchedule.endDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "pricing-schedule.flighted" => Some(("pricingSchedule.flighted", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "pricing-schedule.disregard-overdelivery" => Some(("pricingSchedule.disregardOverdelivery", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "pricing-schedule.pricing-type" => Some(("pricingSchedule.pricingType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "pricing-schedule.cap-cost-option" => Some(("pricingSchedule.capCostOption", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "pricing-schedule.testing-start-date" => Some(("pricingSchedule.testingStartDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "pricing-schedule.floodlight-activity-id" => Some(("pricingSchedule.floodlightActivityId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "advertiser-id", "advertiser-id-dimension-value", "archived", "campaign-id", "campaign-id-dimension-value", "cap-cost-option", "child-placement-ids", "comment", "content-category-id", "create-info", "dimension-name", "directory-site-id", "directory-site-id-dimension-value", "disregard-overdelivery", "end-date", "etag", "external-id", "flighted", "floodlight-activity-id", "id", "id-dimension-value", "kind", "last-modified-info", "match-type", "name", "placement-group-type", "placement-strategy-id", "pricing-schedule", "pricing-type", "primary-placement-id", "primary-placement-id-dimension-value", "site-id", "site-id-dimension-value", "start-date", "subaccount-id", "testing-start-date", "time", "value"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::PlacementGroup = json::value::from_value(object).unwrap(); + let mut call = self.hub.placement_groups().patch(request, opt.value_of("profile-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _placement_groups_update(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "comment" => Some(("comment", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "primary-placement-id" => Some(("primaryPlacementId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id" => Some(("campaignId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "directory-site-id-dimension-value.kind" => Some(("directorySiteIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "directory-site-id-dimension-value.value" => Some(("directorySiteIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "directory-site-id-dimension-value.dimension-name" => Some(("directorySiteIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "directory-site-id-dimension-value.etag" => Some(("directorySiteIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "directory-site-id-dimension-value.match-type" => Some(("directorySiteIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "directory-site-id-dimension-value.id" => Some(("directorySiteIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id" => Some(("advertiserId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "directory-site-id" => Some(("directorySiteId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "placement-group-type" => Some(("placementGroupType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.kind" => Some(("advertiserIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.value" => Some(("advertiserIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.dimension-name" => Some(("advertiserIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.etag" => Some(("advertiserIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.match-type" => Some(("advertiserIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.id" => Some(("advertiserIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "archived" => Some(("archived", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "child-placement-ids" => Some(("childPlacementIds", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "content-category-id" => Some(("contentCategoryId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "external-id" => Some(("externalId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.kind" => Some(("idDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.value" => Some(("idDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.dimension-name" => Some(("idDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.etag" => Some(("idDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.match-type" => Some(("idDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.id" => Some(("idDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "primary-placement-id-dimension-value.kind" => Some(("primaryPlacementIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "primary-placement-id-dimension-value.value" => Some(("primaryPlacementIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "primary-placement-id-dimension-value.dimension-name" => Some(("primaryPlacementIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "primary-placement-id-dimension-value.etag" => Some(("primaryPlacementIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "primary-placement-id-dimension-value.match-type" => Some(("primaryPlacementIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "primary-placement-id-dimension-value.id" => Some(("primaryPlacementIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.kind" => Some(("campaignIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.value" => Some(("campaignIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.dimension-name" => Some(("campaignIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.etag" => Some(("campaignIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.match-type" => Some(("campaignIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.id" => Some(("campaignIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "create-info.time" => Some(("createInfo.time", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "site-id" => Some(("siteId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "site-id-dimension-value.kind" => Some(("siteIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "site-id-dimension-value.value" => Some(("siteIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "site-id-dimension-value.dimension-name" => Some(("siteIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "site-id-dimension-value.etag" => Some(("siteIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "site-id-dimension-value.match-type" => Some(("siteIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "site-id-dimension-value.id" => Some(("siteIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "placement-strategy-id" => Some(("placementStrategyId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "subaccount-id" => Some(("subaccountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "last-modified-info.time" => Some(("lastModifiedInfo.time", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "pricing-schedule.start-date" => Some(("pricingSchedule.startDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "pricing-schedule.end-date" => Some(("pricingSchedule.endDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "pricing-schedule.flighted" => Some(("pricingSchedule.flighted", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "pricing-schedule.disregard-overdelivery" => Some(("pricingSchedule.disregardOverdelivery", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "pricing-schedule.pricing-type" => Some(("pricingSchedule.pricingType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "pricing-schedule.cap-cost-option" => Some(("pricingSchedule.capCostOption", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "pricing-schedule.testing-start-date" => Some(("pricingSchedule.testingStartDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "pricing-schedule.floodlight-activity-id" => Some(("pricingSchedule.floodlightActivityId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "advertiser-id", "advertiser-id-dimension-value", "archived", "campaign-id", "campaign-id-dimension-value", "cap-cost-option", "child-placement-ids", "comment", "content-category-id", "create-info", "dimension-name", "directory-site-id", "directory-site-id-dimension-value", "disregard-overdelivery", "end-date", "etag", "external-id", "flighted", "floodlight-activity-id", "id", "id-dimension-value", "kind", "last-modified-info", "match-type", "name", "placement-group-type", "placement-strategy-id", "pricing-schedule", "pricing-type", "primary-placement-id", "primary-placement-id-dimension-value", "site-id", "site-id-dimension-value", "start-date", "subaccount-id", "testing-start-date", "time", "value"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::PlacementGroup = json::value::from_value(object).unwrap(); + let mut call = self.hub.placement_groups().update(request, opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _placement_strategies_delete(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.placement_strategies().delete(opt.value_of("profile-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok(mut response) => { + Ok(()) + } + } + } + } + + fn _placement_strategies_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.placement_strategies().get(opt.value_of("profile-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _placement_strategies_insert(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "id", "kind", "name"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::PlacementStrategy = json::value::from_value(object).unwrap(); + let mut call = self.hub.placement_strategies().insert(request, opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _placement_strategies_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.placement_strategies().list(opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "sort-order" => { + call = call.sort_order(value.unwrap_or("")); + }, + "sort-field" => { + call = call.sort_field(value.unwrap_or("")); + }, + "search-string" => { + call = call.search_string(value.unwrap_or("")); + }, + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "max-results" => { + call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer")); + }, + "ids" => { + call = call.add_ids(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["search-string", "sort-field", "ids", "max-results", "page-token", "sort-order"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _placement_strategies_patch(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "id", "kind", "name"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::PlacementStrategy = json::value::from_value(object).unwrap(); + let mut call = self.hub.placement_strategies().patch(request, opt.value_of("profile-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _placement_strategies_update(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "id", "kind", "name"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::PlacementStrategy = json::value::from_value(object).unwrap(); + let mut call = self.hub.placement_strategies().update(request, opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _placements_generatetags(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.placements().generatetags(opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "tag-formats" => { + call = call.add_tag_formats(value.unwrap_or("")); + }, + "placement-ids" => { + call = call.add_placement_ids(value.unwrap_or("")); + }, + "campaign-id" => { + call = call.campaign_id(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["tag-formats", "placement-ids", "campaign-id"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _placements_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.placements().get(opt.value_of("profile-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _placements_insert(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "comment" => Some(("comment", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id" => Some(("campaignId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "payment-source" => Some(("paymentSource", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "directory-site-id-dimension-value.kind" => Some(("directorySiteIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "directory-site-id-dimension-value.value" => Some(("directorySiteIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "directory-site-id-dimension-value.dimension-name" => Some(("directorySiteIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "directory-site-id-dimension-value.etag" => Some(("directorySiteIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "directory-site-id-dimension-value.match-type" => Some(("directorySiteIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "directory-site-id-dimension-value.id" => Some(("directorySiteIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id" => Some(("advertiserId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "key-name" => Some(("keyName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "directory-site-id" => Some(("directorySiteId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.kind" => Some(("advertiserIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.value" => Some(("advertiserIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.dimension-name" => Some(("advertiserIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.etag" => Some(("advertiserIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.match-type" => Some(("advertiserIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.id" => Some(("advertiserIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "archived" => Some(("archived", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "publisher-update-info.time" => Some(("publisherUpdateInfo.time", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "tag-formats" => Some(("tagFormats", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "payment-approved" => Some(("paymentApproved", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "tag-setting.include-click-through-urls" => Some(("tagSetting.includeClickThroughUrls", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "tag-setting.include-click-tracking" => Some(("tagSetting.includeClickTracking", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "tag-setting.additional-key-values" => Some(("tagSetting.additionalKeyValues", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "tag-setting.keyword-option" => Some(("tagSetting.keywordOption", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "content-category-id" => Some(("contentCategoryId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "external-id" => Some(("externalId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.kind" => Some(("idDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.value" => Some(("idDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.dimension-name" => Some(("idDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.etag" => Some(("idDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.match-type" => Some(("idDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.id" => Some(("idDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "size.width" => Some(("size.width", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "size.kind" => Some(("size.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "size.iab" => Some(("size.iab", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "size.id" => Some(("size.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "size.height" => Some(("size.height", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "ssl-required" => Some(("sslRequired", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "status" => Some(("status", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.kind" => Some(("campaignIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.value" => Some(("campaignIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.dimension-name" => Some(("campaignIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.etag" => Some(("campaignIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.match-type" => Some(("campaignIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.id" => Some(("campaignIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "primary" => Some(("primary", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "placement-group-id" => Some(("placementGroupId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "create-info.time" => Some(("createInfo.time", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "site-id" => Some(("siteId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "site-id-dimension-value.kind" => Some(("siteIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "site-id-dimension-value.value" => Some(("siteIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "site-id-dimension-value.dimension-name" => Some(("siteIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "site-id-dimension-value.etag" => Some(("siteIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "site-id-dimension-value.match-type" => Some(("siteIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "site-id-dimension-value.id" => Some(("siteIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "compatibility" => Some(("compatibility", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "placement-strategy-id" => Some(("placementStrategyId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "placement-group-id-dimension-value.kind" => Some(("placementGroupIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "placement-group-id-dimension-value.value" => Some(("placementGroupIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "placement-group-id-dimension-value.dimension-name" => Some(("placementGroupIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "placement-group-id-dimension-value.etag" => Some(("placementGroupIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "placement-group-id-dimension-value.match-type" => Some(("placementGroupIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "placement-group-id-dimension-value.id" => Some(("placementGroupIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "subaccount-id" => Some(("subaccountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "lookback-configuration.click-duration" => Some(("lookbackConfiguration.clickDuration", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "lookback-configuration.post-impression-activities-duration" => Some(("lookbackConfiguration.postImpressionActivitiesDuration", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "last-modified-info.time" => Some(("lastModifiedInfo.time", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "pricing-schedule.start-date" => Some(("pricingSchedule.startDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "pricing-schedule.end-date" => Some(("pricingSchedule.endDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "pricing-schedule.flighted" => Some(("pricingSchedule.flighted", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "pricing-schedule.disregard-overdelivery" => Some(("pricingSchedule.disregardOverdelivery", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "pricing-schedule.pricing-type" => Some(("pricingSchedule.pricingType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "pricing-schedule.cap-cost-option" => Some(("pricingSchedule.capCostOption", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "pricing-schedule.testing-start-date" => Some(("pricingSchedule.testingStartDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "pricing-schedule.floodlight-activity-id" => Some(("pricingSchedule.floodlightActivityId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "additional-key-values", "advertiser-id", "advertiser-id-dimension-value", "archived", "campaign-id", "campaign-id-dimension-value", "cap-cost-option", "click-duration", "comment", "compatibility", "content-category-id", "create-info", "dimension-name", "directory-site-id", "directory-site-id-dimension-value", "disregard-overdelivery", "end-date", "etag", "external-id", "flighted", "floodlight-activity-id", "height", "iab", "id", "id-dimension-value", "include-click-through-urls", "include-click-tracking", "key-name", "keyword-option", "kind", "last-modified-info", "lookback-configuration", "match-type", "name", "payment-approved", "payment-source", "placement-group-id", "placement-group-id-dimension-value", "placement-strategy-id", "post-impression-activities-duration", "pricing-schedule", "pricing-type", "primary", "publisher-update-info", "site-id", "site-id-dimension-value", "size", "ssl-required", "start-date", "status", "subaccount-id", "tag-formats", "tag-setting", "testing-start-date", "time", "value", "width"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::Placement = json::value::from_value(object).unwrap(); + let mut call = self.hub.placements().insert(request, opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _placements_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.placements().list(opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "sort-order" => { + call = call.sort_order(value.unwrap_or("")); + }, + "sort-field" => { + call = call.sort_field(value.unwrap_or("")); + }, + "size-ids" => { + call = call.add_size_ids(value.unwrap_or("")); + }, + "site-ids" => { + call = call.add_site_ids(value.unwrap_or("")); + }, + "search-string" => { + call = call.search_string(value.unwrap_or("")); + }, + "pricing-types" => { + call = call.add_pricing_types(value.unwrap_or("")); + }, + "placement-strategy-ids" => { + call = call.add_placement_strategy_ids(value.unwrap_or("")); + }, + "payment-source" => { + call = call.payment_source(value.unwrap_or("")); + }, + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "min-start-date" => { + call = call.min_start_date(value.unwrap_or("")); + }, + "min-end-date" => { + call = call.min_end_date(value.unwrap_or("")); + }, + "max-start-date" => { + call = call.max_start_date(value.unwrap_or("")); + }, + "max-results" => { + call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer")); + }, + "max-end-date" => { + call = call.max_end_date(value.unwrap_or("")); + }, + "ids" => { + call = call.add_ids(value.unwrap_or("")); + }, + "group-ids" => { + call = call.add_group_ids(value.unwrap_or("")); + }, + "directory-site-ids" => { + call = call.add_directory_site_ids(value.unwrap_or("")); + }, + "content-category-ids" => { + call = call.add_content_category_ids(value.unwrap_or("")); + }, + "compatibilities" => { + call = call.add_compatibilities(value.unwrap_or("")); + }, + "campaign-ids" => { + call = call.add_campaign_ids(value.unwrap_or("")); + }, + "archived" => { + call = call.archived(arg_from_str(value.unwrap_or("false"), err, "archived", "boolean")); + }, + "advertiser-ids" => { + call = call.add_advertiser_ids(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["site-ids", "payment-source", "pricing-types", "campaign-ids", "archived", "advertiser-ids", "size-ids", "page-token", "max-start-date", "sort-order", "max-end-date", "placement-strategy-ids", "content-category-ids", "max-results", "min-start-date", "compatibilities", "search-string", "min-end-date", "directory-site-ids", "sort-field", "ids", "group-ids"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _placements_patch(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "comment" => Some(("comment", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id" => Some(("campaignId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "payment-source" => Some(("paymentSource", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "directory-site-id-dimension-value.kind" => Some(("directorySiteIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "directory-site-id-dimension-value.value" => Some(("directorySiteIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "directory-site-id-dimension-value.dimension-name" => Some(("directorySiteIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "directory-site-id-dimension-value.etag" => Some(("directorySiteIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "directory-site-id-dimension-value.match-type" => Some(("directorySiteIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "directory-site-id-dimension-value.id" => Some(("directorySiteIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id" => Some(("advertiserId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "key-name" => Some(("keyName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "directory-site-id" => Some(("directorySiteId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.kind" => Some(("advertiserIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.value" => Some(("advertiserIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.dimension-name" => Some(("advertiserIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.etag" => Some(("advertiserIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.match-type" => Some(("advertiserIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.id" => Some(("advertiserIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "archived" => Some(("archived", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "publisher-update-info.time" => Some(("publisherUpdateInfo.time", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "tag-formats" => Some(("tagFormats", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "payment-approved" => Some(("paymentApproved", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "tag-setting.include-click-through-urls" => Some(("tagSetting.includeClickThroughUrls", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "tag-setting.include-click-tracking" => Some(("tagSetting.includeClickTracking", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "tag-setting.additional-key-values" => Some(("tagSetting.additionalKeyValues", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "tag-setting.keyword-option" => Some(("tagSetting.keywordOption", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "content-category-id" => Some(("contentCategoryId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "external-id" => Some(("externalId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.kind" => Some(("idDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.value" => Some(("idDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.dimension-name" => Some(("idDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.etag" => Some(("idDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.match-type" => Some(("idDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.id" => Some(("idDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "size.width" => Some(("size.width", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "size.kind" => Some(("size.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "size.iab" => Some(("size.iab", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "size.id" => Some(("size.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "size.height" => Some(("size.height", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "ssl-required" => Some(("sslRequired", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "status" => Some(("status", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.kind" => Some(("campaignIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.value" => Some(("campaignIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.dimension-name" => Some(("campaignIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.etag" => Some(("campaignIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.match-type" => Some(("campaignIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.id" => Some(("campaignIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "primary" => Some(("primary", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "placement-group-id" => Some(("placementGroupId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "create-info.time" => Some(("createInfo.time", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "site-id" => Some(("siteId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "site-id-dimension-value.kind" => Some(("siteIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "site-id-dimension-value.value" => Some(("siteIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "site-id-dimension-value.dimension-name" => Some(("siteIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "site-id-dimension-value.etag" => Some(("siteIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "site-id-dimension-value.match-type" => Some(("siteIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "site-id-dimension-value.id" => Some(("siteIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "compatibility" => Some(("compatibility", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "placement-strategy-id" => Some(("placementStrategyId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "placement-group-id-dimension-value.kind" => Some(("placementGroupIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "placement-group-id-dimension-value.value" => Some(("placementGroupIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "placement-group-id-dimension-value.dimension-name" => Some(("placementGroupIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "placement-group-id-dimension-value.etag" => Some(("placementGroupIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "placement-group-id-dimension-value.match-type" => Some(("placementGroupIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "placement-group-id-dimension-value.id" => Some(("placementGroupIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "subaccount-id" => Some(("subaccountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "lookback-configuration.click-duration" => Some(("lookbackConfiguration.clickDuration", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "lookback-configuration.post-impression-activities-duration" => Some(("lookbackConfiguration.postImpressionActivitiesDuration", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "last-modified-info.time" => Some(("lastModifiedInfo.time", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "pricing-schedule.start-date" => Some(("pricingSchedule.startDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "pricing-schedule.end-date" => Some(("pricingSchedule.endDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "pricing-schedule.flighted" => Some(("pricingSchedule.flighted", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "pricing-schedule.disregard-overdelivery" => Some(("pricingSchedule.disregardOverdelivery", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "pricing-schedule.pricing-type" => Some(("pricingSchedule.pricingType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "pricing-schedule.cap-cost-option" => Some(("pricingSchedule.capCostOption", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "pricing-schedule.testing-start-date" => Some(("pricingSchedule.testingStartDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "pricing-schedule.floodlight-activity-id" => Some(("pricingSchedule.floodlightActivityId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "additional-key-values", "advertiser-id", "advertiser-id-dimension-value", "archived", "campaign-id", "campaign-id-dimension-value", "cap-cost-option", "click-duration", "comment", "compatibility", "content-category-id", "create-info", "dimension-name", "directory-site-id", "directory-site-id-dimension-value", "disregard-overdelivery", "end-date", "etag", "external-id", "flighted", "floodlight-activity-id", "height", "iab", "id", "id-dimension-value", "include-click-through-urls", "include-click-tracking", "key-name", "keyword-option", "kind", "last-modified-info", "lookback-configuration", "match-type", "name", "payment-approved", "payment-source", "placement-group-id", "placement-group-id-dimension-value", "placement-strategy-id", "post-impression-activities-duration", "pricing-schedule", "pricing-type", "primary", "publisher-update-info", "site-id", "site-id-dimension-value", "size", "ssl-required", "start-date", "status", "subaccount-id", "tag-formats", "tag-setting", "testing-start-date", "time", "value", "width"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::Placement = json::value::from_value(object).unwrap(); + let mut call = self.hub.placements().patch(request, opt.value_of("profile-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _placements_update(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "comment" => Some(("comment", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id" => Some(("campaignId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "payment-source" => Some(("paymentSource", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "directory-site-id-dimension-value.kind" => Some(("directorySiteIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "directory-site-id-dimension-value.value" => Some(("directorySiteIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "directory-site-id-dimension-value.dimension-name" => Some(("directorySiteIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "directory-site-id-dimension-value.etag" => Some(("directorySiteIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "directory-site-id-dimension-value.match-type" => Some(("directorySiteIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "directory-site-id-dimension-value.id" => Some(("directorySiteIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id" => Some(("advertiserId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "key-name" => Some(("keyName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "directory-site-id" => Some(("directorySiteId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.kind" => Some(("advertiserIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.value" => Some(("advertiserIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.dimension-name" => Some(("advertiserIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.etag" => Some(("advertiserIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.match-type" => Some(("advertiserIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.id" => Some(("advertiserIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "archived" => Some(("archived", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "publisher-update-info.time" => Some(("publisherUpdateInfo.time", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "tag-formats" => Some(("tagFormats", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "payment-approved" => Some(("paymentApproved", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "tag-setting.include-click-through-urls" => Some(("tagSetting.includeClickThroughUrls", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "tag-setting.include-click-tracking" => Some(("tagSetting.includeClickTracking", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "tag-setting.additional-key-values" => Some(("tagSetting.additionalKeyValues", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "tag-setting.keyword-option" => Some(("tagSetting.keywordOption", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "content-category-id" => Some(("contentCategoryId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "external-id" => Some(("externalId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.kind" => Some(("idDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.value" => Some(("idDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.dimension-name" => Some(("idDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.etag" => Some(("idDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.match-type" => Some(("idDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.id" => Some(("idDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "size.width" => Some(("size.width", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "size.kind" => Some(("size.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "size.iab" => Some(("size.iab", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "size.id" => Some(("size.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "size.height" => Some(("size.height", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "ssl-required" => Some(("sslRequired", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "status" => Some(("status", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.kind" => Some(("campaignIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.value" => Some(("campaignIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.dimension-name" => Some(("campaignIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.etag" => Some(("campaignIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.match-type" => Some(("campaignIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "campaign-id-dimension-value.id" => Some(("campaignIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "primary" => Some(("primary", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "placement-group-id" => Some(("placementGroupId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "create-info.time" => Some(("createInfo.time", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "site-id" => Some(("siteId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "site-id-dimension-value.kind" => Some(("siteIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "site-id-dimension-value.value" => Some(("siteIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "site-id-dimension-value.dimension-name" => Some(("siteIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "site-id-dimension-value.etag" => Some(("siteIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "site-id-dimension-value.match-type" => Some(("siteIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "site-id-dimension-value.id" => Some(("siteIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "compatibility" => Some(("compatibility", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "placement-strategy-id" => Some(("placementStrategyId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "placement-group-id-dimension-value.kind" => Some(("placementGroupIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "placement-group-id-dimension-value.value" => Some(("placementGroupIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "placement-group-id-dimension-value.dimension-name" => Some(("placementGroupIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "placement-group-id-dimension-value.etag" => Some(("placementGroupIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "placement-group-id-dimension-value.match-type" => Some(("placementGroupIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "placement-group-id-dimension-value.id" => Some(("placementGroupIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "subaccount-id" => Some(("subaccountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "lookback-configuration.click-duration" => Some(("lookbackConfiguration.clickDuration", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "lookback-configuration.post-impression-activities-duration" => Some(("lookbackConfiguration.postImpressionActivitiesDuration", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "last-modified-info.time" => Some(("lastModifiedInfo.time", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "pricing-schedule.start-date" => Some(("pricingSchedule.startDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "pricing-schedule.end-date" => Some(("pricingSchedule.endDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "pricing-schedule.flighted" => Some(("pricingSchedule.flighted", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "pricing-schedule.disregard-overdelivery" => Some(("pricingSchedule.disregardOverdelivery", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "pricing-schedule.pricing-type" => Some(("pricingSchedule.pricingType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "pricing-schedule.cap-cost-option" => Some(("pricingSchedule.capCostOption", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "pricing-schedule.testing-start-date" => Some(("pricingSchedule.testingStartDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "pricing-schedule.floodlight-activity-id" => Some(("pricingSchedule.floodlightActivityId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "additional-key-values", "advertiser-id", "advertiser-id-dimension-value", "archived", "campaign-id", "campaign-id-dimension-value", "cap-cost-option", "click-duration", "comment", "compatibility", "content-category-id", "create-info", "dimension-name", "directory-site-id", "directory-site-id-dimension-value", "disregard-overdelivery", "end-date", "etag", "external-id", "flighted", "floodlight-activity-id", "height", "iab", "id", "id-dimension-value", "include-click-through-urls", "include-click-tracking", "key-name", "keyword-option", "kind", "last-modified-info", "lookback-configuration", "match-type", "name", "payment-approved", "payment-source", "placement-group-id", "placement-group-id-dimension-value", "placement-strategy-id", "post-impression-activities-duration", "pricing-schedule", "pricing-type", "primary", "publisher-update-info", "site-id", "site-id-dimension-value", "size", "ssl-required", "start-date", "status", "subaccount-id", "tag-formats", "tag-setting", "testing-start-date", "time", "value", "width"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::Placement = json::value::from_value(object).unwrap(); + let mut call = self.hub.placements().update(request, opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _platform_types_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.platform_types().get(opt.value_of("profile-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _platform_types_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.platform_types().list(opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _postal_codes_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.postal_codes().get(opt.value_of("profile-id").unwrap_or(""), opt.value_of("code").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _postal_codes_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.postal_codes().list(opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _projects_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.projects().get(opt.value_of("profile-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _projects_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.projects().list(opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "sort-order" => { + call = call.sort_order(value.unwrap_or("")); + }, + "sort-field" => { + call = call.sort_field(value.unwrap_or("")); + }, + "search-string" => { + call = call.search_string(value.unwrap_or("")); + }, + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "max-results" => { + call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer")); + }, + "ids" => { + call = call.add_ids(value.unwrap_or("")); + }, + "advertiser-ids" => { + call = call.add_advertiser_ids(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["search-string", "sort-field", "advertiser-ids", "ids", "max-results", "page-token", "sort-order"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _regions_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.regions().list(opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _remarketing_list_shares_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.remarketing_list_shares().get(opt.value_of("profile-id").unwrap_or(""), opt.value_of("remarketing-list-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _remarketing_list_shares_patch(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "shared-advertiser-ids" => Some(("sharedAdvertiserIds", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "remarketing-list-id" => Some(("remarketingListId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "shared-account-ids" => Some(("sharedAccountIds", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["kind", "remarketing-list-id", "shared-account-ids", "shared-advertiser-ids"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::RemarketingListShare = json::value::from_value(object).unwrap(); + let mut call = self.hub.remarketing_list_shares().patch(request, opt.value_of("profile-id").unwrap_or(""), opt.value_of("remarketing-list-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _remarketing_list_shares_update(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "shared-advertiser-ids" => Some(("sharedAdvertiserIds", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "remarketing-list-id" => Some(("remarketingListId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "shared-account-ids" => Some(("sharedAccountIds", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["kind", "remarketing-list-id", "shared-account-ids", "shared-advertiser-ids"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::RemarketingListShare = json::value::from_value(object).unwrap(); + let mut call = self.hub.remarketing_list_shares().update(request, opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _remarketing_lists_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.remarketing_lists().get(opt.value_of("profile-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _remarketing_lists_insert(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "list-population-rule.floodlight-activity-name" => Some(("listPopulationRule.floodlightActivityName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "list-population-rule.floodlight-activity-id" => Some(("listPopulationRule.floodlightActivityId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "subaccount-id" => Some(("subaccountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "description" => Some(("description", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "list-size" => Some(("listSize", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "life-span" => Some(("lifeSpan", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id" => Some(("advertiserId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "active" => Some(("active", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.kind" => Some(("advertiserIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.value" => Some(("advertiserIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.dimension-name" => Some(("advertiserIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.etag" => Some(("advertiserIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.match-type" => Some(("advertiserIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.id" => Some(("advertiserIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "list-source" => Some(("listSource", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "active", "advertiser-id", "advertiser-id-dimension-value", "description", "dimension-name", "etag", "floodlight-activity-id", "floodlight-activity-name", "id", "kind", "life-span", "list-population-rule", "list-size", "list-source", "match-type", "name", "subaccount-id", "value"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::RemarketingList = json::value::from_value(object).unwrap(); + let mut call = self.hub.remarketing_lists().insert(request, opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _remarketing_lists_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.remarketing_lists().list(opt.value_of("profile-id").unwrap_or(""), opt.value_of("advertiser-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "sort-order" => { + call = call.sort_order(value.unwrap_or("")); + }, + "sort-field" => { + call = call.sort_field(value.unwrap_or("")); + }, + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "name" => { + call = call.name(value.unwrap_or("")); + }, + "max-results" => { + call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer")); + }, + "floodlight-activity-id" => { + call = call.floodlight_activity_id(value.unwrap_or("")); + }, + "active" => { + call = call.active(arg_from_str(value.unwrap_or("false"), err, "active", "boolean")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["name", "sort-field", "max-results", "page-token", "sort-order", "active", "floodlight-activity-id"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _remarketing_lists_patch(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "list-population-rule.floodlight-activity-name" => Some(("listPopulationRule.floodlightActivityName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "list-population-rule.floodlight-activity-id" => Some(("listPopulationRule.floodlightActivityId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "subaccount-id" => Some(("subaccountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "description" => Some(("description", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "list-size" => Some(("listSize", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "life-span" => Some(("lifeSpan", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id" => Some(("advertiserId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "active" => Some(("active", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.kind" => Some(("advertiserIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.value" => Some(("advertiserIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.dimension-name" => Some(("advertiserIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.etag" => Some(("advertiserIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.match-type" => Some(("advertiserIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.id" => Some(("advertiserIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "list-source" => Some(("listSource", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "active", "advertiser-id", "advertiser-id-dimension-value", "description", "dimension-name", "etag", "floodlight-activity-id", "floodlight-activity-name", "id", "kind", "life-span", "list-population-rule", "list-size", "list-source", "match-type", "name", "subaccount-id", "value"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::RemarketingList = json::value::from_value(object).unwrap(); + let mut call = self.hub.remarketing_lists().patch(request, opt.value_of("profile-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _remarketing_lists_update(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "list-population-rule.floodlight-activity-name" => Some(("listPopulationRule.floodlightActivityName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "list-population-rule.floodlight-activity-id" => Some(("listPopulationRule.floodlightActivityId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "subaccount-id" => Some(("subaccountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "description" => Some(("description", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "list-size" => Some(("listSize", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "life-span" => Some(("lifeSpan", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id" => Some(("advertiserId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "active" => Some(("active", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.kind" => Some(("advertiserIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.value" => Some(("advertiserIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.dimension-name" => Some(("advertiserIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.etag" => Some(("advertiserIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.match-type" => Some(("advertiserIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertiser-id-dimension-value.id" => Some(("advertiserIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "list-source" => Some(("listSource", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "active", "advertiser-id", "advertiser-id-dimension-value", "description", "dimension-name", "etag", "floodlight-activity-id", "floodlight-activity-name", "id", "kind", "life-span", "list-population-rule", "list-size", "list-source", "match-type", "name", "subaccount-id", "value"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::RemarketingList = json::value::from_value(object).unwrap(); + let mut call = self.hub.remarketing_lists().update(request, opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _reports_compatible_fields_query(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "criteria.activities.kind" => Some(("criteria.activities.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "criteria.activities.metric-names" => Some(("criteria.activities.metricNames", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "criteria.date-range.start-date" => Some(("criteria.dateRange.startDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "criteria.date-range.kind" => Some(("criteria.dateRange.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "criteria.date-range.end-date" => Some(("criteria.dateRange.endDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "criteria.date-range.relative-date-range" => Some(("criteria.dateRange.relativeDateRange", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "criteria.custom-rich-media-events.kind" => Some(("criteria.customRichMediaEvents.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "criteria.metric-names" => Some(("criteria.metricNames", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "sub-account-id" => Some(("subAccountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "schedule.start-date" => Some(("schedule.startDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "schedule.runs-on-day-of-month" => Some(("schedule.runsOnDayOfMonth", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "schedule.every" => Some(("schedule.every", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "schedule.expiration-date" => Some(("schedule.expirationDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "schedule.active" => Some(("schedule.active", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "schedule.repeats" => Some(("schedule.repeats", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "schedule.repeats-on-week-days" => Some(("schedule.repeatsOnWeekDays", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "path-to-conversion-criteria.date-range.start-date" => Some(("pathToConversionCriteria.dateRange.startDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.date-range.kind" => Some(("pathToConversionCriteria.dateRange.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.date-range.end-date" => Some(("pathToConversionCriteria.dateRange.endDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.date-range.relative-date-range" => Some(("pathToConversionCriteria.dateRange.relativeDateRange", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.floodlight-config-id.kind" => Some(("pathToConversionCriteria.floodlightConfigId.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.floodlight-config-id.value" => Some(("pathToConversionCriteria.floodlightConfigId.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.floodlight-config-id.dimension-name" => Some(("pathToConversionCriteria.floodlightConfigId.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.floodlight-config-id.etag" => Some(("pathToConversionCriteria.floodlightConfigId.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.floodlight-config-id.match-type" => Some(("pathToConversionCriteria.floodlightConfigId.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.floodlight-config-id.id" => Some(("pathToConversionCriteria.floodlightConfigId.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.report-properties.clicks-lookback-window" => Some(("pathToConversionCriteria.reportProperties.clicksLookbackWindow", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.report-properties.pivot-on-interaction-path" => Some(("pathToConversionCriteria.reportProperties.pivotOnInteractionPath", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.report-properties.impressions-lookback-window" => Some(("pathToConversionCriteria.reportProperties.impressionsLookbackWindow", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.report-properties.include-unattributed-ip-conversions" => Some(("pathToConversionCriteria.reportProperties.includeUnattributedIPConversions", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.report-properties.include-unattributed-cookie-conversions" => Some(("pathToConversionCriteria.reportProperties.includeUnattributedCookieConversions", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.report-properties.maximum-interaction-gap" => Some(("pathToConversionCriteria.reportProperties.maximumInteractionGap", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.report-properties.include-attributed-ip-conversions" => Some(("pathToConversionCriteria.reportProperties.includeAttributedIPConversions", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.report-properties.maximum-click-interactions" => Some(("pathToConversionCriteria.reportProperties.maximumClickInteractions", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.report-properties.maximum-impression-interactions" => Some(("pathToConversionCriteria.reportProperties.maximumImpressionInteractions", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.metric-names" => Some(("pathToConversionCriteria.metricNames", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "format" => Some(("format", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "reach-criteria.activities.kind" => Some(("reachCriteria.activities.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "reach-criteria.activities.metric-names" => Some(("reachCriteria.activities.metricNames", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "reach-criteria.metric-names" => Some(("reachCriteria.metricNames", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "reach-criteria.date-range.start-date" => Some(("reachCriteria.dateRange.startDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "reach-criteria.date-range.kind" => Some(("reachCriteria.dateRange.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "reach-criteria.date-range.end-date" => Some(("reachCriteria.dateRange.endDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "reach-criteria.date-range.relative-date-range" => Some(("reachCriteria.dateRange.relativeDateRange", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "reach-criteria.reach-by-frequency-metric-names" => Some(("reachCriteria.reachByFrequencyMetricNames", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "reach-criteria.custom-rich-media-events.kind" => Some(("reachCriteria.customRichMediaEvents.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "reach-criteria.enable-all-dimension-combinations" => Some(("reachCriteria.enableAllDimensionCombinations", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "file-name" => Some(("fileName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "delivery.message" => Some(("delivery.message", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "delivery.email-owner-delivery-type" => Some(("delivery.emailOwnerDeliveryType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "delivery.email-owner" => Some(("delivery.emailOwner", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "etag" => Some(("etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "owner-profile-id" => Some(("ownerProfileId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "last-modified-time" => Some(("lastModifiedTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "type" => Some(("type", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-criteria.date-range.start-date" => Some(("floodlightCriteria.dateRange.startDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-criteria.date-range.kind" => Some(("floodlightCriteria.dateRange.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-criteria.date-range.end-date" => Some(("floodlightCriteria.dateRange.endDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-criteria.date-range.relative-date-range" => Some(("floodlightCriteria.dateRange.relativeDateRange", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-criteria.floodlight-config-id.kind" => Some(("floodlightCriteria.floodlightConfigId.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-criteria.floodlight-config-id.value" => Some(("floodlightCriteria.floodlightConfigId.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-criteria.floodlight-config-id.dimension-name" => Some(("floodlightCriteria.floodlightConfigId.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-criteria.floodlight-config-id.etag" => Some(("floodlightCriteria.floodlightConfigId.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-criteria.floodlight-config-id.match-type" => Some(("floodlightCriteria.floodlightConfigId.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-criteria.floodlight-config-id.id" => Some(("floodlightCriteria.floodlightConfigId.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-criteria.report-properties.include-unattributed-ip-conversions" => Some(("floodlightCriteria.reportProperties.includeUnattributedIPConversions", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "floodlight-criteria.report-properties.include-unattributed-cookie-conversions" => Some(("floodlightCriteria.reportProperties.includeUnattributedCookieConversions", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "floodlight-criteria.report-properties.include-attributed-ip-conversions" => Some(("floodlightCriteria.reportProperties.includeAttributedIPConversions", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "floodlight-criteria.metric-names" => Some(("floodlightCriteria.metricNames", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "cross-dimension-reach-criteria.pivoted" => Some(("crossDimensionReachCriteria.pivoted", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "cross-dimension-reach-criteria.date-range.start-date" => Some(("crossDimensionReachCriteria.dateRange.startDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "cross-dimension-reach-criteria.date-range.kind" => Some(("crossDimensionReachCriteria.dateRange.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "cross-dimension-reach-criteria.date-range.end-date" => Some(("crossDimensionReachCriteria.dateRange.endDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "cross-dimension-reach-criteria.date-range.relative-date-range" => Some(("crossDimensionReachCriteria.dateRange.relativeDateRange", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "cross-dimension-reach-criteria.dimension" => Some(("crossDimensionReachCriteria.dimension", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "cross-dimension-reach-criteria.overlap-metric-names" => Some(("crossDimensionReachCriteria.overlapMetricNames", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "cross-dimension-reach-criteria.metric-names" => Some(("crossDimensionReachCriteria.metricNames", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "active", "activities", "clicks-lookback-window", "criteria", "cross-dimension-reach-criteria", "custom-rich-media-events", "date-range", "delivery", "dimension", "dimension-name", "email-owner", "email-owner-delivery-type", "enable-all-dimension-combinations", "end-date", "etag", "every", "expiration-date", "file-name", "floodlight-config-id", "floodlight-criteria", "format", "id", "impressions-lookback-window", "include-attributed-ip-conversions", "include-unattributed-cookie-conversions", "include-unattributed-ip-conversions", "kind", "last-modified-time", "match-type", "maximum-click-interactions", "maximum-impression-interactions", "maximum-interaction-gap", "message", "metric-names", "name", "overlap-metric-names", "owner-profile-id", "path-to-conversion-criteria", "pivot-on-interaction-path", "pivoted", "reach-by-frequency-metric-names", "reach-criteria", "relative-date-range", "repeats", "repeats-on-week-days", "report-properties", "runs-on-day-of-month", "schedule", "start-date", "sub-account-id", "type", "value"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::Report = json::value::from_value(object).unwrap(); + let mut call = self.hub.reports().compatible_fields_query(request, opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _reports_delete(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.reports().delete(opt.value_of("profile-id").unwrap_or(""), opt.value_of("report-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok(mut response) => { + Ok(()) + } + } + } + } + + fn _reports_files_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut download_mode = false; + let mut call = self.hub.reports().files_get(opt.value_of("profile-id").unwrap_or(""), opt.value_of("report-id").unwrap_or(""), opt.value_of("file-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + if key == "alt" && value.unwrap_or("unset") == "media" { + download_mode = true; + } + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + if !download_mode { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + } else { + io::copy(&mut response, &mut ostream).unwrap(); + ostream.flush().unwrap(); + } + Ok(()) + } + } + } + } + + fn _reports_files_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.reports().files_list(opt.value_of("profile-id").unwrap_or(""), opt.value_of("report-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "sort-order" => { + call = call.sort_order(value.unwrap_or("")); + }, + "sort-field" => { + call = call.sort_field(value.unwrap_or("")); + }, + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "max-results" => { + call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["sort-field", "sort-order", "max-results", "page-token"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _reports_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.reports().get(opt.value_of("profile-id").unwrap_or(""), opt.value_of("report-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _reports_insert(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "criteria.activities.kind" => Some(("criteria.activities.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "criteria.activities.metric-names" => Some(("criteria.activities.metricNames", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "criteria.date-range.start-date" => Some(("criteria.dateRange.startDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "criteria.date-range.kind" => Some(("criteria.dateRange.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "criteria.date-range.end-date" => Some(("criteria.dateRange.endDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "criteria.date-range.relative-date-range" => Some(("criteria.dateRange.relativeDateRange", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "criteria.custom-rich-media-events.kind" => Some(("criteria.customRichMediaEvents.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "criteria.metric-names" => Some(("criteria.metricNames", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "sub-account-id" => Some(("subAccountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "schedule.start-date" => Some(("schedule.startDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "schedule.runs-on-day-of-month" => Some(("schedule.runsOnDayOfMonth", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "schedule.every" => Some(("schedule.every", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "schedule.expiration-date" => Some(("schedule.expirationDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "schedule.active" => Some(("schedule.active", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "schedule.repeats" => Some(("schedule.repeats", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "schedule.repeats-on-week-days" => Some(("schedule.repeatsOnWeekDays", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "path-to-conversion-criteria.date-range.start-date" => Some(("pathToConversionCriteria.dateRange.startDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.date-range.kind" => Some(("pathToConversionCriteria.dateRange.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.date-range.end-date" => Some(("pathToConversionCriteria.dateRange.endDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.date-range.relative-date-range" => Some(("pathToConversionCriteria.dateRange.relativeDateRange", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.floodlight-config-id.kind" => Some(("pathToConversionCriteria.floodlightConfigId.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.floodlight-config-id.value" => Some(("pathToConversionCriteria.floodlightConfigId.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.floodlight-config-id.dimension-name" => Some(("pathToConversionCriteria.floodlightConfigId.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.floodlight-config-id.etag" => Some(("pathToConversionCriteria.floodlightConfigId.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.floodlight-config-id.match-type" => Some(("pathToConversionCriteria.floodlightConfigId.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.floodlight-config-id.id" => Some(("pathToConversionCriteria.floodlightConfigId.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.report-properties.clicks-lookback-window" => Some(("pathToConversionCriteria.reportProperties.clicksLookbackWindow", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.report-properties.pivot-on-interaction-path" => Some(("pathToConversionCriteria.reportProperties.pivotOnInteractionPath", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.report-properties.impressions-lookback-window" => Some(("pathToConversionCriteria.reportProperties.impressionsLookbackWindow", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.report-properties.include-unattributed-ip-conversions" => Some(("pathToConversionCriteria.reportProperties.includeUnattributedIPConversions", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.report-properties.include-unattributed-cookie-conversions" => Some(("pathToConversionCriteria.reportProperties.includeUnattributedCookieConversions", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.report-properties.maximum-interaction-gap" => Some(("pathToConversionCriteria.reportProperties.maximumInteractionGap", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.report-properties.include-attributed-ip-conversions" => Some(("pathToConversionCriteria.reportProperties.includeAttributedIPConversions", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.report-properties.maximum-click-interactions" => Some(("pathToConversionCriteria.reportProperties.maximumClickInteractions", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.report-properties.maximum-impression-interactions" => Some(("pathToConversionCriteria.reportProperties.maximumImpressionInteractions", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.metric-names" => Some(("pathToConversionCriteria.metricNames", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "format" => Some(("format", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "reach-criteria.activities.kind" => Some(("reachCriteria.activities.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "reach-criteria.activities.metric-names" => Some(("reachCriteria.activities.metricNames", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "reach-criteria.metric-names" => Some(("reachCriteria.metricNames", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "reach-criteria.date-range.start-date" => Some(("reachCriteria.dateRange.startDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "reach-criteria.date-range.kind" => Some(("reachCriteria.dateRange.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "reach-criteria.date-range.end-date" => Some(("reachCriteria.dateRange.endDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "reach-criteria.date-range.relative-date-range" => Some(("reachCriteria.dateRange.relativeDateRange", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "reach-criteria.reach-by-frequency-metric-names" => Some(("reachCriteria.reachByFrequencyMetricNames", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "reach-criteria.custom-rich-media-events.kind" => Some(("reachCriteria.customRichMediaEvents.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "reach-criteria.enable-all-dimension-combinations" => Some(("reachCriteria.enableAllDimensionCombinations", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "file-name" => Some(("fileName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "delivery.message" => Some(("delivery.message", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "delivery.email-owner-delivery-type" => Some(("delivery.emailOwnerDeliveryType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "delivery.email-owner" => Some(("delivery.emailOwner", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "etag" => Some(("etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "owner-profile-id" => Some(("ownerProfileId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "last-modified-time" => Some(("lastModifiedTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "type" => Some(("type", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-criteria.date-range.start-date" => Some(("floodlightCriteria.dateRange.startDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-criteria.date-range.kind" => Some(("floodlightCriteria.dateRange.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-criteria.date-range.end-date" => Some(("floodlightCriteria.dateRange.endDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-criteria.date-range.relative-date-range" => Some(("floodlightCriteria.dateRange.relativeDateRange", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-criteria.floodlight-config-id.kind" => Some(("floodlightCriteria.floodlightConfigId.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-criteria.floodlight-config-id.value" => Some(("floodlightCriteria.floodlightConfigId.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-criteria.floodlight-config-id.dimension-name" => Some(("floodlightCriteria.floodlightConfigId.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-criteria.floodlight-config-id.etag" => Some(("floodlightCriteria.floodlightConfigId.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-criteria.floodlight-config-id.match-type" => Some(("floodlightCriteria.floodlightConfigId.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-criteria.floodlight-config-id.id" => Some(("floodlightCriteria.floodlightConfigId.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-criteria.report-properties.include-unattributed-ip-conversions" => Some(("floodlightCriteria.reportProperties.includeUnattributedIPConversions", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "floodlight-criteria.report-properties.include-unattributed-cookie-conversions" => Some(("floodlightCriteria.reportProperties.includeUnattributedCookieConversions", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "floodlight-criteria.report-properties.include-attributed-ip-conversions" => Some(("floodlightCriteria.reportProperties.includeAttributedIPConversions", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "floodlight-criteria.metric-names" => Some(("floodlightCriteria.metricNames", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "cross-dimension-reach-criteria.pivoted" => Some(("crossDimensionReachCriteria.pivoted", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "cross-dimension-reach-criteria.date-range.start-date" => Some(("crossDimensionReachCriteria.dateRange.startDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "cross-dimension-reach-criteria.date-range.kind" => Some(("crossDimensionReachCriteria.dateRange.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "cross-dimension-reach-criteria.date-range.end-date" => Some(("crossDimensionReachCriteria.dateRange.endDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "cross-dimension-reach-criteria.date-range.relative-date-range" => Some(("crossDimensionReachCriteria.dateRange.relativeDateRange", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "cross-dimension-reach-criteria.dimension" => Some(("crossDimensionReachCriteria.dimension", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "cross-dimension-reach-criteria.overlap-metric-names" => Some(("crossDimensionReachCriteria.overlapMetricNames", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "cross-dimension-reach-criteria.metric-names" => Some(("crossDimensionReachCriteria.metricNames", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "active", "activities", "clicks-lookback-window", "criteria", "cross-dimension-reach-criteria", "custom-rich-media-events", "date-range", "delivery", "dimension", "dimension-name", "email-owner", "email-owner-delivery-type", "enable-all-dimension-combinations", "end-date", "etag", "every", "expiration-date", "file-name", "floodlight-config-id", "floodlight-criteria", "format", "id", "impressions-lookback-window", "include-attributed-ip-conversions", "include-unattributed-cookie-conversions", "include-unattributed-ip-conversions", "kind", "last-modified-time", "match-type", "maximum-click-interactions", "maximum-impression-interactions", "maximum-interaction-gap", "message", "metric-names", "name", "overlap-metric-names", "owner-profile-id", "path-to-conversion-criteria", "pivot-on-interaction-path", "pivoted", "reach-by-frequency-metric-names", "reach-criteria", "relative-date-range", "repeats", "repeats-on-week-days", "report-properties", "runs-on-day-of-month", "schedule", "start-date", "sub-account-id", "type", "value"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::Report = json::value::from_value(object).unwrap(); + let mut call = self.hub.reports().insert(request, opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _reports_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.reports().list(opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "sort-order" => { + call = call.sort_order(value.unwrap_or("")); + }, + "sort-field" => { + call = call.sort_field(value.unwrap_or("")); + }, + "scope" => { + call = call.scope(value.unwrap_or("")); + }, + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "max-results" => { + call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["sort-field", "max-results", "sort-order", "page-token", "scope"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _reports_patch(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "criteria.activities.kind" => Some(("criteria.activities.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "criteria.activities.metric-names" => Some(("criteria.activities.metricNames", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "criteria.date-range.start-date" => Some(("criteria.dateRange.startDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "criteria.date-range.kind" => Some(("criteria.dateRange.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "criteria.date-range.end-date" => Some(("criteria.dateRange.endDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "criteria.date-range.relative-date-range" => Some(("criteria.dateRange.relativeDateRange", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "criteria.custom-rich-media-events.kind" => Some(("criteria.customRichMediaEvents.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "criteria.metric-names" => Some(("criteria.metricNames", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "sub-account-id" => Some(("subAccountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "schedule.start-date" => Some(("schedule.startDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "schedule.runs-on-day-of-month" => Some(("schedule.runsOnDayOfMonth", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "schedule.every" => Some(("schedule.every", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "schedule.expiration-date" => Some(("schedule.expirationDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "schedule.active" => Some(("schedule.active", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "schedule.repeats" => Some(("schedule.repeats", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "schedule.repeats-on-week-days" => Some(("schedule.repeatsOnWeekDays", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "path-to-conversion-criteria.date-range.start-date" => Some(("pathToConversionCriteria.dateRange.startDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.date-range.kind" => Some(("pathToConversionCriteria.dateRange.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.date-range.end-date" => Some(("pathToConversionCriteria.dateRange.endDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.date-range.relative-date-range" => Some(("pathToConversionCriteria.dateRange.relativeDateRange", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.floodlight-config-id.kind" => Some(("pathToConversionCriteria.floodlightConfigId.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.floodlight-config-id.value" => Some(("pathToConversionCriteria.floodlightConfigId.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.floodlight-config-id.dimension-name" => Some(("pathToConversionCriteria.floodlightConfigId.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.floodlight-config-id.etag" => Some(("pathToConversionCriteria.floodlightConfigId.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.floodlight-config-id.match-type" => Some(("pathToConversionCriteria.floodlightConfigId.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.floodlight-config-id.id" => Some(("pathToConversionCriteria.floodlightConfigId.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.report-properties.clicks-lookback-window" => Some(("pathToConversionCriteria.reportProperties.clicksLookbackWindow", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.report-properties.pivot-on-interaction-path" => Some(("pathToConversionCriteria.reportProperties.pivotOnInteractionPath", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.report-properties.impressions-lookback-window" => Some(("pathToConversionCriteria.reportProperties.impressionsLookbackWindow", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.report-properties.include-unattributed-ip-conversions" => Some(("pathToConversionCriteria.reportProperties.includeUnattributedIPConversions", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.report-properties.include-unattributed-cookie-conversions" => Some(("pathToConversionCriteria.reportProperties.includeUnattributedCookieConversions", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.report-properties.maximum-interaction-gap" => Some(("pathToConversionCriteria.reportProperties.maximumInteractionGap", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.report-properties.include-attributed-ip-conversions" => Some(("pathToConversionCriteria.reportProperties.includeAttributedIPConversions", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.report-properties.maximum-click-interactions" => Some(("pathToConversionCriteria.reportProperties.maximumClickInteractions", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.report-properties.maximum-impression-interactions" => Some(("pathToConversionCriteria.reportProperties.maximumImpressionInteractions", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.metric-names" => Some(("pathToConversionCriteria.metricNames", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "format" => Some(("format", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "reach-criteria.activities.kind" => Some(("reachCriteria.activities.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "reach-criteria.activities.metric-names" => Some(("reachCriteria.activities.metricNames", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "reach-criteria.metric-names" => Some(("reachCriteria.metricNames", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "reach-criteria.date-range.start-date" => Some(("reachCriteria.dateRange.startDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "reach-criteria.date-range.kind" => Some(("reachCriteria.dateRange.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "reach-criteria.date-range.end-date" => Some(("reachCriteria.dateRange.endDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "reach-criteria.date-range.relative-date-range" => Some(("reachCriteria.dateRange.relativeDateRange", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "reach-criteria.reach-by-frequency-metric-names" => Some(("reachCriteria.reachByFrequencyMetricNames", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "reach-criteria.custom-rich-media-events.kind" => Some(("reachCriteria.customRichMediaEvents.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "reach-criteria.enable-all-dimension-combinations" => Some(("reachCriteria.enableAllDimensionCombinations", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "file-name" => Some(("fileName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "delivery.message" => Some(("delivery.message", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "delivery.email-owner-delivery-type" => Some(("delivery.emailOwnerDeliveryType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "delivery.email-owner" => Some(("delivery.emailOwner", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "etag" => Some(("etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "owner-profile-id" => Some(("ownerProfileId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "last-modified-time" => Some(("lastModifiedTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "type" => Some(("type", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-criteria.date-range.start-date" => Some(("floodlightCriteria.dateRange.startDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-criteria.date-range.kind" => Some(("floodlightCriteria.dateRange.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-criteria.date-range.end-date" => Some(("floodlightCriteria.dateRange.endDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-criteria.date-range.relative-date-range" => Some(("floodlightCriteria.dateRange.relativeDateRange", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-criteria.floodlight-config-id.kind" => Some(("floodlightCriteria.floodlightConfigId.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-criteria.floodlight-config-id.value" => Some(("floodlightCriteria.floodlightConfigId.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-criteria.floodlight-config-id.dimension-name" => Some(("floodlightCriteria.floodlightConfigId.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-criteria.floodlight-config-id.etag" => Some(("floodlightCriteria.floodlightConfigId.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-criteria.floodlight-config-id.match-type" => Some(("floodlightCriteria.floodlightConfigId.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-criteria.floodlight-config-id.id" => Some(("floodlightCriteria.floodlightConfigId.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-criteria.report-properties.include-unattributed-ip-conversions" => Some(("floodlightCriteria.reportProperties.includeUnattributedIPConversions", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "floodlight-criteria.report-properties.include-unattributed-cookie-conversions" => Some(("floodlightCriteria.reportProperties.includeUnattributedCookieConversions", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "floodlight-criteria.report-properties.include-attributed-ip-conversions" => Some(("floodlightCriteria.reportProperties.includeAttributedIPConversions", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "floodlight-criteria.metric-names" => Some(("floodlightCriteria.metricNames", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "cross-dimension-reach-criteria.pivoted" => Some(("crossDimensionReachCriteria.pivoted", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "cross-dimension-reach-criteria.date-range.start-date" => Some(("crossDimensionReachCriteria.dateRange.startDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "cross-dimension-reach-criteria.date-range.kind" => Some(("crossDimensionReachCriteria.dateRange.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "cross-dimension-reach-criteria.date-range.end-date" => Some(("crossDimensionReachCriteria.dateRange.endDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "cross-dimension-reach-criteria.date-range.relative-date-range" => Some(("crossDimensionReachCriteria.dateRange.relativeDateRange", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "cross-dimension-reach-criteria.dimension" => Some(("crossDimensionReachCriteria.dimension", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "cross-dimension-reach-criteria.overlap-metric-names" => Some(("crossDimensionReachCriteria.overlapMetricNames", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "cross-dimension-reach-criteria.metric-names" => Some(("crossDimensionReachCriteria.metricNames", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "active", "activities", "clicks-lookback-window", "criteria", "cross-dimension-reach-criteria", "custom-rich-media-events", "date-range", "delivery", "dimension", "dimension-name", "email-owner", "email-owner-delivery-type", "enable-all-dimension-combinations", "end-date", "etag", "every", "expiration-date", "file-name", "floodlight-config-id", "floodlight-criteria", "format", "id", "impressions-lookback-window", "include-attributed-ip-conversions", "include-unattributed-cookie-conversions", "include-unattributed-ip-conversions", "kind", "last-modified-time", "match-type", "maximum-click-interactions", "maximum-impression-interactions", "maximum-interaction-gap", "message", "metric-names", "name", "overlap-metric-names", "owner-profile-id", "path-to-conversion-criteria", "pivot-on-interaction-path", "pivoted", "reach-by-frequency-metric-names", "reach-criteria", "relative-date-range", "repeats", "repeats-on-week-days", "report-properties", "runs-on-day-of-month", "schedule", "start-date", "sub-account-id", "type", "value"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::Report = json::value::from_value(object).unwrap(); + let mut call = self.hub.reports().patch(request, opt.value_of("profile-id").unwrap_or(""), opt.value_of("report-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _reports_run(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.reports().run(opt.value_of("profile-id").unwrap_or(""), opt.value_of("report-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "synchronous" => { + call = call.synchronous(arg_from_str(value.unwrap_or("false"), err, "synchronous", "boolean")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["synchronous"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _reports_update(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "criteria.activities.kind" => Some(("criteria.activities.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "criteria.activities.metric-names" => Some(("criteria.activities.metricNames", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "criteria.date-range.start-date" => Some(("criteria.dateRange.startDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "criteria.date-range.kind" => Some(("criteria.dateRange.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "criteria.date-range.end-date" => Some(("criteria.dateRange.endDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "criteria.date-range.relative-date-range" => Some(("criteria.dateRange.relativeDateRange", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "criteria.custom-rich-media-events.kind" => Some(("criteria.customRichMediaEvents.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "criteria.metric-names" => Some(("criteria.metricNames", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "sub-account-id" => Some(("subAccountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "schedule.start-date" => Some(("schedule.startDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "schedule.runs-on-day-of-month" => Some(("schedule.runsOnDayOfMonth", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "schedule.every" => Some(("schedule.every", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "schedule.expiration-date" => Some(("schedule.expirationDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "schedule.active" => Some(("schedule.active", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "schedule.repeats" => Some(("schedule.repeats", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "schedule.repeats-on-week-days" => Some(("schedule.repeatsOnWeekDays", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "path-to-conversion-criteria.date-range.start-date" => Some(("pathToConversionCriteria.dateRange.startDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.date-range.kind" => Some(("pathToConversionCriteria.dateRange.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.date-range.end-date" => Some(("pathToConversionCriteria.dateRange.endDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.date-range.relative-date-range" => Some(("pathToConversionCriteria.dateRange.relativeDateRange", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.floodlight-config-id.kind" => Some(("pathToConversionCriteria.floodlightConfigId.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.floodlight-config-id.value" => Some(("pathToConversionCriteria.floodlightConfigId.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.floodlight-config-id.dimension-name" => Some(("pathToConversionCriteria.floodlightConfigId.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.floodlight-config-id.etag" => Some(("pathToConversionCriteria.floodlightConfigId.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.floodlight-config-id.match-type" => Some(("pathToConversionCriteria.floodlightConfigId.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.floodlight-config-id.id" => Some(("pathToConversionCriteria.floodlightConfigId.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.report-properties.clicks-lookback-window" => Some(("pathToConversionCriteria.reportProperties.clicksLookbackWindow", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.report-properties.pivot-on-interaction-path" => Some(("pathToConversionCriteria.reportProperties.pivotOnInteractionPath", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.report-properties.impressions-lookback-window" => Some(("pathToConversionCriteria.reportProperties.impressionsLookbackWindow", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.report-properties.include-unattributed-ip-conversions" => Some(("pathToConversionCriteria.reportProperties.includeUnattributedIPConversions", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.report-properties.include-unattributed-cookie-conversions" => Some(("pathToConversionCriteria.reportProperties.includeUnattributedCookieConversions", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.report-properties.maximum-interaction-gap" => Some(("pathToConversionCriteria.reportProperties.maximumInteractionGap", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.report-properties.include-attributed-ip-conversions" => Some(("pathToConversionCriteria.reportProperties.includeAttributedIPConversions", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.report-properties.maximum-click-interactions" => Some(("pathToConversionCriteria.reportProperties.maximumClickInteractions", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.report-properties.maximum-impression-interactions" => Some(("pathToConversionCriteria.reportProperties.maximumImpressionInteractions", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "path-to-conversion-criteria.metric-names" => Some(("pathToConversionCriteria.metricNames", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "format" => Some(("format", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "reach-criteria.activities.kind" => Some(("reachCriteria.activities.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "reach-criteria.activities.metric-names" => Some(("reachCriteria.activities.metricNames", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "reach-criteria.metric-names" => Some(("reachCriteria.metricNames", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "reach-criteria.date-range.start-date" => Some(("reachCriteria.dateRange.startDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "reach-criteria.date-range.kind" => Some(("reachCriteria.dateRange.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "reach-criteria.date-range.end-date" => Some(("reachCriteria.dateRange.endDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "reach-criteria.date-range.relative-date-range" => Some(("reachCriteria.dateRange.relativeDateRange", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "reach-criteria.reach-by-frequency-metric-names" => Some(("reachCriteria.reachByFrequencyMetricNames", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "reach-criteria.custom-rich-media-events.kind" => Some(("reachCriteria.customRichMediaEvents.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "reach-criteria.enable-all-dimension-combinations" => Some(("reachCriteria.enableAllDimensionCombinations", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "file-name" => Some(("fileName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "delivery.message" => Some(("delivery.message", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "delivery.email-owner-delivery-type" => Some(("delivery.emailOwnerDeliveryType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "delivery.email-owner" => Some(("delivery.emailOwner", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "etag" => Some(("etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "owner-profile-id" => Some(("ownerProfileId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "last-modified-time" => Some(("lastModifiedTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "type" => Some(("type", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-criteria.date-range.start-date" => Some(("floodlightCriteria.dateRange.startDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-criteria.date-range.kind" => Some(("floodlightCriteria.dateRange.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-criteria.date-range.end-date" => Some(("floodlightCriteria.dateRange.endDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-criteria.date-range.relative-date-range" => Some(("floodlightCriteria.dateRange.relativeDateRange", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-criteria.floodlight-config-id.kind" => Some(("floodlightCriteria.floodlightConfigId.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-criteria.floodlight-config-id.value" => Some(("floodlightCriteria.floodlightConfigId.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-criteria.floodlight-config-id.dimension-name" => Some(("floodlightCriteria.floodlightConfigId.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-criteria.floodlight-config-id.etag" => Some(("floodlightCriteria.floodlightConfigId.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-criteria.floodlight-config-id.match-type" => Some(("floodlightCriteria.floodlightConfigId.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-criteria.floodlight-config-id.id" => Some(("floodlightCriteria.floodlightConfigId.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "floodlight-criteria.report-properties.include-unattributed-ip-conversions" => Some(("floodlightCriteria.reportProperties.includeUnattributedIPConversions", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "floodlight-criteria.report-properties.include-unattributed-cookie-conversions" => Some(("floodlightCriteria.reportProperties.includeUnattributedCookieConversions", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "floodlight-criteria.report-properties.include-attributed-ip-conversions" => Some(("floodlightCriteria.reportProperties.includeAttributedIPConversions", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "floodlight-criteria.metric-names" => Some(("floodlightCriteria.metricNames", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "cross-dimension-reach-criteria.pivoted" => Some(("crossDimensionReachCriteria.pivoted", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "cross-dimension-reach-criteria.date-range.start-date" => Some(("crossDimensionReachCriteria.dateRange.startDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "cross-dimension-reach-criteria.date-range.kind" => Some(("crossDimensionReachCriteria.dateRange.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "cross-dimension-reach-criteria.date-range.end-date" => Some(("crossDimensionReachCriteria.dateRange.endDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "cross-dimension-reach-criteria.date-range.relative-date-range" => Some(("crossDimensionReachCriteria.dateRange.relativeDateRange", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "cross-dimension-reach-criteria.dimension" => Some(("crossDimensionReachCriteria.dimension", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "cross-dimension-reach-criteria.overlap-metric-names" => Some(("crossDimensionReachCriteria.overlapMetricNames", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "cross-dimension-reach-criteria.metric-names" => Some(("crossDimensionReachCriteria.metricNames", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "active", "activities", "clicks-lookback-window", "criteria", "cross-dimension-reach-criteria", "custom-rich-media-events", "date-range", "delivery", "dimension", "dimension-name", "email-owner", "email-owner-delivery-type", "enable-all-dimension-combinations", "end-date", "etag", "every", "expiration-date", "file-name", "floodlight-config-id", "floodlight-criteria", "format", "id", "impressions-lookback-window", "include-attributed-ip-conversions", "include-unattributed-cookie-conversions", "include-unattributed-ip-conversions", "kind", "last-modified-time", "match-type", "maximum-click-interactions", "maximum-impression-interactions", "maximum-interaction-gap", "message", "metric-names", "name", "overlap-metric-names", "owner-profile-id", "path-to-conversion-criteria", "pivot-on-interaction-path", "pivoted", "reach-by-frequency-metric-names", "reach-criteria", "relative-date-range", "repeats", "repeats-on-week-days", "report-properties", "runs-on-day-of-month", "schedule", "start-date", "sub-account-id", "type", "value"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::Report = json::value::from_value(object).unwrap(); + let mut call = self.hub.reports().update(request, opt.value_of("profile-id").unwrap_or(""), opt.value_of("report-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _sites_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.sites().get(opt.value_of("profile-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _sites_insert(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "subaccount-id" => Some(("subaccountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "directory-site-id-dimension-value.kind" => Some(("directorySiteIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "directory-site-id-dimension-value.value" => Some(("directorySiteIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "directory-site-id-dimension-value.dimension-name" => Some(("directorySiteIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "directory-site-id-dimension-value.etag" => Some(("directorySiteIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "directory-site-id-dimension-value.match-type" => Some(("directorySiteIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "directory-site-id-dimension-value.id" => Some(("directorySiteIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "site-settings.disable-brand-safe-ads" => Some(("siteSettings.disableBrandSafeAds", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "site-settings.active-view-opt-out" => Some(("siteSettings.activeViewOptOut", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "site-settings.lookback-configuration.click-duration" => Some(("siteSettings.lookbackConfiguration.clickDuration", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "site-settings.lookback-configuration.post-impression-activities-duration" => Some(("siteSettings.lookbackConfiguration.postImpressionActivitiesDuration", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "site-settings.disable-new-cookie" => Some(("siteSettings.disableNewCookie", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "site-settings.tag-setting.include-click-through-urls" => Some(("siteSettings.tagSetting.includeClickThroughUrls", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "site-settings.tag-setting.include-click-tracking" => Some(("siteSettings.tagSetting.includeClickTracking", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "site-settings.tag-setting.additional-key-values" => Some(("siteSettings.tagSetting.additionalKeyValues", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "site-settings.tag-setting.keyword-option" => Some(("siteSettings.tagSetting.keywordOption", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "site-settings.creative-settings.i-frame-header" => Some(("siteSettings.creativeSettings.iFrameHeader", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "site-settings.creative-settings.i-frame-footer" => Some(("siteSettings.creativeSettings.iFrameFooter", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "approved" => Some(("approved", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "id-dimension-value.kind" => Some(("idDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.value" => Some(("idDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.dimension-name" => Some(("idDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.etag" => Some(("idDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.match-type" => Some(("idDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.id" => Some(("idDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "key-name" => Some(("keyName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "directory-site-id" => Some(("directorySiteId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "active-view-opt-out", "additional-key-values", "approved", "click-duration", "creative-settings", "dimension-name", "directory-site-id", "directory-site-id-dimension-value", "disable-brand-safe-ads", "disable-new-cookie", "etag", "i-frame-footer", "i-frame-header", "id", "id-dimension-value", "include-click-through-urls", "include-click-tracking", "key-name", "keyword-option", "kind", "lookback-configuration", "match-type", "name", "post-impression-activities-duration", "site-settings", "subaccount-id", "tag-setting", "value"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::Site = json::value::from_value(object).unwrap(); + let mut call = self.hub.sites().insert(request, opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _sites_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.sites().list(opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "unmapped-site" => { + call = call.unmapped_site(arg_from_str(value.unwrap_or("false"), err, "unmapped-site", "boolean")); + }, + "subaccount-id" => { + call = call.subaccount_id(value.unwrap_or("")); + }, + "sort-order" => { + call = call.sort_order(value.unwrap_or("")); + }, + "sort-field" => { + call = call.sort_field(value.unwrap_or("")); + }, + "search-string" => { + call = call.search_string(value.unwrap_or("")); + }, + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "max-results" => { + call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer")); + }, + "ids" => { + call = call.add_ids(value.unwrap_or("")); + }, + "directory-site-ids" => { + call = call.add_directory_site_ids(value.unwrap_or("")); + }, + "campaign-ids" => { + call = call.add_campaign_ids(value.unwrap_or("")); + }, + "approved" => { + call = call.approved(arg_from_str(value.unwrap_or("false"), err, "approved", "boolean")); + }, + "ad-words-site" => { + call = call.ad_words_site(arg_from_str(value.unwrap_or("false"), err, "ad-words-site", "boolean")); + }, + "accepts-publisher-paid-placements" => { + call = call.accepts_publisher_paid_placements(arg_from_str(value.unwrap_or("false"), err, "accepts-publisher-paid-placements", "boolean")); + }, + "accepts-interstitial-placements" => { + call = call.accepts_interstitial_placements(arg_from_str(value.unwrap_or("false"), err, "accepts-interstitial-placements", "boolean")); + }, + "accepts-in-stream-video-placements" => { + call = call.accepts_in_stream_video_placements(arg_from_str(value.unwrap_or("false"), err, "accepts-in-stream-video-placements", "boolean")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["accepts-interstitial-placements", "accepts-publisher-paid-placements", "search-string", "subaccount-id", "directory-site-ids", "sort-field", "ids", "max-results", "page-token", "unmapped-site", "accepts-in-stream-video-placements", "ad-words-site", "campaign-ids", "approved", "sort-order"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _sites_patch(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "subaccount-id" => Some(("subaccountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "directory-site-id-dimension-value.kind" => Some(("directorySiteIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "directory-site-id-dimension-value.value" => Some(("directorySiteIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "directory-site-id-dimension-value.dimension-name" => Some(("directorySiteIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "directory-site-id-dimension-value.etag" => Some(("directorySiteIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "directory-site-id-dimension-value.match-type" => Some(("directorySiteIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "directory-site-id-dimension-value.id" => Some(("directorySiteIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "site-settings.disable-brand-safe-ads" => Some(("siteSettings.disableBrandSafeAds", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "site-settings.active-view-opt-out" => Some(("siteSettings.activeViewOptOut", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "site-settings.lookback-configuration.click-duration" => Some(("siteSettings.lookbackConfiguration.clickDuration", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "site-settings.lookback-configuration.post-impression-activities-duration" => Some(("siteSettings.lookbackConfiguration.postImpressionActivitiesDuration", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "site-settings.disable-new-cookie" => Some(("siteSettings.disableNewCookie", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "site-settings.tag-setting.include-click-through-urls" => Some(("siteSettings.tagSetting.includeClickThroughUrls", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "site-settings.tag-setting.include-click-tracking" => Some(("siteSettings.tagSetting.includeClickTracking", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "site-settings.tag-setting.additional-key-values" => Some(("siteSettings.tagSetting.additionalKeyValues", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "site-settings.tag-setting.keyword-option" => Some(("siteSettings.tagSetting.keywordOption", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "site-settings.creative-settings.i-frame-header" => Some(("siteSettings.creativeSettings.iFrameHeader", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "site-settings.creative-settings.i-frame-footer" => Some(("siteSettings.creativeSettings.iFrameFooter", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "approved" => Some(("approved", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "id-dimension-value.kind" => Some(("idDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.value" => Some(("idDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.dimension-name" => Some(("idDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.etag" => Some(("idDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.match-type" => Some(("idDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.id" => Some(("idDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "key-name" => Some(("keyName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "directory-site-id" => Some(("directorySiteId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "active-view-opt-out", "additional-key-values", "approved", "click-duration", "creative-settings", "dimension-name", "directory-site-id", "directory-site-id-dimension-value", "disable-brand-safe-ads", "disable-new-cookie", "etag", "i-frame-footer", "i-frame-header", "id", "id-dimension-value", "include-click-through-urls", "include-click-tracking", "key-name", "keyword-option", "kind", "lookback-configuration", "match-type", "name", "post-impression-activities-duration", "site-settings", "subaccount-id", "tag-setting", "value"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::Site = json::value::from_value(object).unwrap(); + let mut call = self.hub.sites().patch(request, opt.value_of("profile-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _sites_update(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "subaccount-id" => Some(("subaccountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "directory-site-id-dimension-value.kind" => Some(("directorySiteIdDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "directory-site-id-dimension-value.value" => Some(("directorySiteIdDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "directory-site-id-dimension-value.dimension-name" => Some(("directorySiteIdDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "directory-site-id-dimension-value.etag" => Some(("directorySiteIdDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "directory-site-id-dimension-value.match-type" => Some(("directorySiteIdDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "directory-site-id-dimension-value.id" => Some(("directorySiteIdDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "site-settings.disable-brand-safe-ads" => Some(("siteSettings.disableBrandSafeAds", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "site-settings.active-view-opt-out" => Some(("siteSettings.activeViewOptOut", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "site-settings.lookback-configuration.click-duration" => Some(("siteSettings.lookbackConfiguration.clickDuration", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "site-settings.lookback-configuration.post-impression-activities-duration" => Some(("siteSettings.lookbackConfiguration.postImpressionActivitiesDuration", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "site-settings.disable-new-cookie" => Some(("siteSettings.disableNewCookie", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "site-settings.tag-setting.include-click-through-urls" => Some(("siteSettings.tagSetting.includeClickThroughUrls", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "site-settings.tag-setting.include-click-tracking" => Some(("siteSettings.tagSetting.includeClickTracking", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "site-settings.tag-setting.additional-key-values" => Some(("siteSettings.tagSetting.additionalKeyValues", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "site-settings.tag-setting.keyword-option" => Some(("siteSettings.tagSetting.keywordOption", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "site-settings.creative-settings.i-frame-header" => Some(("siteSettings.creativeSettings.iFrameHeader", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "site-settings.creative-settings.i-frame-footer" => Some(("siteSettings.creativeSettings.iFrameFooter", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "approved" => Some(("approved", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "id-dimension-value.kind" => Some(("idDimensionValue.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.value" => Some(("idDimensionValue.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.dimension-name" => Some(("idDimensionValue.dimensionName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.etag" => Some(("idDimensionValue.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.match-type" => Some(("idDimensionValue.matchType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id-dimension-value.id" => Some(("idDimensionValue.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "key-name" => Some(("keyName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "directory-site-id" => Some(("directorySiteId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "active-view-opt-out", "additional-key-values", "approved", "click-duration", "creative-settings", "dimension-name", "directory-site-id", "directory-site-id-dimension-value", "disable-brand-safe-ads", "disable-new-cookie", "etag", "i-frame-footer", "i-frame-header", "id", "id-dimension-value", "include-click-through-urls", "include-click-tracking", "key-name", "keyword-option", "kind", "lookback-configuration", "match-type", "name", "post-impression-activities-duration", "site-settings", "subaccount-id", "tag-setting", "value"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::Site = json::value::from_value(object).unwrap(); + let mut call = self.hub.sites().update(request, opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _sizes_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.sizes().get(opt.value_of("profile-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _sizes_insert(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "width" => Some(("width", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "iab" => Some(("iab", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "height" => Some(("height", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["height", "iab", "id", "kind", "width"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::Size = json::value::from_value(object).unwrap(); + let mut call = self.hub.sizes().insert(request, opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _sizes_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.sizes().list(opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "width" => { + call = call.width(arg_from_str(value.unwrap_or("-0"), err, "width", "integer")); + }, + "ids" => { + call = call.add_ids(value.unwrap_or("")); + }, + "iab-standard" => { + call = call.iab_standard(arg_from_str(value.unwrap_or("false"), err, "iab-standard", "boolean")); + }, + "height" => { + call = call.height(arg_from_str(value.unwrap_or("-0"), err, "height", "integer")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["iab-standard", "width", "ids", "height"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _subaccounts_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.subaccounts().get(opt.value_of("profile-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _subaccounts_insert(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "available-permission-ids" => Some(("availablePermissionIds", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "available-permission-ids", "id", "kind", "name"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::Subaccount = json::value::from_value(object).unwrap(); + let mut call = self.hub.subaccounts().insert(request, opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _subaccounts_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.subaccounts().list(opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "sort-order" => { + call = call.sort_order(value.unwrap_or("")); + }, + "sort-field" => { + call = call.sort_field(value.unwrap_or("")); + }, + "search-string" => { + call = call.search_string(value.unwrap_or("")); + }, + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "max-results" => { + call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer")); + }, + "ids" => { + call = call.add_ids(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["search-string", "sort-field", "ids", "max-results", "page-token", "sort-order"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _subaccounts_patch(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "available-permission-ids" => Some(("availablePermissionIds", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "available-permission-ids", "id", "kind", "name"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::Subaccount = json::value::from_value(object).unwrap(); + let mut call = self.hub.subaccounts().patch(request, opt.value_of("profile-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _subaccounts_update(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "available-permission-ids" => Some(("availablePermissionIds", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "available-permission-ids", "id", "kind", "name"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::Subaccount = json::value::from_value(object).unwrap(); + let mut call = self.hub.subaccounts().update(request, opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _targetable_remarketing_lists_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.targetable_remarketing_lists().get(opt.value_of("profile-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _targetable_remarketing_lists_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.targetable_remarketing_lists().list(opt.value_of("profile-id").unwrap_or(""), opt.value_of("advertiser-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "sort-order" => { + call = call.sort_order(value.unwrap_or("")); + }, + "sort-field" => { + call = call.sort_field(value.unwrap_or("")); + }, + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "name" => { + call = call.name(value.unwrap_or("")); + }, + "max-results" => { + call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer")); + }, + "active" => { + call = call.active(arg_from_str(value.unwrap_or("false"), err, "active", "boolean")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["name", "sort-field", "max-results", "page-token", "sort-order", "active"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _user_profiles_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.user_profiles().get(opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _user_profiles_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.user_profiles().list(); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _user_role_permission_groups_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.user_role_permission_groups().get(opt.value_of("profile-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _user_role_permission_groups_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.user_role_permission_groups().list(opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _user_role_permissions_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.user_role_permissions().get(opt.value_of("profile-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _user_role_permissions_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.user_role_permissions().list(opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "ids" => { + call = call.add_ids(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["ids"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _user_roles_delete(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.user_roles().delete(opt.value_of("profile-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok(mut response) => { + Ok(()) + } + } + } + } + + fn _user_roles_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.user_roles().get(opt.value_of("profile-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _user_roles_insert(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "default-user-role" => Some(("defaultUserRole", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "subaccount-id" => Some(("subaccountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "parent-user-role-id" => Some(("parentUserRoleId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "default-user-role", "id", "kind", "name", "parent-user-role-id", "subaccount-id"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::UserRole = json::value::from_value(object).unwrap(); + let mut call = self.hub.user_roles().insert(request, opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _user_roles_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.user_roles().list(opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "subaccount-id" => { + call = call.subaccount_id(value.unwrap_or("")); + }, + "sort-order" => { + call = call.sort_order(value.unwrap_or("")); + }, + "sort-field" => { + call = call.sort_field(value.unwrap_or("")); + }, + "search-string" => { + call = call.search_string(value.unwrap_or("")); + }, + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "max-results" => { + call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer")); + }, + "ids" => { + call = call.add_ids(value.unwrap_or("")); + }, + "account-user-role-only" => { + call = call.account_user_role_only(arg_from_str(value.unwrap_or("false"), err, "account-user-role-only", "boolean")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["search-string", "subaccount-id", "sort-field", "ids", "max-results", "page-token", "sort-order", "account-user-role-only"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _user_roles_patch(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "default-user-role" => Some(("defaultUserRole", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "subaccount-id" => Some(("subaccountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "parent-user-role-id" => Some(("parentUserRoleId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "default-user-role", "id", "kind", "name", "parent-user-role-id", "subaccount-id"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::UserRole = json::value::from_value(object).unwrap(); + let mut call = self.hub.user_roles().patch(request, opt.value_of("profile-id").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _user_roles_update(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "default-user-role" => Some(("defaultUserRole", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "subaccount-id" => Some(("subaccountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "parent-user-role-id" => Some(("parentUserRoleId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "default-user-role", "id", "kind", "name", "parent-user-role-id", "subaccount-id"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::UserRole = json::value::from_value(object).unwrap(); + let mut call = self.hub.user_roles().update(request, opt.value_of("profile-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _doit(&self, dry_run: bool) -> Result, Option> { + let mut err = InvalidOptionsError::new(); + let mut call_result: Result<(), DoitError> = Ok(()); + let mut err_opt: Option = None; + match self.opt.subcommand() { + ("account-active-ad-summaries", Some(opt)) => { + match opt.subcommand() { + ("get", Some(opt)) => { + call_result = self._account_active_ad_summaries_get(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("account-active-ad-summaries".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("account-permission-groups", Some(opt)) => { + match opt.subcommand() { + ("get", Some(opt)) => { + call_result = self._account_permission_groups_get(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._account_permission_groups_list(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("account-permission-groups".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("account-permissions", Some(opt)) => { + match opt.subcommand() { + ("get", Some(opt)) => { + call_result = self._account_permissions_get(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._account_permissions_list(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("account-permissions".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("account-user-profiles", Some(opt)) => { + match opt.subcommand() { + ("get", Some(opt)) => { + call_result = self._account_user_profiles_get(opt, dry_run, &mut err); + }, + ("insert", Some(opt)) => { + call_result = self._account_user_profiles_insert(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._account_user_profiles_list(opt, dry_run, &mut err); + }, + ("patch", Some(opt)) => { + call_result = self._account_user_profiles_patch(opt, dry_run, &mut err); + }, + ("update", Some(opt)) => { + call_result = self._account_user_profiles_update(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("account-user-profiles".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("accounts", Some(opt)) => { + match opt.subcommand() { + ("get", Some(opt)) => { + call_result = self._accounts_get(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._accounts_list(opt, dry_run, &mut err); + }, + ("patch", Some(opt)) => { + call_result = self._accounts_patch(opt, dry_run, &mut err); + }, + ("update", Some(opt)) => { + call_result = self._accounts_update(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("accounts".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("ads", Some(opt)) => { + match opt.subcommand() { + ("get", Some(opt)) => { + call_result = self._ads_get(opt, dry_run, &mut err); + }, + ("insert", Some(opt)) => { + call_result = self._ads_insert(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._ads_list(opt, dry_run, &mut err); + }, + ("patch", Some(opt)) => { + call_result = self._ads_patch(opt, dry_run, &mut err); + }, + ("update", Some(opt)) => { + call_result = self._ads_update(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("ads".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("advertiser-groups", Some(opt)) => { + match opt.subcommand() { + ("delete", Some(opt)) => { + call_result = self._advertiser_groups_delete(opt, dry_run, &mut err); + }, + ("get", Some(opt)) => { + call_result = self._advertiser_groups_get(opt, dry_run, &mut err); + }, + ("insert", Some(opt)) => { + call_result = self._advertiser_groups_insert(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._advertiser_groups_list(opt, dry_run, &mut err); + }, + ("patch", Some(opt)) => { + call_result = self._advertiser_groups_patch(opt, dry_run, &mut err); + }, + ("update", Some(opt)) => { + call_result = self._advertiser_groups_update(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("advertiser-groups".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("advertisers", Some(opt)) => { + match opt.subcommand() { + ("get", Some(opt)) => { + call_result = self._advertisers_get(opt, dry_run, &mut err); + }, + ("insert", Some(opt)) => { + call_result = self._advertisers_insert(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._advertisers_list(opt, dry_run, &mut err); + }, + ("patch", Some(opt)) => { + call_result = self._advertisers_patch(opt, dry_run, &mut err); + }, + ("update", Some(opt)) => { + call_result = self._advertisers_update(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("advertisers".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("browsers", Some(opt)) => { + match opt.subcommand() { + ("list", Some(opt)) => { + call_result = self._browsers_list(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("browsers".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("campaign-creative-associations", Some(opt)) => { + match opt.subcommand() { + ("insert", Some(opt)) => { + call_result = self._campaign_creative_associations_insert(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._campaign_creative_associations_list(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("campaign-creative-associations".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("campaigns", Some(opt)) => { + match opt.subcommand() { + ("get", Some(opt)) => { + call_result = self._campaigns_get(opt, dry_run, &mut err); + }, + ("insert", Some(opt)) => { + call_result = self._campaigns_insert(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._campaigns_list(opt, dry_run, &mut err); + }, + ("patch", Some(opt)) => { + call_result = self._campaigns_patch(opt, dry_run, &mut err); + }, + ("update", Some(opt)) => { + call_result = self._campaigns_update(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("campaigns".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("change-logs", Some(opt)) => { + match opt.subcommand() { + ("get", Some(opt)) => { + call_result = self._change_logs_get(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._change_logs_list(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("change-logs".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("cities", Some(opt)) => { + match opt.subcommand() { + ("list", Some(opt)) => { + call_result = self._cities_list(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("cities".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("connection-types", Some(opt)) => { + match opt.subcommand() { + ("get", Some(opt)) => { + call_result = self._connection_types_get(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._connection_types_list(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("connection-types".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("content-categories", Some(opt)) => { + match opt.subcommand() { + ("delete", Some(opt)) => { + call_result = self._content_categories_delete(opt, dry_run, &mut err); + }, + ("get", Some(opt)) => { + call_result = self._content_categories_get(opt, dry_run, &mut err); + }, + ("insert", Some(opt)) => { + call_result = self._content_categories_insert(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._content_categories_list(opt, dry_run, &mut err); + }, + ("patch", Some(opt)) => { + call_result = self._content_categories_patch(opt, dry_run, &mut err); + }, + ("update", Some(opt)) => { + call_result = self._content_categories_update(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("content-categories".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("countries", Some(opt)) => { + match opt.subcommand() { + ("get", Some(opt)) => { + call_result = self._countries_get(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._countries_list(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("countries".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("creative-assets", Some(opt)) => { + match opt.subcommand() { + ("insert", Some(opt)) => { + call_result = self._creative_assets_insert(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("creative-assets".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("creative-field-values", Some(opt)) => { + match opt.subcommand() { + ("delete", Some(opt)) => { + call_result = self._creative_field_values_delete(opt, dry_run, &mut err); + }, + ("get", Some(opt)) => { + call_result = self._creative_field_values_get(opt, dry_run, &mut err); + }, + ("insert", Some(opt)) => { + call_result = self._creative_field_values_insert(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._creative_field_values_list(opt, dry_run, &mut err); + }, + ("patch", Some(opt)) => { + call_result = self._creative_field_values_patch(opt, dry_run, &mut err); + }, + ("update", Some(opt)) => { + call_result = self._creative_field_values_update(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("creative-field-values".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("creative-fields", Some(opt)) => { + match opt.subcommand() { + ("delete", Some(opt)) => { + call_result = self._creative_fields_delete(opt, dry_run, &mut err); + }, + ("get", Some(opt)) => { + call_result = self._creative_fields_get(opt, dry_run, &mut err); + }, + ("insert", Some(opt)) => { + call_result = self._creative_fields_insert(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._creative_fields_list(opt, dry_run, &mut err); + }, + ("patch", Some(opt)) => { + call_result = self._creative_fields_patch(opt, dry_run, &mut err); + }, + ("update", Some(opt)) => { + call_result = self._creative_fields_update(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("creative-fields".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("creative-groups", Some(opt)) => { + match opt.subcommand() { + ("get", Some(opt)) => { + call_result = self._creative_groups_get(opt, dry_run, &mut err); + }, + ("insert", Some(opt)) => { + call_result = self._creative_groups_insert(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._creative_groups_list(opt, dry_run, &mut err); + }, + ("patch", Some(opt)) => { + call_result = self._creative_groups_patch(opt, dry_run, &mut err); + }, + ("update", Some(opt)) => { + call_result = self._creative_groups_update(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("creative-groups".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("creatives", Some(opt)) => { + match opt.subcommand() { + ("get", Some(opt)) => { + call_result = self._creatives_get(opt, dry_run, &mut err); + }, + ("insert", Some(opt)) => { + call_result = self._creatives_insert(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._creatives_list(opt, dry_run, &mut err); + }, + ("patch", Some(opt)) => { + call_result = self._creatives_patch(opt, dry_run, &mut err); + }, + ("update", Some(opt)) => { + call_result = self._creatives_update(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("creatives".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("dimension-values", Some(opt)) => { + match opt.subcommand() { + ("query", Some(opt)) => { + call_result = self._dimension_values_query(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("dimension-values".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("directory-site-contacts", Some(opt)) => { + match opt.subcommand() { + ("get", Some(opt)) => { + call_result = self._directory_site_contacts_get(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._directory_site_contacts_list(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("directory-site-contacts".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("directory-sites", Some(opt)) => { + match opt.subcommand() { + ("get", Some(opt)) => { + call_result = self._directory_sites_get(opt, dry_run, &mut err); + }, + ("insert", Some(opt)) => { + call_result = self._directory_sites_insert(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._directory_sites_list(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("directory-sites".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("event-tags", Some(opt)) => { + match opt.subcommand() { + ("delete", Some(opt)) => { + call_result = self._event_tags_delete(opt, dry_run, &mut err); + }, + ("get", Some(opt)) => { + call_result = self._event_tags_get(opt, dry_run, &mut err); + }, + ("insert", Some(opt)) => { + call_result = self._event_tags_insert(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._event_tags_list(opt, dry_run, &mut err); + }, + ("patch", Some(opt)) => { + call_result = self._event_tags_patch(opt, dry_run, &mut err); + }, + ("update", Some(opt)) => { + call_result = self._event_tags_update(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("event-tags".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("files", Some(opt)) => { + match opt.subcommand() { + ("get", Some(opt)) => { + call_result = self._files_get(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._files_list(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("files".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("floodlight-activities", Some(opt)) => { + match opt.subcommand() { + ("delete", Some(opt)) => { + call_result = self._floodlight_activities_delete(opt, dry_run, &mut err); + }, + ("generatetag", Some(opt)) => { + call_result = self._floodlight_activities_generatetag(opt, dry_run, &mut err); + }, + ("get", Some(opt)) => { + call_result = self._floodlight_activities_get(opt, dry_run, &mut err); + }, + ("insert", Some(opt)) => { + call_result = self._floodlight_activities_insert(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._floodlight_activities_list(opt, dry_run, &mut err); + }, + ("patch", Some(opt)) => { + call_result = self._floodlight_activities_patch(opt, dry_run, &mut err); + }, + ("update", Some(opt)) => { + call_result = self._floodlight_activities_update(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("floodlight-activities".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("floodlight-activity-groups", Some(opt)) => { + match opt.subcommand() { + ("delete", Some(opt)) => { + call_result = self._floodlight_activity_groups_delete(opt, dry_run, &mut err); + }, + ("get", Some(opt)) => { + call_result = self._floodlight_activity_groups_get(opt, dry_run, &mut err); + }, + ("insert", Some(opt)) => { + call_result = self._floodlight_activity_groups_insert(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._floodlight_activity_groups_list(opt, dry_run, &mut err); + }, + ("patch", Some(opt)) => { + call_result = self._floodlight_activity_groups_patch(opt, dry_run, &mut err); + }, + ("update", Some(opt)) => { + call_result = self._floodlight_activity_groups_update(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("floodlight-activity-groups".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("floodlight-configurations", Some(opt)) => { + match opt.subcommand() { + ("get", Some(opt)) => { + call_result = self._floodlight_configurations_get(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._floodlight_configurations_list(opt, dry_run, &mut err); + }, + ("patch", Some(opt)) => { + call_result = self._floodlight_configurations_patch(opt, dry_run, &mut err); + }, + ("update", Some(opt)) => { + call_result = self._floodlight_configurations_update(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("floodlight-configurations".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("inventory-items", Some(opt)) => { + match opt.subcommand() { + ("get", Some(opt)) => { + call_result = self._inventory_items_get(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._inventory_items_list(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("inventory-items".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("landing-pages", Some(opt)) => { + match opt.subcommand() { + ("delete", Some(opt)) => { + call_result = self._landing_pages_delete(opt, dry_run, &mut err); + }, + ("get", Some(opt)) => { + call_result = self._landing_pages_get(opt, dry_run, &mut err); + }, + ("insert", Some(opt)) => { + call_result = self._landing_pages_insert(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._landing_pages_list(opt, dry_run, &mut err); + }, + ("patch", Some(opt)) => { + call_result = self._landing_pages_patch(opt, dry_run, &mut err); + }, + ("update", Some(opt)) => { + call_result = self._landing_pages_update(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("landing-pages".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("metros", Some(opt)) => { + match opt.subcommand() { + ("list", Some(opt)) => { + call_result = self._metros_list(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("metros".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("mobile-carriers", Some(opt)) => { + match opt.subcommand() { + ("get", Some(opt)) => { + call_result = self._mobile_carriers_get(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._mobile_carriers_list(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("mobile-carriers".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("operating-system-versions", Some(opt)) => { + match opt.subcommand() { + ("get", Some(opt)) => { + call_result = self._operating_system_versions_get(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._operating_system_versions_list(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("operating-system-versions".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("operating-systems", Some(opt)) => { + match opt.subcommand() { + ("get", Some(opt)) => { + call_result = self._operating_systems_get(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._operating_systems_list(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("operating-systems".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("order-documents", Some(opt)) => { + match opt.subcommand() { + ("get", Some(opt)) => { + call_result = self._order_documents_get(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._order_documents_list(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("order-documents".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("orders", Some(opt)) => { + match opt.subcommand() { + ("get", Some(opt)) => { + call_result = self._orders_get(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._orders_list(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("orders".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("placement-groups", Some(opt)) => { + match opt.subcommand() { + ("get", Some(opt)) => { + call_result = self._placement_groups_get(opt, dry_run, &mut err); + }, + ("insert", Some(opt)) => { + call_result = self._placement_groups_insert(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._placement_groups_list(opt, dry_run, &mut err); + }, + ("patch", Some(opt)) => { + call_result = self._placement_groups_patch(opt, dry_run, &mut err); + }, + ("update", Some(opt)) => { + call_result = self._placement_groups_update(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("placement-groups".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("placement-strategies", Some(opt)) => { + match opt.subcommand() { + ("delete", Some(opt)) => { + call_result = self._placement_strategies_delete(opt, dry_run, &mut err); + }, + ("get", Some(opt)) => { + call_result = self._placement_strategies_get(opt, dry_run, &mut err); + }, + ("insert", Some(opt)) => { + call_result = self._placement_strategies_insert(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._placement_strategies_list(opt, dry_run, &mut err); + }, + ("patch", Some(opt)) => { + call_result = self._placement_strategies_patch(opt, dry_run, &mut err); + }, + ("update", Some(opt)) => { + call_result = self._placement_strategies_update(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("placement-strategies".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("placements", Some(opt)) => { + match opt.subcommand() { + ("generatetags", Some(opt)) => { + call_result = self._placements_generatetags(opt, dry_run, &mut err); + }, + ("get", Some(opt)) => { + call_result = self._placements_get(opt, dry_run, &mut err); + }, + ("insert", Some(opt)) => { + call_result = self._placements_insert(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._placements_list(opt, dry_run, &mut err); + }, + ("patch", Some(opt)) => { + call_result = self._placements_patch(opt, dry_run, &mut err); + }, + ("update", Some(opt)) => { + call_result = self._placements_update(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("placements".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("platform-types", Some(opt)) => { + match opt.subcommand() { + ("get", Some(opt)) => { + call_result = self._platform_types_get(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._platform_types_list(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("platform-types".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("postal-codes", Some(opt)) => { + match opt.subcommand() { + ("get", Some(opt)) => { + call_result = self._postal_codes_get(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._postal_codes_list(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("postal-codes".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("projects", Some(opt)) => { + match opt.subcommand() { + ("get", Some(opt)) => { + call_result = self._projects_get(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._projects_list(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("projects".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("regions", Some(opt)) => { + match opt.subcommand() { + ("list", Some(opt)) => { + call_result = self._regions_list(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("regions".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("remarketing-list-shares", Some(opt)) => { + match opt.subcommand() { + ("get", Some(opt)) => { + call_result = self._remarketing_list_shares_get(opt, dry_run, &mut err); + }, + ("patch", Some(opt)) => { + call_result = self._remarketing_list_shares_patch(opt, dry_run, &mut err); + }, + ("update", Some(opt)) => { + call_result = self._remarketing_list_shares_update(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("remarketing-list-shares".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("remarketing-lists", Some(opt)) => { + match opt.subcommand() { + ("get", Some(opt)) => { + call_result = self._remarketing_lists_get(opt, dry_run, &mut err); + }, + ("insert", Some(opt)) => { + call_result = self._remarketing_lists_insert(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._remarketing_lists_list(opt, dry_run, &mut err); + }, + ("patch", Some(opt)) => { + call_result = self._remarketing_lists_patch(opt, dry_run, &mut err); + }, + ("update", Some(opt)) => { + call_result = self._remarketing_lists_update(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("remarketing-lists".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("reports", Some(opt)) => { + match opt.subcommand() { + ("compatible-fields-query", Some(opt)) => { + call_result = self._reports_compatible_fields_query(opt, dry_run, &mut err); + }, + ("delete", Some(opt)) => { + call_result = self._reports_delete(opt, dry_run, &mut err); + }, + ("files-get", Some(opt)) => { + call_result = self._reports_files_get(opt, dry_run, &mut err); + }, + ("files-list", Some(opt)) => { + call_result = self._reports_files_list(opt, dry_run, &mut err); + }, + ("get", Some(opt)) => { + call_result = self._reports_get(opt, dry_run, &mut err); + }, + ("insert", Some(opt)) => { + call_result = self._reports_insert(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._reports_list(opt, dry_run, &mut err); + }, + ("patch", Some(opt)) => { + call_result = self._reports_patch(opt, dry_run, &mut err); + }, + ("run", Some(opt)) => { + call_result = self._reports_run(opt, dry_run, &mut err); + }, + ("update", Some(opt)) => { + call_result = self._reports_update(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("reports".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("sites", Some(opt)) => { + match opt.subcommand() { + ("get", Some(opt)) => { + call_result = self._sites_get(opt, dry_run, &mut err); + }, + ("insert", Some(opt)) => { + call_result = self._sites_insert(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._sites_list(opt, dry_run, &mut err); + }, + ("patch", Some(opt)) => { + call_result = self._sites_patch(opt, dry_run, &mut err); + }, + ("update", Some(opt)) => { + call_result = self._sites_update(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("sites".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("sizes", Some(opt)) => { + match opt.subcommand() { + ("get", Some(opt)) => { + call_result = self._sizes_get(opt, dry_run, &mut err); + }, + ("insert", Some(opt)) => { + call_result = self._sizes_insert(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._sizes_list(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("sizes".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("subaccounts", Some(opt)) => { + match opt.subcommand() { + ("get", Some(opt)) => { + call_result = self._subaccounts_get(opt, dry_run, &mut err); + }, + ("insert", Some(opt)) => { + call_result = self._subaccounts_insert(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._subaccounts_list(opt, dry_run, &mut err); + }, + ("patch", Some(opt)) => { + call_result = self._subaccounts_patch(opt, dry_run, &mut err); + }, + ("update", Some(opt)) => { + call_result = self._subaccounts_update(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("subaccounts".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("targetable-remarketing-lists", Some(opt)) => { + match opt.subcommand() { + ("get", Some(opt)) => { + call_result = self._targetable_remarketing_lists_get(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._targetable_remarketing_lists_list(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("targetable-remarketing-lists".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("user-profiles", Some(opt)) => { + match opt.subcommand() { + ("get", Some(opt)) => { + call_result = self._user_profiles_get(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._user_profiles_list(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("user-profiles".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("user-role-permission-groups", Some(opt)) => { + match opt.subcommand() { + ("get", Some(opt)) => { + call_result = self._user_role_permission_groups_get(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._user_role_permission_groups_list(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("user-role-permission-groups".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("user-role-permissions", Some(opt)) => { + match opt.subcommand() { + ("get", Some(opt)) => { + call_result = self._user_role_permissions_get(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._user_role_permissions_list(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("user-role-permissions".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("user-roles", Some(opt)) => { + match opt.subcommand() { + ("delete", Some(opt)) => { + call_result = self._user_roles_delete(opt, dry_run, &mut err); + }, + ("get", Some(opt)) => { + call_result = self._user_roles_get(opt, dry_run, &mut err); + }, + ("insert", Some(opt)) => { + call_result = self._user_roles_insert(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._user_roles_list(opt, dry_run, &mut err); + }, + ("patch", Some(opt)) => { + call_result = self._user_roles_patch(opt, dry_run, &mut err); + }, + ("update", Some(opt)) => { + call_result = self._user_roles_update(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("user-roles".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + _ => { + err.issues.push(CLIError::MissingCommandError); + writeln!(io::stderr(), "{}\n", self.opt.usage()).ok(); + } + } + + if dry_run { + if err.issues.len() > 0 { + err_opt = Some(err); + } + Err(err_opt) + } else { + Ok(call_result) + } + } + + // Please note that this call will fail if any part of the opt can't be handled + fn new(opt: ArgMatches<'a, 'n>) -> Result, InvalidOptionsError> { + let (config_dir, secret) = { + let config_dir = match cmn::assure_config_dir_exists(opt.value_of("folder").unwrap_or("~/.google-service-cli")) { + Err(e) => return Err(InvalidOptionsError::single(e, 3)), + Ok(p) => p, + }; + + match cmn::application_secret_from_directory(&config_dir, "dfareporting2d2-secret.json", + "{\"installed\":{\"auth_uri\":\"https://accounts.google.com/o/oauth2/auth\",\"client_secret\":\"hCsslbCUyfehWMmbkG8vTYxG\",\"token_uri\":\"https://accounts.google.com/o/oauth2/token\",\"client_email\":\"\",\"redirect_uris\":[\"urn:ietf:wg:oauth:2.0:oob\",\"oob\"],\"client_x509_cert_url\":\"\",\"client_id\":\"620010449518-9ngf7o4dhs0dka470npqvor6dc5lqb9b.apps.googleusercontent.com\",\"auth_provider_x509_cert_url\":\"https://www.googleapis.com/oauth2/v1/certs\"}}") { + Ok(secret) => (config_dir, secret), + Err(e) => return Err(InvalidOptionsError::single(e, 4)) + } + }; + + let auth = Authenticator::new( &secret, DefaultAuthenticatorDelegate, + if opt.is_present("debug-auth") { + hyper::Client::with_connector(mock::TeeConnector { + connector: hyper::net::HttpsConnector::::default() + }) + } else { + hyper::Client::new() + }, + JsonTokenStorage { + program_name: "dfareporting2d2", + db_dir: config_dir.clone(), + }, None); + + let client = + if opt.is_present("debug") { + hyper::Client::with_connector(mock::TeeConnector { + connector: hyper::net::HttpsConnector::::default() + }) + } else { + hyper::Client::new() + }; + let engine = Engine { + opt: opt, + hub: api::Dfareporting::new(client, auth), + gp: vec!["alt", "fields", "key", "oauth-token", "pretty-print", "quota-user", "user-ip"], + gpm: vec![ + ("oauth-token", "oauth_token"), + ("pretty-print", "prettyPrint"), + ("quota-user", "quotaUser"), + ("user-ip", "userIp"), + ] + }; + + match engine._doit(true) { + Err(Some(err)) => Err(err), + Err(None) => Ok(engine), + Ok(_) => unreachable!(), + } + } + + fn doit(&self) -> Result<(), DoitError> { + match self._doit(false) { + Ok(res) => res, + Err(_) => unreachable!(), + } + } +} + +fn main() { + let mut exit_status = 0i32; + let upload_value_names = ["mode", "file"]; + let arg_data = [ + ("account-active-ad-summaries", "methods: 'get'", vec![ + ("get", + Some(r##"Gets the account's active ad summary by account ID."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/account-active-ad-summaries_get", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"summary-account-id"##), + None, + Some(r##"Account ID."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("account-permission-groups", "methods: 'get' and 'list'", vec![ + ("get", + Some(r##"Gets one account permission group by ID."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/account-permission-groups_get", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"Account permission group ID."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Retrieves the list of account permission groups."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/account-permission-groups_list", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("account-permissions", "methods: 'get' and 'list'", vec![ + ("get", + Some(r##"Gets one account permission by ID."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/account-permissions_get", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"Account permission ID."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Retrieves the list of account permissions."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/account-permissions_list", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("account-user-profiles", "methods: 'get', 'insert', 'list', 'patch' and 'update'", vec![ + ("get", + Some(r##"Gets one account user profile by ID."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/account-user-profiles_get", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"User profile ID."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("insert", + Some(r##"Inserts a new account user profile."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/account-user-profiles_insert", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Retrieves a list of account user profiles, possibly filtered."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/account-user-profiles_list", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("patch", + Some(r##"Updates an existing account user profile. This method supports patch semantics."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/account-user-profiles_patch", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"User profile ID."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("update", + Some(r##"Updates an existing account user profile."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/account-user-profiles_update", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("accounts", "methods: 'get', 'list', 'patch' and 'update'", vec![ + ("get", + Some(r##"Gets one account by ID."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/accounts_get", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"Account ID."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Retrieves the list of accounts, possibly filtered."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/accounts_list", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("patch", + Some(r##"Updates an existing account. This method supports patch semantics."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/accounts_patch", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"Account ID."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("update", + Some(r##"Updates an existing account."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/accounts_update", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("ads", "methods: 'get', 'insert', 'list', 'patch' and 'update'", vec![ + ("get", + Some(r##"Gets one ad by ID."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/ads_get", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"Ad ID."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("insert", + Some(r##"Inserts a new ad."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/ads_insert", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Retrieves a list of ads, possibly filtered."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/ads_list", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("patch", + Some(r##"Updates an existing ad. This method supports patch semantics."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/ads_patch", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"Ad ID."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("update", + Some(r##"Updates an existing ad."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/ads_update", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("advertiser-groups", "methods: 'delete', 'get', 'insert', 'list', 'patch' and 'update'", vec![ + ("delete", + Some(r##"Deletes an existing advertiser group."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/advertiser-groups_delete", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"Advertiser group ID."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + ]), + ("get", + Some(r##"Gets one advertiser group by ID."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/advertiser-groups_get", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"Advertiser group ID."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("insert", + Some(r##"Inserts a new advertiser group."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/advertiser-groups_insert", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Retrieves a list of advertiser groups, possibly filtered."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/advertiser-groups_list", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("patch", + Some(r##"Updates an existing advertiser group. This method supports patch semantics."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/advertiser-groups_patch", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"Advertiser group ID."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("update", + Some(r##"Updates an existing advertiser group."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/advertiser-groups_update", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("advertisers", "methods: 'get', 'insert', 'list', 'patch' and 'update'", vec![ + ("get", + Some(r##"Gets one advertiser by ID."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/advertisers_get", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"Advertiser ID."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("insert", + Some(r##"Inserts a new advertiser."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/advertisers_insert", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Retrieves a list of advertisers, possibly filtered."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/advertisers_list", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("patch", + Some(r##"Updates an existing advertiser. This method supports patch semantics."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/advertisers_patch", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"Advertiser ID."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("update", + Some(r##"Updates an existing advertiser."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/advertisers_update", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("browsers", "methods: 'list'", vec![ + ("list", + Some(r##"Retrieves a list of browsers."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/browsers_list", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("campaign-creative-associations", "methods: 'insert' and 'list'", vec![ + ("insert", + Some(r##"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."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/campaign-creative-associations_insert", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"campaign-id"##), + None, + Some(r##"Campaign ID in this association."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Retrieves the list of creative IDs associated with the specified campaign."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/campaign-creative-associations_list", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"campaign-id"##), + None, + Some(r##"Campaign ID in this association."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("campaigns", "methods: 'get', 'insert', 'list', 'patch' and 'update'", vec![ + ("get", + Some(r##"Gets one campaign by ID."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/campaigns_get", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"Campaign ID."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("insert", + Some(r##"Inserts a new campaign."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/campaigns_insert", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"default-landing-page-name"##), + None, + Some(r##"Default landing page name for this new campaign. Must be less than 256 characters long."##), + Some(true), + Some(false)), + + (Some(r##"default-landing-page-url"##), + None, + Some(r##"Default landing page URL for this new campaign."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Retrieves a list of campaigns, possibly filtered."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/campaigns_list", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("patch", + Some(r##"Updates an existing campaign. This method supports patch semantics."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/campaigns_patch", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"Campaign ID."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("update", + Some(r##"Updates an existing campaign."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/campaigns_update", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("change-logs", "methods: 'get' and 'list'", vec![ + ("get", + Some(r##"Gets one change log by ID."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/change-logs_get", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"Change log ID."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Retrieves a list of change logs."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/change-logs_list", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("cities", "methods: 'list'", vec![ + ("list", + Some(r##"Retrieves a list of cities, possibly filtered."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/cities_list", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("connection-types", "methods: 'get' and 'list'", vec![ + ("get", + Some(r##"Gets one connection type by ID."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/connection-types_get", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"Connection type ID."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Retrieves a list of connection types."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/connection-types_list", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("content-categories", "methods: 'delete', 'get', 'insert', 'list', 'patch' and 'update'", vec![ + ("delete", + Some(r##"Deletes an existing content category."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/content-categories_delete", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"Content category ID."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + ]), + ("get", + Some(r##"Gets one content category by ID."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/content-categories_get", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"Content category ID."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("insert", + Some(r##"Inserts a new content category."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/content-categories_insert", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Retrieves a list of content categories, possibly filtered."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/content-categories_list", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("patch", + Some(r##"Updates an existing content category. This method supports patch semantics."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/content-categories_patch", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"Content category ID."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("update", + Some(r##"Updates an existing content category."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/content-categories_update", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("countries", "methods: 'get' and 'list'", vec![ + ("get", + Some(r##"Gets one country by ID."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/countries_get", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"dart-id"##), + None, + Some(r##"Country DART ID."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Retrieves a list of countries."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/countries_list", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("creative-assets", "methods: 'insert'", vec![ + ("insert", + Some(r##"Inserts a new creative asset."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/creative-assets_insert", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"advertiser-id"##), + None, + Some(r##"Advertiser ID of this creative. This is a required field."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"mode"##), + Some(r##"u"##), + Some(r##"Specify the upload protocol (simple|resumable) and the file to upload"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("creative-field-values", "methods: 'delete', 'get', 'insert', 'list', 'patch' and 'update'", vec![ + ("delete", + Some(r##"Deletes an existing creative field value."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/creative-field-values_delete", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"creative-field-id"##), + None, + Some(r##"Creative field ID for this creative field value."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"Creative Field Value ID"##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + ]), + ("get", + Some(r##"Gets one creative field value by ID."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/creative-field-values_get", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"creative-field-id"##), + None, + Some(r##"Creative field ID for this creative field value."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"Creative Field Value ID"##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("insert", + Some(r##"Inserts a new creative field value."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/creative-field-values_insert", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"creative-field-id"##), + None, + Some(r##"Creative field ID for this creative field value."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Retrieves a list of creative field values, possibly filtered."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/creative-field-values_list", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"creative-field-id"##), + None, + Some(r##"Creative field ID for this creative field value."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("patch", + Some(r##"Updates an existing creative field value. This method supports patch semantics."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/creative-field-values_patch", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"creative-field-id"##), + None, + Some(r##"Creative field ID for this creative field value."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"Creative Field Value ID"##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("update", + Some(r##"Updates an existing creative field value."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/creative-field-values_update", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"creative-field-id"##), + None, + Some(r##"Creative field ID for this creative field value."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("creative-fields", "methods: 'delete', 'get', 'insert', 'list', 'patch' and 'update'", vec![ + ("delete", + Some(r##"Deletes an existing creative field."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/creative-fields_delete", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"Creative Field ID"##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + ]), + ("get", + Some(r##"Gets one creative field by ID."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/creative-fields_get", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"Creative Field ID"##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("insert", + Some(r##"Inserts a new creative field."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/creative-fields_insert", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Retrieves a list of creative fields, possibly filtered."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/creative-fields_list", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("patch", + Some(r##"Updates an existing creative field. This method supports patch semantics."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/creative-fields_patch", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"Creative Field ID"##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("update", + Some(r##"Updates an existing creative field."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/creative-fields_update", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("creative-groups", "methods: 'get', 'insert', 'list', 'patch' and 'update'", vec![ + ("get", + Some(r##"Gets one creative group by ID."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/creative-groups_get", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"Creative group ID."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("insert", + Some(r##"Inserts a new creative group."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/creative-groups_insert", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Retrieves a list of creative groups, possibly filtered."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/creative-groups_list", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("patch", + Some(r##"Updates an existing creative group. This method supports patch semantics."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/creative-groups_patch", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"Creative group ID."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("update", + Some(r##"Updates an existing creative group."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/creative-groups_update", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("creatives", "methods: 'get', 'insert', 'list', 'patch' and 'update'", vec![ + ("get", + Some(r##"Gets one creative by ID."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/creatives_get", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"Creative ID."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("insert", + Some(r##"Inserts a new creative."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/creatives_insert", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Retrieves a list of creatives, possibly filtered."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/creatives_list", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("patch", + Some(r##"Updates an existing creative. This method supports patch semantics."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/creatives_patch", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"Creative ID."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("update", + Some(r##"Updates an existing creative."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/creatives_update", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("dimension-values", "methods: 'query'", vec![ + ("query", + Some(r##"Retrieves list of report dimension values for a list of filters."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/dimension-values_query", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"The DFA user profile ID."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("directory-site-contacts", "methods: 'get' and 'list'", vec![ + ("get", + Some(r##"Gets one directory site contact by ID."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/directory-site-contacts_get", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"Directory site contact ID."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Retrieves a list of directory site contacts, possibly filtered."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/directory-site-contacts_list", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("directory-sites", "methods: 'get', 'insert' and 'list'", vec![ + ("get", + Some(r##"Gets one directory site by ID."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/directory-sites_get", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"Directory site ID."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("insert", + Some(r##"Inserts a new directory site."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/directory-sites_insert", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Retrieves a list of directory sites, possibly filtered."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/directory-sites_list", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("event-tags", "methods: 'delete', 'get', 'insert', 'list', 'patch' and 'update'", vec![ + ("delete", + Some(r##"Deletes an existing event tag."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/event-tags_delete", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"Event tag ID."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + ]), + ("get", + Some(r##"Gets one event tag by ID."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/event-tags_get", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"Event tag ID."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("insert", + Some(r##"Inserts a new event tag."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/event-tags_insert", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Retrieves a list of event tags, possibly filtered."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/event-tags_list", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("patch", + Some(r##"Updates an existing event tag. This method supports patch semantics."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/event-tags_patch", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"Event tag ID."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("update", + Some(r##"Updates an existing event tag."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/event-tags_update", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("files", "methods: 'get' and 'list'", vec![ + ("get", + Some(r##"Retrieves a report file by its report ID and file ID."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/files_get", + vec![ + (Some(r##"report-id"##), + None, + Some(r##"The ID of the report."##), + Some(true), + Some(false)), + + (Some(r##"file-id"##), + None, + Some(r##"The ID of the report file."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Lists files for a user profile."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/files_list", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"The DFA profile ID."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("floodlight-activities", "methods: 'delete', 'generatetag', 'get', 'insert', 'list', 'patch' and 'update'", vec![ + ("delete", + Some(r##"Deletes an existing floodlight activity."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/floodlight-activities_delete", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"Floodlight activity ID."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + ]), + ("generatetag", + Some(r##"Generates a tag for a floodlight activity."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/floodlight-activities_generatetag", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("get", + Some(r##"Gets one floodlight activity by ID."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/floodlight-activities_get", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"Floodlight activity ID."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("insert", + Some(r##"Inserts a new floodlight activity."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/floodlight-activities_insert", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Retrieves a list of floodlight activities, possibly filtered."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/floodlight-activities_list", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("patch", + Some(r##"Updates an existing floodlight activity. This method supports patch semantics."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/floodlight-activities_patch", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"Floodlight activity ID."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("update", + Some(r##"Updates an existing floodlight activity."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/floodlight-activities_update", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("floodlight-activity-groups", "methods: 'delete', 'get', 'insert', 'list', 'patch' and 'update'", vec![ + ("delete", + Some(r##"Deletes an existing floodlight activity group."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/floodlight-activity-groups_delete", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"Floodlight activity Group ID."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + ]), + ("get", + Some(r##"Gets one floodlight activity group by ID."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/floodlight-activity-groups_get", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"Floodlight activity Group ID."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("insert", + Some(r##"Inserts a new floodlight activity group."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/floodlight-activity-groups_insert", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Retrieves a list of floodlight activity groups, possibly filtered."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/floodlight-activity-groups_list", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("patch", + Some(r##"Updates an existing floodlight activity group. This method supports patch semantics."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/floodlight-activity-groups_patch", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"Floodlight activity Group ID."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("update", + Some(r##"Updates an existing floodlight activity group."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/floodlight-activity-groups_update", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("floodlight-configurations", "methods: 'get', 'list', 'patch' and 'update'", vec![ + ("get", + Some(r##"Gets one floodlight configuration by ID."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/floodlight-configurations_get", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"Floodlight configuration ID."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Retrieves a list of floodlight configurations, possibly filtered."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/floodlight-configurations_list", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("patch", + Some(r##"Updates an existing floodlight configuration. This method supports patch semantics."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/floodlight-configurations_patch", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"Floodlight configuration ID."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("update", + Some(r##"Updates an existing floodlight configuration."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/floodlight-configurations_update", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("inventory-items", "methods: 'get' and 'list'", vec![ + ("get", + Some(r##"Gets one inventory item by ID."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/inventory-items_get", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"project-id"##), + None, + Some(r##"Project ID for order documents."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"Inventory item ID."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Retrieves a list of inventory items, possibly filtered."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/inventory-items_list", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"project-id"##), + None, + Some(r##"Project ID for order documents."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("landing-pages", "methods: 'delete', 'get', 'insert', 'list', 'patch' and 'update'", vec![ + ("delete", + Some(r##"Deletes an existing campaign landing page."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/landing-pages_delete", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"campaign-id"##), + None, + Some(r##"Landing page campaign ID."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"Landing page ID."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + ]), + ("get", + Some(r##"Gets one campaign landing page by ID."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/landing-pages_get", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"campaign-id"##), + None, + Some(r##"Landing page campaign ID."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"Landing page ID."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("insert", + Some(r##"Inserts a new landing page for the specified campaign."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/landing-pages_insert", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"campaign-id"##), + None, + Some(r##"Landing page campaign ID."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Retrieves the list of landing pages for the specified campaign."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/landing-pages_list", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"campaign-id"##), + None, + Some(r##"Landing page campaign ID."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("patch", + Some(r##"Updates an existing campaign landing page. This method supports patch semantics."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/landing-pages_patch", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"campaign-id"##), + None, + Some(r##"Landing page campaign ID."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"Landing page ID."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("update", + Some(r##"Updates an existing campaign landing page."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/landing-pages_update", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"campaign-id"##), + None, + Some(r##"Landing page campaign ID."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("metros", "methods: 'list'", vec![ + ("list", + Some(r##"Retrieves a list of metros."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/metros_list", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("mobile-carriers", "methods: 'get' and 'list'", vec![ + ("get", + Some(r##"Gets one mobile carrier by ID."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/mobile-carriers_get", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"Mobile carrier ID."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Retrieves a list of mobile carriers."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/mobile-carriers_list", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("operating-system-versions", "methods: 'get' and 'list'", vec![ + ("get", + Some(r##"Gets one operating system version by ID."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/operating-system-versions_get", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"Operating system version ID."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Retrieves a list of operating system versions."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/operating-system-versions_list", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("operating-systems", "methods: 'get' and 'list'", vec![ + ("get", + Some(r##"Gets one operating system by DART ID."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/operating-systems_get", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"dart-id"##), + None, + Some(r##"Operating system DART ID."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Retrieves a list of operating systems."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/operating-systems_list", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("order-documents", "methods: 'get' and 'list'", vec![ + ("get", + Some(r##"Gets one order document by ID."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/order-documents_get", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"project-id"##), + None, + Some(r##"Project ID for order documents."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"Order document ID."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Retrieves a list of order documents, possibly filtered."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/order-documents_list", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"project-id"##), + None, + Some(r##"Project ID for order documents."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("orders", "methods: 'get' and 'list'", vec![ + ("get", + Some(r##"Gets one order by ID."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/orders_get", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"project-id"##), + None, + Some(r##"Project ID for orders."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"Order ID."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Retrieves a list of orders, possibly filtered."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/orders_list", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"project-id"##), + None, + Some(r##"Project ID for orders."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("placement-groups", "methods: 'get', 'insert', 'list', 'patch' and 'update'", vec![ + ("get", + Some(r##"Gets one placement group by ID."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/placement-groups_get", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"Placement group ID."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("insert", + Some(r##"Inserts a new placement group."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/placement-groups_insert", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Retrieves a list of placement groups, possibly filtered."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/placement-groups_list", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("patch", + Some(r##"Updates an existing placement group. This method supports patch semantics."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/placement-groups_patch", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"Placement group ID."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("update", + Some(r##"Updates an existing placement group."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/placement-groups_update", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("placement-strategies", "methods: 'delete', 'get', 'insert', 'list', 'patch' and 'update'", vec![ + ("delete", + Some(r##"Deletes an existing placement strategy."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/placement-strategies_delete", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"Placement strategy ID."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + ]), + ("get", + Some(r##"Gets one placement strategy by ID."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/placement-strategies_get", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"Placement strategy ID."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("insert", + Some(r##"Inserts a new placement strategy."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/placement-strategies_insert", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Retrieves a list of placement strategies, possibly filtered."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/placement-strategies_list", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("patch", + Some(r##"Updates an existing placement strategy. This method supports patch semantics."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/placement-strategies_patch", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"Placement strategy ID."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("update", + Some(r##"Updates an existing placement strategy."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/placement-strategies_update", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("placements", "methods: 'generatetags', 'get', 'insert', 'list', 'patch' and 'update'", vec![ + ("generatetags", + Some(r##"Generates tags for a placement."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/placements_generatetags", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("get", + Some(r##"Gets one placement by ID."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/placements_get", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"Placement ID."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("insert", + Some(r##"Inserts a new placement."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/placements_insert", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Retrieves a list of placements, possibly filtered."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/placements_list", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("patch", + Some(r##"Updates an existing placement. This method supports patch semantics."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/placements_patch", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"Placement ID."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("update", + Some(r##"Updates an existing placement."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/placements_update", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("platform-types", "methods: 'get' and 'list'", vec![ + ("get", + Some(r##"Gets one platform type by ID."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/platform-types_get", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"Platform type ID."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Retrieves a list of platform types."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/platform-types_list", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("postal-codes", "methods: 'get' and 'list'", vec![ + ("get", + Some(r##"Gets one postal code by ID."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/postal-codes_get", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"code"##), + None, + Some(r##"Postal code ID."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Retrieves a list of postal codes."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/postal-codes_list", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("projects", "methods: 'get' and 'list'", vec![ + ("get", + Some(r##"Gets one project by ID."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/projects_get", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"Project ID."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Retrieves a list of projects, possibly filtered."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/projects_list", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("regions", "methods: 'list'", vec![ + ("list", + Some(r##"Retrieves a list of regions."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/regions_list", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("remarketing-list-shares", "methods: 'get', 'patch' and 'update'", vec![ + ("get", + Some(r##"Gets one remarketing list share by remarketing list ID."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/remarketing-list-shares_get", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"remarketing-list-id"##), + None, + Some(r##"Remarketing list ID."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("patch", + Some(r##"Updates an existing remarketing list share. This method supports patch semantics."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/remarketing-list-shares_patch", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"remarketing-list-id"##), + None, + Some(r##"Remarketing list ID."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("update", + Some(r##"Updates an existing remarketing list share."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/remarketing-list-shares_update", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("remarketing-lists", "methods: 'get', 'insert', 'list', 'patch' and 'update'", vec![ + ("get", + Some(r##"Gets one remarketing list by ID."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/remarketing-lists_get", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"Remarketing list ID."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("insert", + Some(r##"Inserts a new remarketing list."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/remarketing-lists_insert", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Retrieves a list of remarketing lists, possibly filtered."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/remarketing-lists_list", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"advertiser-id"##), + None, + Some(r##"Select only remarketing lists owned by this advertiser."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("patch", + Some(r##"Updates an existing remarketing list. This method supports patch semantics."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/remarketing-lists_patch", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"Remarketing list ID."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("update", + Some(r##"Updates an existing remarketing list."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/remarketing-lists_update", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("reports", "methods: 'compatible-fields-query', 'delete', 'files-get', 'files-list', 'get', 'insert', 'list', 'patch', 'run' and 'update'", vec![ + ("compatible-fields-query", + Some(r##"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."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/reports_compatible-fields-query", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"The DFA user profile ID."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("delete", + Some(r##"Deletes a report by its ID."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/reports_delete", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"The DFA user profile ID."##), + Some(true), + Some(false)), + + (Some(r##"report-id"##), + None, + Some(r##"The ID of the report."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + ]), + ("files-get", + Some(r##"Retrieves a report file."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/reports_files-get", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"The DFA profile ID."##), + Some(true), + Some(false)), + + (Some(r##"report-id"##), + None, + Some(r##"The ID of the report."##), + Some(true), + Some(false)), + + (Some(r##"file-id"##), + None, + Some(r##"The ID of the report file."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("files-list", + Some(r##"Lists files for a report."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/reports_files-list", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"The DFA profile ID."##), + Some(true), + Some(false)), + + (Some(r##"report-id"##), + None, + Some(r##"The ID of the parent report."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("get", + Some(r##"Retrieves a report by its ID."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/reports_get", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"The DFA user profile ID."##), + Some(true), + Some(false)), + + (Some(r##"report-id"##), + None, + Some(r##"The ID of the report."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("insert", + Some(r##"Creates a report."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/reports_insert", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"The DFA user profile ID."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Retrieves list of reports."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/reports_list", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"The DFA user profile ID."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("patch", + Some(r##"Updates a report. This method supports patch semantics."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/reports_patch", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"The DFA user profile ID."##), + Some(true), + Some(false)), + + (Some(r##"report-id"##), + None, + Some(r##"The ID of the report."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("run", + Some(r##"Runs a report."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/reports_run", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"The DFA profile ID."##), + Some(true), + Some(false)), + + (Some(r##"report-id"##), + None, + Some(r##"The ID of the report."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("update", + Some(r##"Updates a report."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/reports_update", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"The DFA user profile ID."##), + Some(true), + Some(false)), + + (Some(r##"report-id"##), + None, + Some(r##"The ID of the report."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("sites", "methods: 'get', 'insert', 'list', 'patch' and 'update'", vec![ + ("get", + Some(r##"Gets one site by ID."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/sites_get", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"Site ID."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("insert", + Some(r##"Inserts a new site."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/sites_insert", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Retrieves a list of sites, possibly filtered."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/sites_list", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("patch", + Some(r##"Updates an existing site. This method supports patch semantics."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/sites_patch", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"Site ID."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("update", + Some(r##"Updates an existing site."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/sites_update", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("sizes", "methods: 'get', 'insert' and 'list'", vec![ + ("get", + Some(r##"Gets one size by ID."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/sizes_get", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"Size ID."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("insert", + Some(r##"Inserts a new size."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/sizes_insert", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Retrieves a list of sizes, possibly filtered."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/sizes_list", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("subaccounts", "methods: 'get', 'insert', 'list', 'patch' and 'update'", vec![ + ("get", + Some(r##"Gets one subaccount by ID."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/subaccounts_get", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"Subaccount ID."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("insert", + Some(r##"Inserts a new subaccount."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/subaccounts_insert", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Gets a list of subaccounts, possibly filtered."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/subaccounts_list", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("patch", + Some(r##"Updates an existing subaccount. This method supports patch semantics."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/subaccounts_patch", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"Subaccount ID."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("update", + Some(r##"Updates an existing subaccount."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/subaccounts_update", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("targetable-remarketing-lists", "methods: 'get' and 'list'", vec![ + ("get", + Some(r##"Gets one remarketing list by ID."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/targetable-remarketing-lists_get", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"Remarketing list ID."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Retrieves a list of targetable remarketing lists, possibly filtered."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/targetable-remarketing-lists_list", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"advertiser-id"##), + None, + Some(r##"Select only targetable remarketing lists targetable by these advertisers."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("user-profiles", "methods: 'get' and 'list'", vec![ + ("get", + Some(r##"Gets one user profile by ID."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/user-profiles_get", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"The user profile ID."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Retrieves list of user profiles for a user."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/user-profiles_list", + vec![ + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("user-role-permission-groups", "methods: 'get' and 'list'", vec![ + ("get", + Some(r##"Gets one user role permission group by ID."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/user-role-permission-groups_get", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"User role permission group ID."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Gets a list of all supported user role permission groups."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/user-role-permission-groups_list", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("user-role-permissions", "methods: 'get' and 'list'", vec![ + ("get", + Some(r##"Gets one user role permission by ID."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/user-role-permissions_get", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"User role permission ID."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Gets a list of user role permissions, possibly filtered."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/user-role-permissions_list", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("user-roles", "methods: 'delete', 'get', 'insert', 'list', 'patch' and 'update'", vec![ + ("delete", + Some(r##"Deletes an existing user role."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/user-roles_delete", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"User role ID."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + ]), + ("get", + Some(r##"Gets one user role by ID."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/user-roles_get", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"User role ID."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("insert", + Some(r##"Inserts a new user role."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/user-roles_insert", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Retrieves a list of user roles, possibly filtered."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/user-roles_list", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("patch", + Some(r##"Updates an existing user role. This method supports patch semantics."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/user-roles_patch", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"User role ID."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("update", + Some(r##"Updates an existing user role."##), + "Details at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli/user-roles_update", + vec![ + (Some(r##"profile-id"##), + None, + Some(r##"User profile ID associated with this request."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ]; + + let mut app = App::new("dfareporting2d2") + .author("Sebastian Thiel ") + .version("0.3.2+20150717") + .about("Manage your DoubleClick Campaign Manager ad campaigns and reports.") + .after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_dfareporting2d2_cli") + .arg(Arg::with_name("url") + .long("scope") + .help("Specify the authentication a method should be executed in. Each scope requires the user to grant this application permission to use it.If unset, it defaults to the shortest scope url for a particular method.") + .multiple(true) + .takes_value(true)) + .arg(Arg::with_name("folder") + .long("config-dir") + .help("A directory into which we will store our persistent data. Defaults to a user-writable directory that we will create during the first invocation.[default: ~/.google-service-cli") + .multiple(false) + .takes_value(true)) + .arg(Arg::with_name("debug") + .long("debug") + .help("Output all server communication to standard error. `tx` and `rx` are placed into the same stream.") + .multiple(false) + .takes_value(false)) + .arg(Arg::with_name("debug-auth") + .long("debug-auth") + .help("Output all communication related to authentication to standard error. `tx` and `rx` are placed into the same stream.") + .multiple(false) + .takes_value(false)); + + for &(main_command_name, ref about, ref subcommands) in arg_data.iter() { + let mut mcmd = SubCommand::with_name(main_command_name).about(about); + + for &(sub_command_name, ref desc, url_info, ref args) in subcommands { + let mut scmd = SubCommand::with_name(sub_command_name); + if let &Some(desc) = desc { + scmd = scmd.about(desc); + } + scmd = scmd.after_help(url_info); + + for &(ref arg_name, ref flag, ref desc, ref required, ref multi) in args { + let arg_name_str = + match (arg_name, flag) { + (&Some(an), _ ) => an, + (_ , &Some(f)) => f, + _ => unreachable!(), + }; + let mut arg = Arg::with_name(arg_name_str) + .empty_values(false); + if let &Some(short_flag) = flag { + arg = arg.short(short_flag); + } + if let &Some(desc) = desc { + arg = arg.help(desc); + } + if arg_name.is_some() && flag.is_some() { + arg = arg.takes_value(true); + } + if let &Some(required) = required { + arg = arg.required(required); + } + if let &Some(multi) = multi { + arg = arg.multiple(multi); + } + if arg_name_str == "mode" { + arg = arg.number_of_values(2); + arg = arg.value_names(&upload_value_names); + + scmd = scmd.arg(Arg::with_name("mime") + .short("m") + .requires("mode") + .required(false) + .help("The file's mime time, like 'application/octet-stream'") + .takes_value(true)); + } + scmd = scmd.arg(arg); + } + mcmd = mcmd.subcommand(scmd); + } + app = app.subcommand(mcmd); + } + + let matches = app.get_matches(); + + let debug = matches.is_present("debug"); + match Engine::new(matches) { + Err(err) => { + exit_status = err.exit_code; + writeln!(io::stderr(), "{}", err).ok(); + }, + Ok(engine) => { + if let Err(doit_err) = engine.doit() { + exit_status = 1; + match doit_err { + DoitError::IoError(path, err) => { + writeln!(io::stderr(), "Failed to open output file '{}': {}", path, err).ok(); + }, + DoitError::ApiError(err) => { + if debug { + writeln!(io::stderr(), "{:#?}", err).ok(); + } else { + writeln!(io::stderr(), "{}", err).ok(); + } + } + } + } + } + } + + std::process::exit(exit_status); +} \ No newline at end of file diff --git a/gen/dfareporting2d2/Cargo.toml b/gen/dfareporting2d2/Cargo.toml new file mode 100644 index 0000000000..482bc463a5 --- /dev/null +++ b/gen/dfareporting2d2/Cargo.toml @@ -0,0 +1,29 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-dfareporting2d2" +version = "0.1.9+20150717" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with dfareporting (protocol v2.2)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/dfareporting2d2" +homepage = "https://developers.google.com/doubleclick-advertisers/reporting/" +documentation = "http://byron.github.io/google-apis-rs/google_dfareporting2d2" +license = "MIT" +keywords = ["dfareporting", "google", "protocol", "web", "api"] +build = "src/build.rs" + + +[dependencies] +hyper = ">= 0.6.8" +mime = "0.1.0" +serde = ">= 0.6.0" +serde_json = ">= 0.6.0" +yup-oauth2 = "*" +url = "*" + +[build-dependencies] +syntex = { version = "*" } +serde_codegen = { version = "*" } + diff --git a/gen/dfareporting2d2/LICENSE.md b/gen/dfareporting2d2/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/dfareporting2d2/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/dfareporting2d2/README.md b/gen/dfareporting2d2/README.md new file mode 100644 index 0000000000..def5ad574e --- /dev/null +++ b/gen/dfareporting2d2/README.md @@ -0,0 +1,304 @@ + +The `google-dfareporting2d2` library allows access to all features of the *Google dfareporting* service. + +This documentation was generated from *dfareporting* crate version *0.1.9+20150717*, where *20150717* is the exact revision of the *dfareporting:v2.2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. + +Everything else about the *dfareporting* *v2d2* 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_dfareporting2d2/struct.Dfareporting.html) ... + +* [account active ad summaries](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.AccountActiveAdSummary.html) + * [*get*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.AccountActiveAdSummaryGetCall.html) +* [account permission groups](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.AccountPermissionGroup.html) + * [*get*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.AccountPermissionGroupGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.AccountPermissionGroupListCall.html) +* [account permissions](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.AccountPermission.html) + * [*get*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.AccountPermissionGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.AccountPermissionListCall.html) +* [account user profiles](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.AccountUserProfile.html) + * [*get*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.AccountUserProfileGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.AccountUserProfileInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.AccountUserProfileListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.AccountUserProfilePatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.AccountUserProfileUpdateCall.html) +* [accounts](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.Account.html) + * [*get*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.AccountGetCall.html), [*list*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.AccountListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.AccountPatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.AccountUpdateCall.html) +* [ads](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.Ad.html) + * [*get*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.AdGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.AdInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.AdListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.AdPatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.AdUpdateCall.html) +* [advertiser groups](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.AdvertiserGroup.html) + * [*delete*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.AdvertiserGroupDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.AdvertiserGroupGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.AdvertiserGroupInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.AdvertiserGroupListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.AdvertiserGroupPatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.AdvertiserGroupUpdateCall.html) +* [advertisers](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.Advertiser.html) + * [*get*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.AdvertiserGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.AdvertiserInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.AdvertiserListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.AdvertiserPatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.AdvertiserUpdateCall.html) +* [browsers](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.Browser.html) + * [*list*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.BrowserListCall.html) +* [campaign creative associations](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.CampaignCreativeAssociation.html) + * [*insert*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.CampaignCreativeAssociationInsertCall.html) and [*list*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.CampaignCreativeAssociationListCall.html) +* [campaigns](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.Campaign.html) + * [*get*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.CampaignGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.CampaignInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.CampaignListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.CampaignPatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.CampaignUpdateCall.html) +* [change logs](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.ChangeLog.html) + * [*get*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.ChangeLogGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.ChangeLogListCall.html) +* [cities](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.City.html) + * [*list*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.CityListCall.html) +* [connection types](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.ConnectionType.html) + * [*get*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.ConnectionTypeGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.ConnectionTypeListCall.html) +* [content categories](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.ContentCategory.html) + * [*delete*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.ContentCategoryDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.ContentCategoryGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.ContentCategoryInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.ContentCategoryListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.ContentCategoryPatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.ContentCategoryUpdateCall.html) +* [countries](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.Country.html) + * [*get*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.CountryGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.CountryListCall.html) +* [creative assets](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.CreativeAsset.html) + * [*insert*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.CreativeAssetInsertCall.html) +* [creative field values](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.CreativeFieldValue.html) + * [*delete*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.CreativeFieldValueDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.CreativeFieldValueGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.CreativeFieldValueInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.CreativeFieldValueListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.CreativeFieldValuePatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.CreativeFieldValueUpdateCall.html) +* [creative fields](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.CreativeField.html) + * [*delete*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.CreativeFieldDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.CreativeFieldGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.CreativeFieldInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.CreativeFieldListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.CreativeFieldPatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.CreativeFieldUpdateCall.html) +* [creative groups](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.CreativeGroup.html) + * [*get*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.CreativeGroupGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.CreativeGroupInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.CreativeGroupListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.CreativeGroupPatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.CreativeGroupUpdateCall.html) +* [creatives](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.Creative.html) + * [*get*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.CreativeGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.CreativeInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.CreativeListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.CreativePatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.CreativeUpdateCall.html) +* [dimension values](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.DimensionValue.html) + * [*query*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.DimensionValueQueryCall.html) +* [directory site contacts](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.DirectorySiteContact.html) + * [*get*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.DirectorySiteContactGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.DirectorySiteContactListCall.html) +* [directory sites](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.DirectorySite.html) + * [*get*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.DirectorySiteGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.DirectorySiteInsertCall.html) and [*list*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.DirectorySiteListCall.html) +* [event tags](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.EventTag.html) + * [*delete*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.EventTagDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.EventTagGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.EventTagInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.EventTagListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.EventTagPatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.EventTagUpdateCall.html) +* [files](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.File.html) + * [*get*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.FileGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.FileListCall.html) +* [floodlight activities](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.FloodlightActivity.html) + * [*delete*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.FloodlightActivityDeleteCall.html), [*generatetag*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.FloodlightActivityGeneratetagCall.html), [*get*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.FloodlightActivityGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.FloodlightActivityInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.FloodlightActivityListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.FloodlightActivityPatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.FloodlightActivityUpdateCall.html) +* [floodlight activity groups](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.FloodlightActivityGroup.html) + * [*delete*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.FloodlightActivityGroupDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.FloodlightActivityGroupGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.FloodlightActivityGroupInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.FloodlightActivityGroupListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.FloodlightActivityGroupPatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.FloodlightActivityGroupUpdateCall.html) +* [floodlight configurations](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.FloodlightConfiguration.html) + * [*get*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.FloodlightConfigurationGetCall.html), [*list*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.FloodlightConfigurationListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.FloodlightConfigurationPatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.FloodlightConfigurationUpdateCall.html) +* [inventory items](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.InventoryItem.html) + * [*get*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.InventoryItemGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.InventoryItemListCall.html) +* [landing pages](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.LandingPage.html) + * [*delete*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.LandingPageDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.LandingPageGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.LandingPageInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.LandingPageListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.LandingPagePatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.LandingPageUpdateCall.html) +* [metros](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.Metro.html) + * [*list*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.MetroListCall.html) +* [mobile carriers](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.MobileCarrier.html) + * [*get*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.MobileCarrierGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.MobileCarrierListCall.html) +* [operating system versions](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.OperatingSystemVersion.html) + * [*get*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.OperatingSystemVersionGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.OperatingSystemVersionListCall.html) +* [operating systems](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.OperatingSystem.html) + * [*get*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.OperatingSystemGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.OperatingSystemListCall.html) +* [order documents](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.OrderDocument.html) + * [*get*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.OrderDocumentGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.OrderDocumentListCall.html) +* [orders](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.Order.html) + * [*get*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.OrderGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.OrderListCall.html) +* [placement groups](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.PlacementGroup.html) + * [*get*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.PlacementGroupGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.PlacementGroupInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.PlacementGroupListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.PlacementGroupPatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.PlacementGroupUpdateCall.html) +* [placement strategies](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.PlacementStrategy.html) + * [*delete*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.PlacementStrategyDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.PlacementStrategyGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.PlacementStrategyInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.PlacementStrategyListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.PlacementStrategyPatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.PlacementStrategyUpdateCall.html) +* [placements](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.Placement.html) + * [*generatetags*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.PlacementGeneratetagCall.html), [*get*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.PlacementGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.PlacementInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.PlacementListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.PlacementPatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.PlacementUpdateCall.html) +* [platform types](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.PlatformType.html) + * [*get*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.PlatformTypeGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.PlatformTypeListCall.html) +* [postal codes](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.PostalCode.html) + * [*get*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.PostalCodeGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.PostalCodeListCall.html) +* [projects](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.Project.html) + * [*get*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.ProjectGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.ProjectListCall.html) +* [regions](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.Region.html) + * [*list*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.RegionListCall.html) +* [remarketing list shares](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.RemarketingListShare.html) + * [*get*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.RemarketingListShareGetCall.html), [*patch*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.RemarketingListSharePatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.RemarketingListShareUpdateCall.html) +* [remarketing lists](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.RemarketingList.html) + * [*get*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.RemarketingListGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.RemarketingListInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.RemarketingListListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.RemarketingListPatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.RemarketingListUpdateCall.html) +* [reports](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.Report.html) + * [*compatible fields query*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.ReportCompatibleFieldQueryCall.html), [*delete*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.ReportDeleteCall.html), [*files get*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.ReportFileGetCall.html), [*files list*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.ReportFileListCall.html), [*get*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.ReportGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.ReportInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.ReportListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.ReportPatchCall.html), [*run*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.ReportRunCall.html) and [*update*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.ReportUpdateCall.html) +* [sites](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.Site.html) + * [*get*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.SiteGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.SiteInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.SiteListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.SitePatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.SiteUpdateCall.html) +* [sizes](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.Size.html) + * [*get*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.SizeGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.SizeInsertCall.html) and [*list*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.SizeListCall.html) +* [subaccounts](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.Subaccount.html) + * [*get*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.SubaccountGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.SubaccountInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.SubaccountListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.SubaccountPatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.SubaccountUpdateCall.html) +* [targetable remarketing lists](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.TargetableRemarketingList.html) + * [*get*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.TargetableRemarketingListGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.TargetableRemarketingListListCall.html) +* [user profiles](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.UserProfile.html) + * [*get*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.UserProfileGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.UserProfileListCall.html) +* [user role permission groups](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.UserRolePermissionGroup.html) + * [*get*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.UserRolePermissionGroupGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.UserRolePermissionGroupListCall.html) +* [user role permissions](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.UserRolePermission.html) + * [*get*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.UserRolePermissionGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.UserRolePermissionListCall.html) +* [user roles](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.UserRole.html) + * [*delete*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.UserRoleDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.UserRoleGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.UserRoleInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.UserRoleListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.UserRolePatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.UserRoleUpdateCall.html) + + +Upload supported by ... + +* [*insert creative assets*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.CreativeAssetInsertCall.html) + +Download supported by ... + +* [*get files*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/struct.FileGetCall.html) +* [*files get reports*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/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_dfareporting2d2/struct.Dfareporting.html)** + * a central object to maintain state and allow accessing all *Activities* + * creates [*Method Builders*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/trait.MethodsBuilder.html) which in turn + allow access to individual [*Call Builders*](http://byron.github.io/google-apis-rs/google_dfareporting2d2/trait.CallBuilder.html) +* **[Resources](http://byron.github.io/google-apis-rs/google_dfareporting2d2/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_dfareporting2d2/trait.Part.html)** + * a collection of properties + * never directly used in *Activities* +* **[Activities](http://byron.github.io/google-apis-rs/google_dfareporting2d2/trait.CallBuilder.html)** + * operations to apply to *Resources* + +All *structures* are marked with applicable traits to further categorize them and ease browsing. + +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-dfareporting2d2 = "*" +``` + +## A complete example + +```Rust +extern crate hyper; +extern crate yup_oauth2 as oauth2; +extern crate google_dfareporting2d2 as dfareporting2d2; +use dfareporting2d2::{Result, Error}; +use std::default::Default; +use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +use dfareporting2d2::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 { + Err(e) => match e { + // The Error enum provides details about what exactly happened. + // You can also just use its `Debug`, `Display` or `Error` traits + Error::HttpError(_) + |Error::MissingAPIKey + |Error::MissingToken(_) + |Error::Cancelled + |Error::UploadSizeLimitExceeded(_, _) + |Error::Failure(_) + |Error::BadRequest(_) + |Error::FieldClash(_) + |Error::JsonDecodeError(_, _) => println!("{}", e), + }, + Ok(res) => println!("Success: {:?}", res), +} + +``` +## Handling Errors + +All errors produced by the system are provided either as [Result](http://byron.github.io/google-apis-rs/google_dfareporting2d2/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_dfareporting2d2/trait.Delegate.html), or the [Authenticator Delegate](http://byron.github.io/google-apis-rs/google_dfareporting2d2/../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 Downloads +If a method supports downloads, the response body, which is part of the [Result](http://byron.github.io/google-apis-rs/google_dfareporting2d2/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_dfareporting2d2/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_dfareporting2d2/trait.Delegate.html) to the +[Method Builder](http://byron.github.io/google-apis-rs/google_dfareporting2d2/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_dfareporting2d2/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_dfareporting2d2/trait.RequestValue.html) and +[decodable](http://byron.github.io/google-apis-rs/google_dfareporting2d2/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_dfareporting2d2/trait.Part.html) which are identifiable 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_dfareporting2d2/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_dfareporting2d2/trait.RequestValue.html) are moved + +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 **dfareporting2d2** 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/dfareporting2d2/src/build.rs b/gen/dfareporting2d2/src/build.rs new file mode 100644 index 0000000000..0a12d85da6 --- /dev/null +++ b/gen/dfareporting2d2/src/build.rs @@ -0,0 +1,16 @@ +extern crate syntex; +extern crate serde_codegen; + +use std::env; +use std::path::Path; + +pub fn main() { + let out_dir = env::var_os("OUT_DIR").unwrap(); + + let src = Path::new("src/lib.rs.in"); + let dst = Path::new(&out_dir).join("lib.rs"); + + let mut registry = syntex::Registry::new(); + serde_codegen::register(&mut registry); + registry.expand("google-dfareporting2d2", &src, &dst).unwrap(); +} diff --git a/gen/dfareporting2d2/src/cmn.rs b/gen/dfareporting2d2/src/cmn.rs new file mode 100644 index 0000000000..0e31353ba3 --- /dev/null +++ b/gen/dfareporting2d2/src/cmn.rs @@ -0,0 +1,762 @@ +// COPY OF 'src/rust/api/cmn.rs' +// DO NOT EDIT +use std::io::{self, Read, Seek, Cursor, Write, SeekFrom}; +use std; +use std::fmt::{self, Display}; +use std::str::FromStr; +use std::error; +use std::thread::sleep_ms; + +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::h1::LINE_ENDING; +use hyper::method::Method; +use hyper::status::StatusCode; + +use serde_json as json; + +/// 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 {} + +/// Identifies types for building methods of a particular resource type +pub trait MethodsBuilder {} + +/// Identifies types which represent builders for a particular resource method +pub trait CallBuilder {} + +/// Identifies types which can be inserted and deleted. +/// Types with this trait are most commonly used by clients of this API. +pub trait Resource {} + +/// Identifies types which are used in API responses. +pub trait ResponseResult {} + +/// Identifies types which are used in API requests. +pub trait RequestValue {} + +/// Identifies types which are not actually used by the API +/// This might be a bug within the google API schema. +pub trait UnusedType {} + +/// Identifies types which are only used as part of other types, which +/// usually are carrying the `Resource` trait. +pub trait Part {} + +/// 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 {} + +/// 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 +} + +/// A utility to represent detailed errors we might see in case there are BadRequests. +/// The latter happen if the sent parameters or request structures are unsound +#[derive(Deserialize, Serialize, Debug)] +pub struct ErrorResponse { + error: ServerError, +} + +#[derive(Deserialize, Serialize, Debug)] +pub struct ServerError { + errors: Vec, + code: u16, + message: String, +} + +#[derive(Deserialize, Serialize, Debug)] +pub struct ServerMessage { + domain: String, + reason: String, + message: String, + #[serde(rename="locationType")] + location_type: Option, + location: 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 successful. That way, the delegate 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. + /// + /// If you choose to retry after a duration, the duration should be chosen using the + /// [exponential backoff algorithm](http://en.wikipedia.org/wiki/Exponential_backoff). + /// + /// Return retry information. + fn http_error(&mut self, &hyper::Error) -> 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 it as a general information about the + /// impending failure. + /// The given Error provides information about why the token couldn't be acquired in the + /// first place + fn token(&mut self, err: &error::Error) -> Option { + let _ = err; + 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/canceled, 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()`. + /// It will also be called with None after a successful upload, which allows the delegate + /// to forget the URL. That way, we will not attempt to resume an upload that has already + /// finished. + fn store_upload_url(&mut self, url: Option<&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: &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. + /// + /// If you choose to retry after a duration, the duration should be chosen using the + /// [exponential backoff algorithm](http://en.wikipedia.org/wiki/Exponential_backoff). + fn http_failure(&mut self, _: &hyper::client::Response, Option, _: 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 {} + + +#[derive(Debug)] +pub enum Error { + /// The http connection failed + HttpError(hyper::Error), + + /// 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), + + /// Represents information about a request that was not understood by the server. + /// Details are included. + BadRequest(ErrorResponse), + + /// 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(Box), + + /// 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(String, json::Error), + + /// Indicates an HTTP repsonse with a non-success status code + Failure(hyper::client::Response), +} + + +impl Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + Error::HttpError(ref err) => err.fmt(f), + Error::UploadSizeLimitExceeded(ref resource_size, ref max_size) => + writeln!(f, "The media size {} exceeds the maximum allowed upload size of {}" + , resource_size, max_size), + Error::MissingAPIKey => { + (writeln!(f, "The application's API key was not found in the configuration")).ok(); + writeln!(f, "It is used as there are no Scopes defined for this method.") + }, + Error::BadRequest(ref err) => { + try!(writeln!(f, "Bad Requst ({}): {}", err.error.code, err.error.message)); + for err in err.error.errors.iter() { + try!(writeln!(f, " {}: {}, {}{}", + err.domain, + err.message, + err.reason, + match &err.location { + &Some(ref loc) => format!("@{}", loc), + &None => String::new(), + })); + } + Ok(()) + }, + Error::MissingToken(ref err) => + writeln!(f, "Token retrieval failed with error: {}", err), + Error::Cancelled => + writeln!(f, "Operation cancelled by delegate"), + Error::FieldClash(field) => + writeln!(f, "The custom parameter '{}' is already provided natively by the CallBuilder.", field), + Error::JsonDecodeError(ref json_str, ref err) + => writeln!(f, "{}: {}", err, json_str), + Error::Failure(ref response) => + writeln!(f, "Http status indicates failure: {:?}", response), + } + } +} + +impl error::Error for Error { + fn description(&self) -> &str { + match *self { + Error::HttpError(ref err) => err.description(), + Error::JsonDecodeError(_, ref err) => err.description(), + _ => "NO DESCRIPTION POSSIBLE - use `Display.fmt()` instead" + } + } + + fn cause(&self) -> Option<&error::Error> { + match *self { + Error::HttpError(ref err) => err.cause(), + Error::JsonDecodeError(_, ref err) => err.cause(), + _ => None + } + } +} + +/// A universal result type used as return for all calls. +pub type Result = std::result::Result; + +/// 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 + 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 following macro invocation needs to be expanded, as `include!` +// doens't support external macros +// header!{ +// #[doc="The `X-Upload-Content-Type` header."] +// (XUploadContentType, "X-Upload-Content-Type") => [Mime] + +// xupload_content_type { +// test_header!( +// test1, +// vec![b"text/plain"], +// Some(HeaderField( +// vec![Mime(TopLevel::Text, SubLevel::Plain, Vec::new())] +// ))); + +// } +// } + +/// The `X-Upload-Content-Type` header. +/// +/// Generated via rustc --pretty expanded -Z unstable-options, and manually +/// processed to be more readable. +#[derive(PartialEq, Debug, Clone)] +pub struct XUploadContentType(pub Mime); + +impl ::std::ops::Deref for XUploadContentType { + type Target = Mime; + fn deref<'a>(&'a self) -> &'a Mime { &self.0 } +} +impl ::std::ops::DerefMut for XUploadContentType { + fn deref_mut<'a>(&'a mut self) -> &'a mut Mime { &mut self.0 } +} +impl Header for XUploadContentType { + fn header_name() -> &'static str { "X-Upload-Content-Type" } + fn parse_header(raw: &[Vec]) -> hyper::error::Result { + hyper::header::parsing::from_one_raw_str(raw).map(XUploadContentType) + } +} +impl HeaderFormat for XUploadContentType { + fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { + Display::fmt(&**self, f) + } +} +impl Display for XUploadContentType { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Display::fmt(&**self, f) + } +} + +#[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]) -> hyper::error::Result { + Err(hyper::error::Error::Method) + } +} + + +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]) -> hyper::error::Result { + if raw.len() > 0 { + let v = &raw[0]; + if let Ok(s) = std::str::from_utf8(v) { + const PREFIX: &'static str = "bytes "; + if s.starts_with(PREFIX) { + if let Ok(c) = ::from_str(&s[PREFIX.len()..]) { + return Ok(RangeResponseHeader(c)) + } + } + } + } + Err(hyper::error::Error::Method) + } +} + +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, 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, A> ResumableUploadHelper<'a, A> + where A: oauth2::GetToken { + + fn query_transfer_status(&mut self) -> std::result::Result> { + 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, None) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + return Err(Ok(r)) + } + }; + return Ok(h.0.last) + } + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + return Err(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() { + Ok(s) => s, + Err(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 + }; + + self.reader.seek(SeekFrom::Start(start)).unwrap(); + loop { + let request_size = match self.content_length - start { + rs if rs > chunk_size => chunk_size, + rs => rs + }; + + 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 + } + // workaround https://github.com/rust-lang/rust/issues/22252 + let res = 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(); + match res { + 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, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + } + return Some(Ok(res)) + }, + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + return Some(Err(err)) + } + } + } + } +} + +// Copy of src/rust/cli/cmn.rs +// TODO(ST): Allow sharing common code between program types +pub fn remove_json_null_values(value: &mut json::value::Value) { + match *value { + json::value::Value::Object(ref mut map) => { + let mut for_removal = Vec::new(); + + for (key, mut value) in map.iter_mut() { + if value.is_null() { + for_removal.push(key.clone()); + } else { + remove_json_null_values(&mut value); + } + } + + for key in &for_removal { + map.remove(key); + } + } + _ => {} + } +} diff --git a/gen/dfareporting2d2/src/lib.rs b/gen/dfareporting2d2/src/lib.rs new file mode 100644 index 0000000000..ad98d12003 --- /dev/null +++ b/gen/dfareporting2d2/src/lib.rs @@ -0,0 +1,308 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/api/lib.rs.mako' +// DO NOT EDIT ! + +//! This documentation was generated from *dfareporting* crate version *0.1.9+20150717*, where *20150717* is the exact revision of the *dfareporting:v2.2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +//! +//! Everything else about the *dfareporting* *v2d2* 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/dfareporting2d2). +//! # 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), [*insert*](struct.AccountUserProfileInsertCall.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) +//! * [*get*](struct.ConnectionTypeGetCall.html) and [*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), [*insert*](struct.DirectorySiteInsertCall.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) +//! * [inventory items](struct.InventoryItem.html) +//! * [*get*](struct.InventoryItemGetCall.html) and [*list*](struct.InventoryItemListCall.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) +//! * [*get*](struct.MobileCarrierGetCall.html) and [*list*](struct.MobileCarrierListCall.html) +//! * [operating system versions](struct.OperatingSystemVersion.html) +//! * [*get*](struct.OperatingSystemVersionGetCall.html) and [*list*](struct.OperatingSystemVersionListCall.html) +//! * [operating systems](struct.OperatingSystem.html) +//! * [*get*](struct.OperatingSystemGetCall.html) and [*list*](struct.OperatingSystemListCall.html) +//! * [order documents](struct.OrderDocument.html) +//! * [*get*](struct.OrderDocumentGetCall.html) and [*list*](struct.OrderDocumentListCall.html) +//! * [orders](struct.Order.html) +//! * [*get*](struct.OrderGetCall.html) and [*list*](struct.OrderListCall.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) +//! * [*get*](struct.PlatformTypeGetCall.html) and [*list*](struct.PlatformTypeListCall.html) +//! * [postal codes](struct.PostalCode.html) +//! * [*get*](struct.PostalCodeGetCall.html) and [*list*](struct.PostalCodeListCall.html) +//! * [projects](struct.Project.html) +//! * [*get*](struct.ProjectGetCall.html) and [*list*](struct.ProjectListCall.html) +//! * [regions](struct.Region.html) +//! * [*list*](struct.RegionListCall.html) +//! * [remarketing list shares](struct.RemarketingListShare.html) +//! * [*get*](struct.RemarketingListShareGetCall.html), [*patch*](struct.RemarketingListSharePatchCall.html) and [*update*](struct.RemarketingListShareUpdateCall.html) +//! * [remarketing lists](struct.RemarketingList.html) +//! * [*get*](struct.RemarketingListGetCall.html), [*insert*](struct.RemarketingListInsertCall.html), [*list*](struct.RemarketingListListCall.html), [*patch*](struct.RemarketingListPatchCall.html) and [*update*](struct.RemarketingListUpdateCall.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) +//! * [targetable remarketing lists](struct.TargetableRemarketingList.html) +//! * [*get*](struct.TargetableRemarketingListGetCall.html) and [*list*](struct.TargetableRemarketingListListCall.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* +//! * creates [*Method Builders*](trait.MethodsBuilder.html) which in turn +//! allow access to individual [*Call Builders*](trait.CallBuilder.html) +//! * **[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* +//! +//! All *structures* are marked with applicable traits to further categorize them and ease browsing. +//! +//! 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-dfareporting2d2 = "*" +//! ``` +//! +//! ## A complete example +//! +//! ```test_harness,no_run +//! extern crate hyper; +//! extern crate yup_oauth2 as oauth2; +//! extern crate google_dfareporting2d2 as dfareporting2d2; +//! use dfareporting2d2::{Result, Error}; +//! # #[test] fn egal() { +//! use std::default::Default; +//! use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +//! use dfareporting2d2::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("justo") +//! .sort_field("dolore") +//! .scope("At") +//! .page_token("dolor") +//! .max_results(-39) +//! .doit(); +//! +//! match result { +//! Err(e) => match e { +//! // The Error enum provides details about what exactly happened. +//! // You can also just use its `Debug`, `Display` or `Error` traits +//! Error::HttpError(_) +//! |Error::MissingAPIKey +//! |Error::MissingToken(_) +//! |Error::Cancelled +//! |Error::UploadSizeLimitExceeded(_, _) +//! |Error::Failure(_) +//! |Error::BadRequest(_) +//! |Error::FieldClash(_) +//! |Error::JsonDecodeError(_, _) => println!("{}", e), +//! }, +//! Ok(res) => println!("Success: {:?}", res), +//! } +//! # } +//! ``` +//! ## 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 Downloads +//! 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 identifiable 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 moved +//! +//! 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 +//! +//! + +// 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)] + +include!(concat!(env!("OUT_DIR"), "/lib.rs")); \ No newline at end of file diff --git a/gen/dfareporting2d2/src/lib.rs.in b/gen/dfareporting2d2/src/lib.rs.in new file mode 100644 index 0000000000..1c03bf05bc --- /dev/null +++ b/gen/dfareporting2d2/src/lib.rs.in @@ -0,0 +1,66561 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/api/lib.rs.in.mako' +// DO NOT EDIT ! + +extern crate hyper; +extern crate serde; +extern crate serde_json; +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 serde_json as json; +use std::io; +use std::fs; +use std::thread::sleep_ms; + +pub use cmn::{MultiPartReader, ToParts, MethodInfo, Result, Error, CallBuilder, Hub, ReadSeek, Part, + ResponseResult, RequestValue, NestedType, Delegate, DefaultDelegate, MethodsBuilder, + Resource, ErrorResponse, remove_json_null_values}; + + +// ############## +// 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 AsRef for Scope { + fn as_ref(&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_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::{Result, Error}; +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2d2::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 { +/// Err(e) => match e { +/// // The Error enum provides details about what exactly happened. +/// // You can also just use its `Debug`, `Display` or `Error` traits +/// Error::HttpError(_) +/// |Error::MissingAPIKey +/// |Error::MissingToken(_) +/// |Error::Cancelled +/// |Error::UploadSizeLimitExceeded(_, _) +/// |Error::Failure(_) +/// |Error::BadRequest(_) +/// |Error::FieldClash(_) +/// |Error::JsonDecodeError(_, _) => println!("{}", e), +/// }, +/// Ok(res) => println!("Success: {:?}", res), +/// } +/// # } +/// ``` +pub struct Dfareporting { + client: RefCell, + auth: RefCell, + _user_agent: String, +} + +impl<'a, C, A> Hub for Dfareporting {} + +impl<'a, C, A> Dfareporting + where 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.9".to_string(), + } + } + + pub fn account_active_ad_summaries(&'a self) -> AccountActiveAdSummaryMethods<'a, C, A> { + AccountActiveAdSummaryMethods { hub: &self } + } + pub fn account_permission_groups(&'a self) -> AccountPermissionGroupMethods<'a, C, A> { + AccountPermissionGroupMethods { hub: &self } + } + pub fn account_permissions(&'a self) -> AccountPermissionMethods<'a, C, A> { + AccountPermissionMethods { hub: &self } + } + pub fn account_user_profiles(&'a self) -> AccountUserProfileMethods<'a, C, A> { + AccountUserProfileMethods { hub: &self } + } + pub fn accounts(&'a self) -> AccountMethods<'a, C, A> { + AccountMethods { hub: &self } + } + pub fn ads(&'a self) -> AdMethods<'a, C, A> { + AdMethods { hub: &self } + } + pub fn advertiser_groups(&'a self) -> AdvertiserGroupMethods<'a, C, A> { + AdvertiserGroupMethods { hub: &self } + } + pub fn advertisers(&'a self) -> AdvertiserMethods<'a, C, A> { + AdvertiserMethods { hub: &self } + } + pub fn browsers(&'a self) -> BrowserMethods<'a, C, A> { + BrowserMethods { hub: &self } + } + pub fn campaign_creative_associations(&'a self) -> CampaignCreativeAssociationMethods<'a, C, A> { + CampaignCreativeAssociationMethods { hub: &self } + } + pub fn campaigns(&'a self) -> CampaignMethods<'a, C, A> { + CampaignMethods { hub: &self } + } + pub fn change_logs(&'a self) -> ChangeLogMethods<'a, C, A> { + ChangeLogMethods { hub: &self } + } + pub fn cities(&'a self) -> CityMethods<'a, C, A> { + CityMethods { hub: &self } + } + pub fn connection_types(&'a self) -> ConnectionTypeMethods<'a, C, A> { + ConnectionTypeMethods { hub: &self } + } + pub fn content_categories(&'a self) -> ContentCategoryMethods<'a, C, A> { + ContentCategoryMethods { hub: &self } + } + pub fn countries(&'a self) -> CountryMethods<'a, C, A> { + CountryMethods { hub: &self } + } + pub fn creative_assets(&'a self) -> CreativeAssetMethods<'a, C, A> { + CreativeAssetMethods { hub: &self } + } + pub fn creative_field_values(&'a self) -> CreativeFieldValueMethods<'a, C, A> { + CreativeFieldValueMethods { hub: &self } + } + pub fn creative_fields(&'a self) -> CreativeFieldMethods<'a, C, A> { + CreativeFieldMethods { hub: &self } + } + pub fn creative_groups(&'a self) -> CreativeGroupMethods<'a, C, A> { + CreativeGroupMethods { hub: &self } + } + pub fn creatives(&'a self) -> CreativeMethods<'a, C, A> { + CreativeMethods { hub: &self } + } + pub fn dimension_values(&'a self) -> DimensionValueMethods<'a, C, A> { + DimensionValueMethods { hub: &self } + } + pub fn directory_site_contacts(&'a self) -> DirectorySiteContactMethods<'a, C, A> { + DirectorySiteContactMethods { hub: &self } + } + pub fn directory_sites(&'a self) -> DirectorySiteMethods<'a, C, A> { + DirectorySiteMethods { hub: &self } + } + pub fn event_tags(&'a self) -> EventTagMethods<'a, C, A> { + EventTagMethods { hub: &self } + } + pub fn files(&'a self) -> FileMethods<'a, C, A> { + FileMethods { hub: &self } + } + pub fn floodlight_activities(&'a self) -> FloodlightActivityMethods<'a, C, A> { + FloodlightActivityMethods { hub: &self } + } + pub fn floodlight_activity_groups(&'a self) -> FloodlightActivityGroupMethods<'a, C, A> { + FloodlightActivityGroupMethods { hub: &self } + } + pub fn floodlight_configurations(&'a self) -> FloodlightConfigurationMethods<'a, C, A> { + FloodlightConfigurationMethods { hub: &self } + } + pub fn inventory_items(&'a self) -> InventoryItemMethods<'a, C, A> { + InventoryItemMethods { hub: &self } + } + pub fn landing_pages(&'a self) -> LandingPageMethods<'a, C, A> { + LandingPageMethods { hub: &self } + } + pub fn metros(&'a self) -> MetroMethods<'a, C, A> { + MetroMethods { hub: &self } + } + pub fn mobile_carriers(&'a self) -> MobileCarrierMethods<'a, C, A> { + MobileCarrierMethods { hub: &self } + } + pub fn operating_system_versions(&'a self) -> OperatingSystemVersionMethods<'a, C, A> { + OperatingSystemVersionMethods { hub: &self } + } + pub fn operating_systems(&'a self) -> OperatingSystemMethods<'a, C, A> { + OperatingSystemMethods { hub: &self } + } + pub fn order_documents(&'a self) -> OrderDocumentMethods<'a, C, A> { + OrderDocumentMethods { hub: &self } + } + pub fn orders(&'a self) -> OrderMethods<'a, C, A> { + OrderMethods { hub: &self } + } + pub fn placement_groups(&'a self) -> PlacementGroupMethods<'a, C, A> { + PlacementGroupMethods { hub: &self } + } + pub fn placement_strategies(&'a self) -> PlacementStrategyMethods<'a, C, A> { + PlacementStrategyMethods { hub: &self } + } + pub fn placements(&'a self) -> PlacementMethods<'a, C, A> { + PlacementMethods { hub: &self } + } + pub fn platform_types(&'a self) -> PlatformTypeMethods<'a, C, A> { + PlatformTypeMethods { hub: &self } + } + pub fn postal_codes(&'a self) -> PostalCodeMethods<'a, C, A> { + PostalCodeMethods { hub: &self } + } + pub fn projects(&'a self) -> ProjectMethods<'a, C, A> { + ProjectMethods { hub: &self } + } + pub fn regions(&'a self) -> RegionMethods<'a, C, A> { + RegionMethods { hub: &self } + } + pub fn remarketing_list_shares(&'a self) -> RemarketingListShareMethods<'a, C, A> { + RemarketingListShareMethods { hub: &self } + } + pub fn remarketing_lists(&'a self) -> RemarketingListMethods<'a, C, A> { + RemarketingListMethods { hub: &self } + } + pub fn reports(&'a self) -> ReportMethods<'a, C, A> { + ReportMethods { hub: &self } + } + pub fn sites(&'a self) -> SiteMethods<'a, C, A> { + SiteMethods { hub: &self } + } + pub fn sizes(&'a self) -> SizeMethods<'a, C, A> { + SizeMethods { hub: &self } + } + pub fn subaccounts(&'a self) -> SubaccountMethods<'a, C, A> { + SubaccountMethods { hub: &self } + } + pub fn targetable_remarketing_lists(&'a self) -> TargetableRemarketingListMethods<'a, C, A> { + TargetableRemarketingListMethods { hub: &self } + } + pub fn user_profiles(&'a self) -> UserProfileMethods<'a, C, A> { + UserProfileMethods { hub: &self } + } + pub fn user_role_permission_groups(&'a self) -> UserRolePermissionGroupMethods<'a, C, A> { + UserRolePermissionGroupMethods { hub: &self } + } + pub fn user_role_permissions(&'a self) -> UserRolePermissionMethods<'a, C, A> { + UserRolePermissionMethods { hub: &self } + } + pub fn user_roles(&'a self) -> UserRoleMethods<'a, C, 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.9`. + /// + /// 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, Serialize, Deserialize)] +pub struct OperatingSystemsListResponse { + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#operatingSystemsListResponse". + pub kind: Option, + /// Operating system collection. + #[serde(rename="operatingSystems")] + pub operating_systems: Option>, +} + +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, Serialize, Deserialize)] +pub struct DirectorySiteSettings { + /// Whether this site accepts interstitial ads. + #[serde(rename="interstitialPlacementAccepted")] + pub interstitial_placement_accepted: Option, + /// Whether this directory site has disabled Nielsen OCR reach ratings. + #[serde(rename="nielsenOcrOptOut")] + pub nielsen_ocr_opt_out: Option, + /// Whether this directory site has disabled active view creatives. + #[serde(rename="activeViewOptOut")] + pub active_view_opt_out: Option, + /// Whether this directory site has disabled active view for in-stream video creatives. + #[serde(rename="videoActiveViewOptOut")] + pub video_active_view_opt_out: Option, + /// Directory site DFP settings. + pub dfp_settings: Option, + /// Whether this directory site has disabled generation of Verification ins tags. + #[serde(rename="verificationTagOptOut")] + pub verification_tag_opt_out: Option, + /// Whether this site accepts in-stream video ads. + pub instream_video_placement_accepted: Option, +} + +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) +/// * [get mobile carriers](struct.MobileCarrierGetCall.html) (response) +/// +#[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(rename="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(rename="countryCode")] + pub country_code: Option, + /// Name of this mobile carrier. + pub name: Option, +} + +impl Resource for MobileCarrier {} +impl ResponseResult 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(rename="accountId")] + pub account_id: Option, + /// IDs of the available user role permissions for this subaccount. + #[serde(rename="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, Serialize, Deserialize)] +pub struct AccountPermissionGroup { + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#accountPermissionGroup". + pub kind: Option, + /// ID of this account permission group. + pub id: Option, + /// Name of this account permission group. + pub name: Option, +} + +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, Serialize, 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(rename="nextPageToken")] + pub next_page_token: Option, + /// The dimension values returned in this response. + pub items: Option>, + /// The kind of list this is, in this case dfareporting#dimensionValueList. + pub kind: Option, + /// The eTag of this response for caching purposes. + pub etag: Option, +} + +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, Serialize, Deserialize)] +pub struct CampaignCreativeAssociationsListResponse { + /// Pagination token to be used for the next list operation. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// Campaign creative association collection + #[serde(rename="campaignCreativeAssociations")] + pub campaign_creative_associations: Option>, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#campaignCreativeAssociationsListResponse". + pub kind: Option, +} + +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, Serialize, Deserialize)] +pub struct FloodlightActivitiesListResponse { + /// Pagination token to be used for the next list operation. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#floodlightActivitiesListResponse". + pub kind: Option, + /// Floodlight activity collection. + #[serde(rename="floodlightActivities")] + pub floodlight_activities: Option>, +} + +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, Serialize, Deserialize)] +pub struct UserRolePermissionGroupsListResponse { + /// User role permission group collection. + #[serde(rename="userRolePermissionGroups")] + pub user_role_permission_groups: Option>, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#userRolePermissionGroupsListResponse". + pub kind: Option, +} + +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, Serialize, 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(rename="nextPageToken")] + pub next_page_token: Option, + /// The files returned in this response. + pub items: Option>, + /// The kind of list this is, in this case dfareporting#fileList. + pub kind: Option, + /// The eTag of this response for caching purposes. + pub etag: Option, +} + +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: Option, + /// List of custom rich media event IDs. Dimension values must be all of type dfa:richMediaEventTypeIdAndName. + #[serde(rename="filteredEventIds")] + pub filtered_event_ids: Option>, +} + +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: Option, + /// ID of this event tag override. This is a read-only, auto-generated field. + pub id: Option, +} + +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, Serialize, Deserialize)] +pub struct AccountActiveAdSummary { + /// Ads that can be activated for the account. + #[serde(rename="availableAds")] + pub available_ads: Option, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#accountActiveAdSummary". + pub kind: Option, + /// ID of the account. + #[serde(rename="accountId")] + pub account_id: Option, + /// Ads that have been activated for the account + #[serde(rename="activeAds")] + pub active_ads: Option, + /// Maximum number of active ads allowed for the account. + #[serde(rename="activeAdsLimitTier")] + pub active_ads_limit_tier: Option, +} + +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(rename="clickDuration")] + pub click_duration: Option, + /// 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(rename="postImpressionActivitiesDuration")] + pub post_impression_activities_duration: Option, +} + +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, Serialize, Deserialize)] +pub struct FloodlightActivitiesGenerateTagResponse { + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#floodlightActivitiesGenerateTagResponse". + pub kind: Option, + /// Generated tag for this floodlight activity. + #[serde(rename="floodlightActivityTag")] + pub floodlight_activity_tag: Option, +} + +impl ResponseResult for FloodlightActivitiesGenerateTagResponse {} + + +/// Remarketing List Population Rule Term. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ListPopulationTerm { + /// ID of the list in question. This field is only relevant when type is set to LIST_MEMBERSHIP_TERM. + #[serde(rename="remarketingListId")] + pub remarketing_list_id: Option, + /// Will be true if the term should check if the user is in the list and false if the term should check if the user is not in the list. This field is only relevant when type is set to LIST_MEMBERSHIP_TERM. False by default. + pub contains: Option, + /// Whether to negate the comparison result of this term during rule evaluation. This field is only relevant when type is left unset or set to CUSTOM_VARIABLE_TERM or REFERRER_TERM. + pub negation: Option, + /// Literal to compare the variable to. This field is only relevant when type is left unset or set to CUSTOM_VARIABLE_TERM or REFERRER_TERM. + pub value: Option, + /// Friendly name of this term's variable. This is a read-only, auto-generated field. This field is only relevant when type is left unset or set to CUSTOM_VARIABLE_TERM. + #[serde(rename="variableFriendlyName")] + pub variable_friendly_name: Option, + /// Comparison operator of this term. This field is only relevant when type is left unset or set to CUSTOM_VARIABLE_TERM or REFERRER_TERM. + pub operator: Option, + /// List population term type determines the applicable fields in this object. If left unset or set to CUSTOM_VARIABLE_TERM, then variableName, variableFriendlyName, operator, value, and negation are applicable. If set to LIST_MEMBERSHIP_TERM then remarketingListId and contains are applicable. If set to REFERRER_TERM then operator, value, and negation are applicable. + #[serde(rename="type")] + pub type_: Option, + /// Name of the variable (U1, U2, etc.) being compared in this term. This field is only relevant when type is set to null, CUSTOM_VARIABLE_TERM or REFERRER_TERM. + #[serde(rename="variableName")] + pub variable_name: Option, +} + +impl Part for ListPopulationTerm {} + + +/// 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(rename="disableBrandSafeAds")] + pub disable_brand_safe_ads: Option, + /// Site-wide creative settings. + #[serde(rename="creativeSettings")] + pub creative_settings: Option, + /// Whether active view creatives are disabled for this site. + #[serde(rename="activeViewOptOut")] + pub active_view_opt_out: Option, + /// Lookback window settings for this site. + #[serde(rename="lookbackConfiguration")] + pub lookback_configuration: Option, + /// Whether new cookies are disabled for this site. + #[serde(rename="disableNewCookie")] + pub disable_new_cookie: Option, + /// Configuration settings for dynamic and image floodlight tags. + #[serde(rename="tagSetting")] + pub tag_setting: Option, +} + +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) +/// * [insert account user profiles](struct.AccountUserProfileInsertCall.html) (request|response) +/// * [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(rename="siteFilter")] + pub site_filter: Option, + /// Filter that describes which campaigns are visible to the user profile. + #[serde(rename="campaignFilter")] + pub campaign_filter: Option, + /// User role ID of the user profile. This is a required field. + #[serde(rename="userRoleId")] + pub user_role_id: Option, + /// User type of the user profile. This is a read-only field that can be left blank. + #[serde(rename="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(rename="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(rename="subaccountId")] + pub subaccount_id: Option, + /// Filter that describes which user roles are visible to the user profile. + #[serde(rename="userRoleFilter")] + pub user_role_filter: Option, + /// Trafficker type of this user profile. + #[serde(rename="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(rename="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(rename="dynamicTagEnabled")] + pub dynamic_tag_enabled: Option, + /// Whether image tags are enabled. + #[serde(rename="imageTagEnabled")] + pub image_tag_enabled: Option, +} + +impl Part for TagSettings {} + + +/// Contains properties of a targetable remarketing list. Remarketing enables you to create lists of users who have performed specific actions on a site, then target ads to members of those lists. This resource is a read-only view of a remarketing list to be used to faciliate targeting ads to specific lists. Remarketing lists that are owned by your advertisers and those that are shared to your advertisers or account are accessible via this resource. To manage remarketing lists that are owned by your advertisers, use the RemarketingLists 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 targetable remarketing lists](struct.TargetableRemarketingListListCall.html) (none) +/// * [get targetable remarketing lists](struct.TargetableRemarketingListGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct TargetableRemarketingList { + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#targetableRemarketingList". + pub kind: Option, + /// Subaccount ID of this remarketing list. This is a read-only, auto-generated field that is only returned in GET requests. + #[serde(rename="subaccountId")] + pub subaccount_id: Option, + /// Targetable remarketing list description. + pub description: Option, + /// Number of users currently in the list. This is a read-only field. + #[serde(rename="listSize")] + pub list_size: Option, + /// Number of days that a user should remain in the targetable remarketing list without an impression. + #[serde(rename="lifeSpan")] + pub life_span: Option, + /// Dimension value for the advertiser ID that owns this targetable remarketing list. + #[serde(rename="advertiserId")] + pub advertiser_id: Option, + /// Product from which this targetable remarketing list was originated. + #[serde(rename="listSource")] + pub list_source: Option, + /// Whether this targetable remarketing list is active. + pub active: Option, + /// Dimension value for the ID of the advertiser. + #[serde(rename="advertiserIdDimensionValue")] + pub advertiser_id_dimension_value: Option, + /// Account ID of this remarketing list. This is a read-only, auto-generated field that is only returned in GET requests. + #[serde(rename="accountId")] + pub account_id: Option, + /// Targetable remarketing list ID. + pub id: Option, + /// Name of the targetable remarketing list. Is no greater than 128 characters long. + pub name: Option, +} + +impl Resource for TargetableRemarketingList {} +impl ResponseResult for TargetableRemarketingList {} + + +/// 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*). +/// +/// * [get operating system versions](struct.OperatingSystemVersionGetCall.html) (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(rename="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 the first dot) of this operating system version. + #[serde(rename="minorVersion")] + pub minor_version: Option, + /// Name of this operating system version. + pub name: Option, + /// Operating system of this operating system version. + #[serde(rename="operatingSystem")] + pub operating_system: Option, + /// ID of this operating system version. + pub id: Option, +} + +impl Resource for OperatingSystemVersion {} +impl ResponseResult for OperatingSystemVersion {} + + +/// Remarketing 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 remarketing lists](struct.RemarketingListListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct RemarketingListsListResponse { + /// Pagination token to be used for the next list operation. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// Remarketing list collection. + #[serde(rename="remarketingLists")] + pub remarketing_lists: Option>, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#remarketingListsListResponse". + pub kind: Option, +} + +impl ResponseResult for RemarketingListsListResponse {} + + +/// 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(rename="creativeFieldId")] + pub creative_field_id: Option, + /// ID of the creative field value. + #[serde(rename="creativeFieldValueId")] + pub creative_field_value_id: Option, +} + +impl Part for CreativeFieldAssignment {} + + +/// Remarketing List Population 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 ListPopulationRule { + /// Floodlight activity ID associated with this rule. This field can be left blank. + #[serde(rename="floodlightActivityId")] + pub floodlight_activity_id: Option, + /// Name of floodlight activity associated with this rule. This is a read-only, auto-generated field. + #[serde(rename="floodlightActivityName")] + pub floodlight_activity_name: Option, + /// Clauses that make up this list population rule. Clauses are joined by ANDs, and the clauses themselves are made up of list population terms which are joined by ORs. + #[serde(rename="listPopulationClauses")] + pub list_population_clauses: Option>, +} + +impl Part for ListPopulationRule {} + + +/// 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(rename="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(rename="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(rename="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(rename="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(rename="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(rename="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(rename="maximumImageSize")] + pub maximum_image_size: Option, + /// Whether campaigns created in this account will be enabled for Nielsen OCR reach ratings by default. + #[serde(rename="nielsenOcrEnabled")] + pub nielsen_ocr_enabled: Option, + /// Default placement dimensions for this account. + #[serde(rename="defaultCreativeSizeId")] + pub default_creative_size_id: Option, + /// Account permissions assigned to this account. + #[serde(rename="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(rename="currencyId")] + pub currency_id: Option, + /// Reporting configuration of this account. + #[serde(rename="reportsConfiguration")] + pub reports_configuration: Option, + /// Maximum number of active ads allowed for this account. + #[serde(rename="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(rename="daysOfWeek")] + pub days_of_week: Option>, + /// 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(rename="hoursOfDay")] + pub hours_of_day: Option>, + /// Whether or not to use the user's local time. If false, the America/New York time zone applies. + #[serde(rename="userLocalTime")] + pub user_local_time: Option, +} + +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, Serialize, Deserialize)] +pub struct CompatibleFields { + /// The kind of resource this is, in this case dfareporting#compatibleFields. + pub kind: Option, + /// Contains items that are compatible to be selected for a report of type "CROSS_DIMENSION_REACH". + #[serde(rename="crossDimensionReachReportCompatibleFields")] + pub cross_dimension_reach_report_compatible_fields: Option, + /// Contains items that are compatible to be selected for a report of type "REACH". + #[serde(rename="reachReportCompatibleFields")] + pub reach_report_compatible_fields: Option, + /// Contains items that are compatible to be selected for a report of type "PATH_TO_CONVERSION". + #[serde(rename="pathToConversionReportCompatibleFields")] + pub path_to_conversion_report_compatible_fields: Option, + /// Contains items that are compatible to be selected for a report of type "FLOODLIGHT". + #[serde(rename="floodlightReportCompatibleFields")] + pub floodlight_report_compatible_fields: Option, + /// Contains items that are compatible to be selected for a report of type "STANDARD". + #[serde(rename="reportCompatibleFields")] + pub report_compatible_fields: Option, +} + +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(rename="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(rename="countryDartId")] + pub country_dart_id: Option, + /// Name of this region. + pub name: Option, + /// Country code of the country to which this region belongs. + #[serde(rename="countryCode")] + pub country_code: Option, + /// DART ID of this region. + #[serde(rename="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: Option, + /// The list of standard dimensions the report should include. + pub dimensions: Option>, + /// The list of names of metrics the report should include. + #[serde(rename="metricNames")] + pub metric_names: Option>, + /// The date range for which this report should be run. + #[serde(rename="dateRange")] + pub date_range: Option, + /// Custom Rich Media Events group. + #[serde(rename="customRichMediaEvents")] + pub custom_rich_media_events: Option, + /// 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(rename="dimensionFilters")] + pub dimension_filters: Option>, +} + +impl NestedType for ReportCriteria {} +impl Part for ReportCriteria {} + + +/// Order 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 orders](struct.OrderListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct OrdersListResponse { + /// Pagination token to be used for the next list operation. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#ordersListResponse". + pub kind: Option, + /// Order collection. + pub orders: Option>, +} + +impl ResponseResult for OrdersListResponse {} + + +/// 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, Serialize, Deserialize)] +pub struct CrossDimensionReachReportCompatibleFields { + /// Dimensions which are compatible to be selected in the "breakdown" section of the report. + pub breakdown: Option>, + /// Metrics which are compatible to be selected in the "metricNames" section of the report. + pub metrics: Option>, + /// The kind of resource this is, in this case dfareporting#crossDimensionReachReportCompatibleFields. + pub kind: Option, + /// Metrics which are compatible to be selected in the "overlapMetricNames" section of the report. + #[serde(rename="overlapMetrics")] + pub overlap_metrics: Option>, + /// Dimensions which are compatible to be selected in the "dimensionFilters" section of the report. + #[serde(rename="dimensionFilters")] + pub dimension_filters: Option>, +} + +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(rename="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(rename="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(rename="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(rename="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, Serialize, Deserialize)] +pub struct EventTagsListResponse { + /// Event tag collection. + #[serde(rename="eventTags")] + pub event_tags: Option>, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#eventTagsListResponse". + pub kind: Option, +} + +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(rename="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(rename="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(rename="advertiserId")] + pub advertiser_id: Option, + /// Dimension value for the ID of the floodlight configuration. This is a read-only, auto-generated field. + #[serde(rename="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(rename="idDimensionValue")] + pub id_dimension_value: Option, + /// Dimension value for the ID of the advertiser. This is a read-only, auto-generated field. + #[serde(rename="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(rename="tagString")] + pub tag_string: Option, + /// Type of the floodlight activity group. This is a required field that is read-only after insertion. + #[serde(rename="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(rename="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: Option, + /// ID of this audience segment. This is a read-only, auto-generated field. + pub id: Option, + /// Name of this audience segment. This is a required field and must be less than 65 characters long. + pub name: Option, +} + +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(rename="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(rename="endDate")] + pub end_date: Option, + /// Click-through URL suffix override properties for this campaign. + #[serde(rename="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(rename="additionalCreativeOptimizationConfigurations")] + pub additional_creative_optimization_configurations: Option>, + /// Advertiser ID of this campaign. This is a required field. + #[serde(rename="advertiserId")] + pub advertiser_id: Option, + /// Audience segment groups assigned to this campaign. Cannot have more than 300 segment groups. + #[serde(rename="audienceSegmentGroups")] + pub audience_segment_groups: Option>, + /// Information about the creation of this campaign. This is a read-only field. + #[serde(rename="createInfo")] + pub create_info: Option, + /// Click-through event tag ID override properties for this campaign. + #[serde(rename="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(rename="advertiserIdDimensionValue")] + pub advertiser_id_dimension_value: Option, + /// Overrides that can be used to activate or deactivate advertiser event tags. + #[serde(rename="eventTagOverrides")] + pub event_tag_overrides: Option>, + /// Creative optimization configuration for the campaign. + #[serde(rename="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(rename="accountId")] + pub account_id: Option, + /// Campaign trafficker contact emails. + #[serde(rename="traffickerEmails")] + pub trafficker_emails: Option>, + /// List of creative group IDs that are assigned to the campaign. + #[serde(rename="creativeGroupIds")] + pub creative_group_ids: Option>, + /// Subaccount ID of this campaign. This is a read-only field that can be left blank. + #[serde(rename="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(rename="lookbackConfiguration")] + pub lookback_configuration: Option, + /// Whether Nielsen reports are enabled for this campaign. + #[serde(rename="nielsenOcrEnabled")] + pub nielsen_ocr_enabled: Option, + /// Information about the most recent modification of this campaign. This is a read-only field. + #[serde(rename="lastModifiedInfo")] + pub last_modified_info: Option, + /// Whether comScore vCE reports are enabled for this campaign. + #[serde(rename="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(rename="externalId")] + pub external_id: Option, + /// Advertiser group ID of the associated advertiser. + #[serde(rename="advertiserGroupId")] + pub advertiser_group_id: Option, + /// Dimension value for the ID of this campaign. This is a read-only, auto-generated field. + #[serde(rename="idDimensionValue")] + pub id_dimension_value: Option, + /// Billing invoice code included in the DCM client billing invoices associated with the campaign. + #[serde(rename="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, Serialize, Deserialize)] +pub struct ChangeLog { + /// Time when the object was modified. + #[serde(rename="changeTime")] + pub change_time: Option, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#changeLog". + pub kind: Option, + /// Subaccount ID of the modified object. + #[serde(rename="subaccountId")] + pub subaccount_id: Option, + /// Old value of the object field. + #[serde(rename="oldValue")] + pub old_value: Option, + /// ID of the object of this change log. The object could be a campaign, placement, ad, or other type. + #[serde(rename="objectId")] + pub object_id: Option, + /// ID of this change log. + pub id: Option, + /// User profile name of the user who modified the object. + #[serde(rename="userProfileName")] + pub user_profile_name: Option, + /// Field name of the object which changed. + #[serde(rename="fieldName")] + pub field_name: Option, + /// ID of the user who modified the object. + #[serde(rename="userProfileId")] + pub user_profile_id: Option, + /// Action which caused the change. + pub action: Option, + /// 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(rename="transactionId")] + pub transaction_id: Option, + /// Account ID of the modified object. + #[serde(rename="accountId")] + pub account_id: Option, + /// New value of the object field. + #[serde(rename="newValue")] + pub new_value: Option, + /// Object type of the change log. + #[serde(rename="objectType")] + pub object_type: Option, +} + +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, Serialize, Deserialize)] +pub struct File { + /// The status of the report file. + pub status: Option, + /// The kind of resource this is, in this case dfareporting#file. + pub kind: Option, + /// The output format of the report. Only available once the file is available. + pub format: Option, + /// 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(rename="dateRange")] + pub date_range: Option, + /// The filename of the file. + #[serde(rename="fileName")] + pub file_name: Option, + /// The eTag of this response for caching purposes. + pub etag: Option, + /// The ID of the report this file was generated from. + #[serde(rename="reportId")] + pub report_id: Option, + /// The URLs where the completed report file can be downloaded. + pub urls: Option, + /// The timestamp in milliseconds since epoch when this file was last modified. + #[serde(rename="lastModifiedTime")] + pub last_modified_time: Option, + /// The unique ID of this report file. + pub id: Option, +} + +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: Option, +} + +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: Option>, + /// Whether the report is pivoted or not. Defaults to true. + pub pivoted: Option, + /// The list of names of overlap metrics the report should include. + #[serde(rename="overlapMetricNames")] + pub overlap_metric_names: Option>, + /// The list of names of metrics the report should include. + #[serde(rename="metricNames")] + pub metric_names: Option>, + /// The date range this report should be run for. + #[serde(rename="dateRange")] + pub date_range: Option, + /// The list of filters on which dimensions are filtered. + #[serde(rename="dimensionFilters")] + pub dimension_filters: Option>, + /// The dimension option. + pub dimension: Option, +} + +impl NestedType for ReportCrossDimensionReachCriteria {} +impl Part for ReportCrossDimensionReachCriteria {} + + +/// 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(rename="campaignId")] + pub campaign_id: Option, + /// Payment source for this placement. This is a required field that is read-only after insertion. + #[serde(rename="paymentSource")] + pub payment_source: Option, + /// Dimension value for the ID of the directory site. This is a read-only, auto-generated field. + #[serde(rename="directorySiteIdDimensionValue")] + pub directory_site_id_dimension_value: Option, + /// Advertiser ID of this placement. This field can be left blank. + #[serde(rename="advertiserId")] + pub advertiser_id: Option, + /// Key name of this placement. This is a read-only, auto-generated field. + #[serde(rename="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(rename="directorySiteId")] + pub directory_site_id: Option, + /// Dimension value for the ID of the advertiser. This is a read-only, auto-generated field. + #[serde(rename="advertiserIdDimensionValue")] + pub advertiser_id_dimension_value: Option, + /// ID of the content category assigned to this placement. + #[serde(rename="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(rename="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(rename="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(rename="paymentApproved")] + pub payment_approved: Option, + /// Tag settings for this placement. + #[serde(rename="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(rename="externalId")] + pub external_id: Option, + /// Dimension value for the ID of this placement. This is a read-only, auto-generated field. + #[serde(rename="idDimensionValue")] + pub id_dimension_value: Option, + /// Account ID of this placement. This field can be left blank. + #[serde(rename="accountId")] + pub account_id: Option, + /// Whether creatives assigned to this placement must be SSL-compliant. + #[serde(rename="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(rename="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(rename="placementGroupId")] + pub placement_group_id: Option, + /// Information about the creation of this placement. This is a read-only field. + #[serde(rename="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(rename="siteId")] + pub site_id: Option, + /// Dimension value for the ID of the site. This is a read-only, auto-generated field. + #[serde(rename="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(rename="placementStrategyId")] + pub placement_strategy_id: Option, + /// Dimension value for the ID of the placement group. This is a read-only, auto-generated field. + #[serde(rename="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(rename="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(rename="lookbackConfiguration")] + pub lookback_configuration: Option, + /// Information about the most recent modification of this placement. This is a read-only field. + #[serde(rename="lastModifiedInfo")] + pub last_modified_info: Option, + /// Pricing schedule of this placement. This field is required on insertion, specifically subfields startDate, endDate and pricingType. + #[serde(rename="pricingSchedule")] + pub pricing_schedule: Option, +} + +impl RequestValue for Placement {} +impl Resource for Placement {} +impl ResponseResult for Placement {} + + +/// Inventory item 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 inventory items](struct.InventoryItemListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct InventoryItemsListResponse { + /// Pagination token to be used for the next list operation. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#inventoryItemsListResponse". + pub kind: Option, + /// Inventory item collection + #[serde(rename="inventoryItems")] + pub inventory_items: Option>, +} + +impl ResponseResult for InventoryItemsListResponse {} + + +/// 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(rename="audienceSegments")] + pub audience_segments: Option>, + /// ID of this audience segment group. This is a read-only, auto-generated field. + pub id: Option, + /// Name of this audience segment group. This is a required field and must be less than 65 characters long. + pub name: Option, +} + +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(rename="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. It 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 {} + + +/// 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(rename="floodlightActivityId")] + pub floodlight_activity_id: Option, + /// Dimension value for the ID of the floodlight activity. This is a read-only, auto-generated field. + #[serde(rename="floodlightActivityIdDimensionValue")] + pub floodlight_activity_id_dimension_value: Option, + /// 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: Option, +} + +impl Part for OptimizationActivity {} + + +/// Placement 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 PlacementTag { + /// Tags generated for this placement. + #[serde(rename="tagDatas")] + pub tag_datas: Option>, + /// Placement ID + #[serde(rename="placementId")] + pub placement_id: Option, +} + +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, Serialize, Deserialize)] +pub struct CountriesListResponse { + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#countriesListResponse". + pub kind: Option, + /// Country collection. + pub countries: Option>, +} + +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 { + /// Read-only convenience field representing the actual URL that will be used for this click-through. The URL is computed as follows: + /// - If defaultLandingPage is enabled then the campaign's default landing page URL is assigned to this field. + /// - If defaultLandingPage is not enabled and a landingPageId is specified then that landing page's URL is assigned to this field. + /// - If neither of the above cases apply, then the customClickThroughUrl is assigned to this field. + #[serde(rename="computedClickThroughUrl")] + pub computed_click_through_url: Option, + /// Custom click-through URL. Applicable if the defaultLandingPage field is set to false and the landingPageId field is left unset. + #[serde(rename="customClickThroughUrl")] + pub custom_click_through_url: Option, + /// ID of the landing page for the click-through URL. Applicable if the defaultLandingPage field is set to false. + #[serde(rename="landingPageId")] + pub landing_page_id: Option, + /// Whether the campaign default landing page is used. + #[serde(rename="defaultLandingPage")] + pub default_landing_page: Option, +} + +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(rename="clickThroughUrl")] + pub click_through_url: Option, + /// ID of the creative for this companion click-through override. + #[serde(rename="creativeId")] + pub creative_id: Option, +} + +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: Option, + /// Number of times an individual user can be served the ad within the specified duration. The maximum allowed is 15. + pub impressions: Option, +} + +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(rename="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 {} + + +/// Contains properties of a remarketing list's sharing information. Sharing allows other accounts or advertisers to target to your remarketing lists. This resource can be used to manage remarketing list sharing to other accounts and advertisers. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where 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 remarketing list shares](struct.RemarketingListShareGetCall.html) (response) +/// * [patch remarketing list shares](struct.RemarketingListSharePatchCall.html) (request|response) +/// * [update remarketing list shares](struct.RemarketingListShareUpdateCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct RemarketingListShare { + /// Advertisers that the remarketing list is shared with. + #[serde(rename="sharedAdvertiserIds")] + pub shared_advertiser_ids: Option>, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#remarketingListShare". + pub kind: Option, + /// Remarketing list ID. This is a read-only, auto-generated field. + #[serde(rename="remarketingListId")] + pub remarketing_list_id: Option, + /// Accounts that the remarketing list is shared with. + #[serde(rename="sharedAccountIds")] + pub shared_account_ids: Option>, +} + +impl RequestValue for RemarketingListShare {} +impl Resource for RemarketingListShare {} +impl ResponseResult for RemarketingListShare {} + + +/// 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, Serialize, Deserialize)] +pub struct OperatingSystemVersionsListResponse { + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#operatingSystemVersionsListResponse". + pub kind: Option, + /// Operating system version collection. + #[serde(rename="operatingSystemVersions")] + pub operating_system_versions: Option>, +} + +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(rename="accountId")] + pub account_id: Option, + /// ID of this content category. This is a read-only, auto-generated field. + pub id: 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, +} + +impl RequestValue for ContentCategory {} +impl ResponseResult for ContentCategory {} + + +/// Targetable remarketing 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 targetable remarketing lists](struct.TargetableRemarketingListListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct TargetableRemarketingListsListResponse { + /// Pagination token to be used for the next list operation. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#targetableRemarketingListsListResponse". + pub kind: Option, + /// Targetable remarketing list collection. + #[serde(rename="targetableRemarketingLists")] + pub targetable_remarketing_lists: Option>, +} + +impl ResponseResult for TargetableRemarketingListsListResponse {} + + +/// Represents a buy from the DoubleClick Planning inventory store. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where 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 inventory items](struct.InventoryItemGetCall.html) (response) +/// * [list inventory items](struct.InventoryItemListCall.html) (none) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct InventoryItem { + /// Order ID of this inventory item. + #[serde(rename="orderId")] + pub order_id: Option, + /// Advertiser ID of this inventory item. + #[serde(rename="advertiserId")] + pub advertiser_id: Option, + /// ID of the site this inventory item is associated with. + #[serde(rename="siteId")] + pub site_id: Option, + /// Ad slots of this inventory item. If this inventory item represents a standalone placement, there will be exactly one ad slot. If this inventory item represents a placement group, there will be more than one ad slot, each representing one child placement in that placement group. + #[serde(rename="adSlots")] + pub ad_slots: Option>, + /// RFP ID of this inventory item. + #[serde(rename="rfpId")] + pub rfp_id: Option, + /// Content category ID of this inventory item. + #[serde(rename="contentCategoryId")] + pub content_category_id: Option, + /// Placement strategy ID of this inventory item. + #[serde(rename="placementStrategyId")] + pub placement_strategy_id: Option, + /// Account ID of this inventory item. + #[serde(rename="accountId")] + pub account_id: Option, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#inventoryItem". + pub kind: Option, + /// Negotiation channel ID of this inventory item. + #[serde(rename="negotiationChannelId")] + pub negotiation_channel_id: Option, + /// Subaccount ID of this inventory item. + #[serde(rename="subaccountId")] + pub subaccount_id: Option, + /// Name of this inventory item. For standalone inventory items, this is the same name as that of its only ad slot. For group inventory items, this can differ from the name of any of its ad slots. + pub name: Option, + /// Estimated click-through rate of this inventory item. + #[serde(rename="estimatedClickThroughRate")] + pub estimated_click_through_rate: Option, + /// Information about the most recent modification of this inventory item. + #[serde(rename="lastModifiedInfo")] + pub last_modified_info: Option, + /// Estimated conversion rate of this inventory item. + #[serde(rename="estimatedConversionRate")] + pub estimated_conversion_rate: Option, + /// Whether this inventory item is in plan. + #[serde(rename="inPlan")] + pub in_plan: Option, + /// ID of this inventory item. + pub id: Option, + /// Project ID of this inventory item. + #[serde(rename="projectId")] + pub project_id: Option, + /// Pricing of this inventory item. + pub pricing: Option, +} + +impl Resource for InventoryItem {} +impl ResponseResult for InventoryItem {} + + +/// 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, Serialize, Deserialize)] +pub struct FloodlightReportCompatibleFields { + /// Metrics which are compatible to be selected in the "metricNames" section of the report. + pub metrics: Option>, + /// The kind of resource this is, in this case dfareporting#floodlightReportCompatibleFields. + pub kind: Option, + /// Dimensions which are compatible to be selected in the "dimensionFilters" section of the report. + #[serde(rename="dimensionFilters")] + pub dimension_filters: Option>, + /// Dimensions which are compatible to be selected in the "dimensions" section of the report. + pub dimensions: Option>, +} + +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(rename="type")] + pub type_: Option, + /// 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: Option, +} + +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, Serialize, Deserialize)] +pub struct DirectorySiteContactAssignment { + /// ID of this directory site contact. This is a read-only, auto-generated field. + #[serde(rename="contactId")] + pub contact_id: Option, + /// 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: Option, +} + +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: Option, + /// Sequence number of the creative assignment, applicable when the rotation type is CREATIVE_ROTATION_TYPE_SEQUENTIAL. + pub sequence: Option, + /// Click-through URL of the creative assignment. + #[serde(rename="clickThroughUrl")] + pub click_through_url: Option, + /// 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(rename="richMediaExitOverrides")] + pub rich_media_exit_overrides: Option>, + /// 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(rename="applyEventTags")] + pub apply_event_tags: Option, + /// Creative group assignments for this creative assignment. Only one assignment per creative group number is allowed for a maximum of two assignments. + #[serde(rename="creativeGroupAssignments")] + pub creative_group_assignments: Option>, + /// Companion creative overrides for this creative assignment. Applicable to video ads. + #[serde(rename="companionCreativeOverrides")] + pub companion_creative_overrides: Option>, + /// Date and time that the assigned creative should start serving. + #[serde(rename="startTime")] + pub start_time: Option, + /// 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(rename="sslCompliant")] + pub ssl_compliant: Option, + /// Whether this creative assignment is active. When true, the creative will be included in the ad's rotation. + pub active: Option, + /// ID of the creative to be assigned. This is a required field. + #[serde(rename="creativeId")] + pub creative_id: Option, + /// Date and time that the assigned creative should stop serving. Must be later than the start time. + #[serde(rename="endTime")] + pub end_time: Option, + /// Dimension value for the ID of the creative. This is a read-only, auto-generated field. + #[serde(rename="creativeIdDimensionValue")] + pub creative_id_dimension_value: Option, +} + +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, Deserialize)] +pub struct DimensionValueRequest { + /// The name of the dimension for which values should be requested. + #[serde(rename="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(rename="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(rename="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 {} + + +/// Ad Slot +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct AdSlot { + /// Comment for this ad slot. + pub comment: Option, + /// ID of the placement from an external platform that is linked to this ad slot. + #[serde(rename="linkedPlacementId")] + pub linked_placement_id: Option, + /// Name of this ad slot. + pub name: Option, + /// Primary ad slot of a roadblock inventory item. + pub primary: Option, + /// Height of this ad slot. + pub height: Option, + /// Width of this ad slot. + pub width: Option, + /// Payment source type of this ad slot. + #[serde(rename="paymentSourceType")] + pub payment_source_type: Option, + /// Ad slot 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. + pub compatibility: Option, +} + +impl Part for AdSlot {} + + +/// 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(rename="overrideInheritedEventTag")] + pub override_inherited_event_tag: Option, + /// ID of the click-through event tag to apply to all ads in this entity's scope. + #[serde(rename="defaultClickThroughEventTagId")] + pub default_click_through_event_tag_id: Option, +} + +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, Serialize, Deserialize)] +pub struct UserProfileList { + /// The user profiles returned in this response. + pub items: Option>, + /// The kind of list this is, in this case dfareporting#userProfileList. + pub kind: Option, + /// The eTag of this response for caching purposes. + pub etag: Option, +} + +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, Serialize, Deserialize)] +pub struct SubaccountsListResponse { + /// Pagination token to be used for the next list operation. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#subaccountsListResponse". + pub kind: Option, + /// Subaccount collection. + pub subaccounts: Option>, +} + +impl ResponseResult for SubaccountsListResponse {} + + +/// Contains properties of a DoubleClick Planning order document. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where 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 order documents](struct.OrderDocumentGetCall.html) (response) +/// * [list order documents](struct.OrderDocumentListCall.html) (none) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct OrderDocument { + /// ID of the order from which this order document is created. + #[serde(rename="orderId")] + pub order_id: Option, + /// Timestamp of the last email sent with this order document. + #[serde(rename="lastSentTime")] + pub last_sent_time: Option, + /// The amended order document ID of this order document. An order document can be created by optionally amending another order document so that the change history can be preserved. + #[serde(rename="amendedOrderDocumentId")] + pub amended_order_document_id: Option, + /// List of email addresses that received the last sent document. + #[serde(rename="lastSentRecipients")] + pub last_sent_recipients: Option>, + /// IDs of users who have approved this order document. + #[serde(rename="approvedByUserProfileIds")] + pub approved_by_user_profile_ids: Option>, + /// ID of this order document. + pub id: Option, + /// Account ID of this order document. + #[serde(rename="accountId")] + pub account_id: Option, + /// Advertiser ID of this order document. + #[serde(rename="advertiserId")] + pub advertiser_id: Option, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#orderDocument". + pub kind: Option, + /// Subaccount ID of this order document. + #[serde(rename="subaccountId")] + pub subaccount_id: Option, + /// Effective date of this order document. + #[serde(rename="effectiveDate")] + pub effective_date: Option, + /// Title of this order document. + pub title: Option, + /// Project ID of this order document. + #[serde(rename="projectId")] + pub project_id: Option, + /// Whether this order document has been signed. + pub signed: Option, + /// Information about the creation of this order document. + #[serde(rename="createdInfo")] + pub created_info: Option, + /// Whether this order document is cancelled. + pub cancelled: Option, + /// Type of this order document + #[serde(rename="type")] + pub type_: Option, +} + +impl Resource for OrderDocument {} +impl ResponseResult for OrderDocument {} + + +/// 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(rename="ownerProfileId")] + pub owner_profile_id: Option, + /// The subaccount ID to which this report belongs if applicable. + #[serde(rename="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(rename="pathToConversionCriteria")] + pub path_to_conversion_criteria: Option, + /// The report criteria for a report of type "REACH". + #[serde(rename="reachCriteria")] + pub reach_criteria: Option, + /// The report criteria for a report of type "FLOODLIGHT". + #[serde(rename="floodlightCriteria")] + pub floodlight_criteria: Option, + /// The filename used when generating report files for this report. + #[serde(rename="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(rename="lastModifiedTime")] + pub last_modified_time: Option, + /// The report criteria for a report of type "CROSS_DIMENSION_REACH". + #[serde(rename="crossDimensionReachCriteria")] + pub cross_dimension_reach_criteria: Option, + /// The account ID to which this report belongs. + #[serde(rename="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(rename="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*). +/// +/// * [get platform types](struct.PlatformTypeGetCall.html) (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 {} +impl ResponseResult 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, Serialize, Deserialize)] +pub struct AdvertisersListResponse { + /// Pagination token to be used for the next list operation. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// Advertiser collection. + pub advertisers: Option>, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#advertisersListResponse". + pub kind: Option, +} + +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(rename="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(rename="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(rename="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(rename="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(rename="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(rename="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(rename="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(rename="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(rename="horizontallyLocked")] + pub horizontally_locked: Option, + /// Initial wait time type before making the asset visible. Applicable to the following creative types: all RICH_MEDIA. + #[serde(rename="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(rename="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(rename="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(rename="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(rename="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(rename="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(rename="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(rename="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(rename="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(rename="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(rename="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(rename="originalBackup")] + pub original_backup: Option, + /// Whether to hide selection boxes flag for an asset. Applicable to the following creative types: all RICH_MEDIA. + #[serde(rename="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(rename="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(rename="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(rename="childAssetType")] + pub child_asset_type: Option, + /// Exit event configured for the backup image. Applicable to the following creative types: all RICH_MEDIA. + #[serde(rename="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(rename="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(rename="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(rename="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(rename="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(rename="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(rename="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, Serialize, Deserialize)] +pub struct DirectorySitesListResponse { + /// Pagination token to be used for the next list operation. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#directorySitesListResponse". + pub kind: Option, + /// Directory site collection. + #[serde(rename="directorySites")] + pub directory_sites: Option>, +} + +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: Option, +} + +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, Serialize, Deserialize)] +pub struct RegionsListResponse { + /// Region collection. + pub regions: Option>, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#regionsListResponse". + pub kind: Option, +} + +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, Serialize, Deserialize)] +pub struct UserRolePermissionGroup { + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#userRolePermissionGroup". + pub kind: Option, + /// ID of this user role permission. + pub id: Option, + /// Name of this user role permission group. + pub name: Option, +} + +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(rename="eventName")] + pub event_name: Option, + /// 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: Option, + /// Parameter value for the specified click tag. This field contains a click-through url. + pub value: Option, +} + +impl Part for ClickTag {} + + +/// Contains information about an internet connection type that can be targeted by ads. Clients can use the connection type to target mobile vs. broadband users. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where 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 connection types](struct.ConnectionTypeGetCall.html) (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 {} +impl ResponseResult 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, Serialize, Deserialize)] +pub struct BrowsersListResponse { + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#browsersListResponse". + pub kind: Option, + /// Browser collection. + pub browsers: Option>, +} + +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(rename="objectIds")] + pub object_ids: Option>, + /// 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: Option, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#objectFilter". + pub kind: Option, +} + +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(rename="iFrameHeader")] + pub i_frame_header: Option, + /// Header text for iFrames for this site. Must be less than or equal to 2000 characters long. + #[serde(rename="iFrameFooter")] + pub i_frame_footer: Option, +} + +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, Serialize, Deserialize)] +pub struct Dimension { + /// The kind of resource this is, in this case dfareporting#dimension. + pub kind: Option, + /// The dimension name, e.g. dfa:advertiser + pub name: Option, +} + +impl Part for Dimension {} + + +/// Contact of an order. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct OrderContact { + /// Type of this contact. + #[serde(rename="contactType")] + pub contact_type: Option, + /// Title of this contact. + #[serde(rename="contactTitle")] + pub contact_title: Option, + /// Free-form information about this contact. It could be any information related to this contact in addition to type, title, name, and signature user profile ID. + #[serde(rename="contactInfo")] + pub contact_info: Option, + /// Name of this contact. + #[serde(rename="contactName")] + pub contact_name: Option, + /// ID of the user profile containing the signature that will be embedded into order documents. + #[serde(rename="signatureUserProfileId")] + pub signature_user_profile_id: Option, +} + +impl Part for OrderContact {} + + +/// 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) +/// * [insert directory sites](struct.DirectorySiteInsertCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct DirectorySite { + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#directorySite". + pub kind: Option, + /// Country ID of this directory site. + #[serde(rename="countryId")] + pub country_id: Option, + /// Description of this directory site. + pub description: Option, + /// Directory site settings. + pub settings: Option, + /// 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(rename="currencyId")] + pub currency_id: Option, + /// Tag types for regular placements. + /// + /// Acceptable values are: + /// - "STANDARD" + /// - "IFRAME_JAVASCRIPT_INPAGE" + /// - "INTERNAL_REDIRECT_INPAGE" + /// - "JAVASCRIPT_INPAGE" + #[serde(rename="inpageTagFormats")] + pub inpage_tag_formats: Option>, + /// URL of this directory site. + pub url: Option, + /// Directory site contacts. + #[serde(rename="contactAssignments")] + pub contact_assignments: Option>, + /// Parent directory site ID. + #[serde(rename="parentId")] + pub parent_id: Option, + /// Tag types for interstitial placements. + /// + /// Acceptable values are: + /// - "IFRAME_JAVASCRIPT_INTERSTITIAL" + /// - "INTERNAL_REDIRECT_INTERSTITIAL" + /// - "JAVASCRIPT_INTERSTITIAL" + #[serde(rename="interstitialTagFormats")] + pub interstitial_tag_formats: Option>, + /// Dimension value for the ID of this directory site. This is a read-only, auto-generated field. + #[serde(rename="idDimensionValue")] + pub id_dimension_value: Option, + /// Whether this directory site is active. + pub active: Option, + /// ID of this directory site. This is a read-only, auto-generated field. + pub id: Option, + /// Name of this directory site. + pub name: Option, +} + +impl RequestValue for DirectorySite {} +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, Serialize, Deserialize)] +pub struct CitiesListResponse { + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#citiesListResponse". + pub kind: Option, + /// City collection. + pub cities: Option>, +} + +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(rename="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(rename="groupNumber")] + pub group_number: Option, + /// Advertiser ID of this creative group. This is a required field on insertion. + #[serde(rename="advertiserId")] + pub advertiser_id: Option, + /// Dimension value for the ID of the advertiser. This is a read-only, auto-generated field. + #[serde(rename="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(rename="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, Serialize, Deserialize)] +pub struct Metric { + /// The kind of resource this is, in this case dfareporting#metric. + pub kind: Option, + /// The metric name, e.g. dfa:impressions + pub name: Option, +} + +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(rename="customExitUrl")] + pub custom_exit_url: Option, + /// Whether to use the custom exit URL. + #[serde(rename="useCustomExitUrl")] + pub use_custom_exit_url: Option, + /// ID for the override to refer to a specific exit in the creative. + #[serde(rename="exitId")] + pub exit_id: Option, +} + +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, Serialize, Deserialize)] +pub struct AccountPermissionsListResponse { + /// Account permission collection. + #[serde(rename="accountPermissions")] + pub account_permissions: Option>, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#accountPermissionsListResponse". + pub kind: Option, +} + +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, Serialize, Deserialize)] +pub struct PlacementsGenerateTagsResponse { + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#placementsGenerateTagsResponse". + pub kind: Option, + /// Set of generated tags for the specified placements. + #[serde(rename="placementTags")] + pub placement_tags: Option>, +} + +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, Serialize, Deserialize)] +pub struct FloodlightActivityGroupsListResponse { + /// Pagination token to be used for the next list operation. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#floodlightActivityGroupsListResponse". + pub kind: Option, + /// Floodlight activity group collection. + #[serde(rename="floodlightActivityGroups")] + pub floodlight_activity_groups: Option>, +} + +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, Serialize, Deserialize)] +pub struct DirectorySiteContactsListResponse { + /// Pagination token to be used for the next list operation. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// Directory site contact collection + #[serde(rename="directorySiteContacts")] + pub directory_site_contacts: Option>, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#directorySiteContactsListResponse". + pub kind: Option, +} + +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(rename="targetType")] + pub target_type: Option, + /// Artwork type used by the creative.This is a read-only field. + #[serde(rename="artworkType")] + pub artwork_type: Option, + /// Reporting ID, used to differentiate multiple videos in a single creative. + #[serde(rename="videoReportingId")] + pub video_reporting_id: Option, + /// Properties for rich media popup windows. This field is used only for exit events. + #[serde(rename="popupWindowProperties")] + pub popup_window_properties: Option, + /// 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(rename="artworkLabel")] + pub artwork_label: Option, + /// Type of the event. This is a read-only field. + #[serde(rename="advertiserCustomEventType")] + pub advertiser_custom_event_type: Option, + /// Exit URL of the event. This field is used only for exit events. + #[serde(rename="exitUrl")] + pub exit_url: Option, + /// ID of this event. This is a required field and should not be modified after insertion. + pub id: Option, + /// User-entered name for the event. + #[serde(rename="advertiserCustomEventName")] + pub advertiser_custom_event_name: Option, +} + +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, Serialize, Deserialize)] +pub struct CreativesListResponse { + /// Pagination token to be used for the next list operation. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#creativesListResponse". + pub kind: Option, + /// Creative collection. + pub creatives: Option>, +} + +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(rename="omnitureCostDataEnabled")] + pub omniture_cost_data_enabled: Option, + /// Whether Omniture integration is enabled. This property can be enabled only when the "Advanced Ad Serving" account setting is enabled. + #[serde(rename="omnitureIntegrationEnabled")] + pub omniture_integration_enabled: Option, +} + +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, Serialize, Deserialize)] +pub struct PathToConversionReportCompatibleFields { + /// Metrics which are compatible to be selected in the "metricNames" section of the report. + pub metrics: Option>, + /// Per-interaction dimensions which are compatible to be selected in the "perInteractionDimensions" section of the report. + #[serde(rename="perInteractionDimensions")] + pub per_interaction_dimensions: Option>, + /// The kind of resource this is, in this case dfareporting#pathToConversionReportCompatibleFields. + pub kind: Option, + /// Conversion dimensions which are compatible to be selected in the "conversionDimensions" section of the report. + #[serde(rename="conversionDimensions")] + pub conversion_dimensions: Option>, + /// Custom floodlight variables which are compatible to be selected in the "customFloodlightVariables" section of the report. + #[serde(rename="customFloodlightVariables")] + pub custom_floodlight_variables: Option>, +} + +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, Serialize, Deserialize)] +pub struct MobileCarriersListResponse { + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#mobileCarriersListResponse". + pub kind: Option, + /// Mobile carrier collection. + #[serde(rename="mobileCarriers")] + pub mobile_carriers: Option>, +} + +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: Option, + /// ID of this dynamic tag. This is a read-only, auto-generated field. + pub id: Option, + /// Name of this tag. + pub name: Option, +} + +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(rename="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(rename="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(rename="counterCustomEvents")] + pub counter_custom_events: Option>, + /// Advertiser ID of this creative. This is a required field. Applicable to all creative types. + #[serde(rename="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(rename="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(rename="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(rename="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(rename="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(rename="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(rename="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(rename="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(rename="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(rename="exitCustomEvents")] + pub exit_custom_events: Option>, + /// ID of current rendering version. This is a read-only field. Applicable to all creative types. + #[serde(rename="renderingId")] + pub rendering_id: Option, + /// Description of the video ad. Applicable to the following creative types: INSTREAM_VIDEO and all VPAID. + #[serde(rename="videoDescription")] + pub video_description: Option, + /// Third-party URL used to record backup image impressions. Applicable to the following creative types: all RICH_MEDIA + #[serde(rename="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(rename="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(rename="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(rename="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(rename="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(rename="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(rename="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(rename="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(rename="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(rename="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(rename="backupImageFeatures")] + pub backup_image_features: 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(rename="videoDuration")] + pub video_duration: 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(rename="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(rename="clickTags")] + pub click_tags: Option>, + /// Target window for backup image. Applicable to the following creative types: ENHANCED_BANNER, FLASH_INPAGE, and HTML5_BANNER. + #[serde(rename="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(rename="requiredFlashPluginVersion")] + pub required_flash_plugin_version: Option, + /// Reporting label used for HTML5 banner backup image. Applicable to the following creative types: ENHANCED_BANNER. + #[serde(rename="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(rename="adParameters")] + pub ad_parameters: 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(rename="htmlCodeLocked")] + pub html_code_locked: 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(rename="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, + /// 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(rename="adTagKeys")] + pub ad_tag_keys: Option>, + /// Whether Flash assets associated with the creative need to be automatically converted to HTML5. This flag is enabled by default and users can choose to disable it if they don't want the system to generate and use HTML5 asset for this creative. Applicable to the following creative types: ENHANCED_BANNER and FLASH_INPAGE. + #[serde(rename="convertFlashToHtml5")] + pub convert_flash_to_html5: Option, + /// Whether creative should be treated as SSL compliant even if the system scan shows it's not. + #[serde(rename="sslOverride")] + pub ssl_override: Option, + /// Creative last modification information. This is a read-only field. Applicable to all creative types. + #[serde(rename="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(rename="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(rename="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(rename="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(rename="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(rename="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(rename="htmlCode")] + pub html_code: Option, + /// Whether the creative is SSL-compliant. This is a read-only field. Applicable to all creative types. + #[serde(rename="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(rename="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(rename="exposureToConversionEnabled")] + pub exposure_to_conversion_enabled: Option, + /// 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(rename="reportGenerationTimeZoneId")] + pub report_generation_time_zone_id: Option, + /// Default lookback windows for new advertisers in this account. + #[serde(rename="lookbackConfiguration")] + pub lookback_configuration: Option, +} + +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, Serialize, Deserialize)] +pub struct CampaignsListResponse { + /// Campaign collection. + pub campaigns: Option>, + /// Pagination token to be used for the next list operation. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#campaignsListResponse". + pub kind: Option, +} + +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, Serialize, Deserialize)] +pub struct UserRolePermissionsListResponse { + /// User role permission collection. + #[serde(rename="userRolePermissions")] + pub user_role_permissions: Option>, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#userRolePermissionsListResponse". + pub kind: Option, +} + +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, Serialize, Deserialize)] +pub struct UserProfile { + /// The user name. + #[serde(rename="userName")] + pub user_name: Option, + /// The kind of resource this is, in this case dfareporting#userProfile. + pub kind: Option, + /// The sub account ID this profile belongs to if applicable. + #[serde(rename="subAccountId")] + pub sub_account_id: Option, + /// The account name this profile belongs to. + #[serde(rename="accountName")] + pub account_name: Option, + /// The eTag of this response for caching purposes. + pub etag: Option, + /// The sub account name this profile belongs to if applicable. + #[serde(rename="subAccountName")] + pub sub_account_name: Option, + /// The unique ID of the user profile. + #[serde(rename="profileId")] + pub profile_id: Option, + /// The account ID to which this profile belongs. + #[serde(rename="accountId")] + pub account_id: Option, +} + +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(rename="creativeGroupId")] + pub creative_group_id: Option, + /// Creative group number of the creative group assignment. + #[serde(rename="creativeGroupNumber")] + pub creative_group_number: Option, +} + +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(rename="conversionDimensions")] + pub conversion_dimensions: Option>, + /// The list of names of metrics the report should include. + #[serde(rename="metricNames")] + pub metric_names: Option>, + /// The date range this report should be run for. + #[serde(rename="dateRange")] + pub date_range: Option, + /// The list of custom floodlight variables the report should include. + #[serde(rename="customFloodlightVariables")] + pub custom_floodlight_variables: Option>, + /// The list of 'dfa:activity' values to filter on. + #[serde(rename="activityFilters")] + pub activity_filters: Option>, + /// The list of custom rich media events to include. + #[serde(rename="customRichMediaEvents")] + pub custom_rich_media_events: Option>, + /// The list of per interaction dimensions the report should include. + #[serde(rename="perInteractionDimensions")] + pub per_interaction_dimensions: Option>, + /// The properties of the report. + #[serde(rename="reportProperties")] + pub report_properties: Option, + /// 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(rename="floodlightConfigId")] + pub floodlight_config_id: Option, +} + +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, Serialize, Deserialize)] +pub struct CreativeFieldsListResponse { + /// Pagination token to be used for the next list operation. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// Creative field collection. + #[serde(rename="creativeFields")] + pub creative_fields: Option>, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#creativeFieldsListResponse". + pub kind: Option, +} + +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: Option, + /// The type of delivery for the owner to receive, if enabled. + #[serde(rename="emailOwnerDeliveryType")] + pub email_owner_delivery_type: Option, + /// The list of recipients to which to email the report. + pub recipients: Option>, + /// Whether the report should be emailed to the report owner. + #[serde(rename="emailOwner")] + pub email_owner: Option, +} + +impl NestedType for ReportDelivery {} +impl Part for ReportDelivery {} + + +/// Project 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 projects](struct.ProjectListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ProjectsListResponse { + /// Pagination token to be used for the next list operation. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#projectsListResponse". + pub kind: Option, + /// Project collection. + pub projects: Option>, +} + +impl ResponseResult for ProjectsListResponse {} + + +/// 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: Option>, + /// 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: Option>, + /// 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: Option>, + /// 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: Option>, + /// 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(rename="excludeCountries")] + pub exclude_countries: Option, + /// 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(rename="postalCodes")] + pub postal_codes: Option>, +} + +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: Option, + /// 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(rename="hardCutoff")] + pub hard_cutoff: Option, + /// Limit on the number of times an individual user can be served the ad within a specified period of time. + #[serde(rename="frequencyCap")] + pub frequency_cap: Option, + /// 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(rename="impressionRatio")] + pub impression_ratio: Option, +} + +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(rename="startDate")] + pub start_date: Option, + /// 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(rename="runsOnDayOfMonth")] + pub runs_on_day_of_month: Option, + /// The expiration date when the scheduled report stops running. + #[serde(rename="expirationDate")] + pub expiration_date: Option, + /// Whether the schedule is active or not. Must be set to either true or false. + pub active: Option, + /// 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: Option, + /// 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: Option, + /// List of week days "WEEKLY" on which scheduled reports should run. + #[serde(rename="repeatsOnWeekDays")] + pub repeats_on_week_days: Option>, +} + +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: Option, + /// The delivery type for the recipient. + #[serde(rename="deliveryType")] + pub delivery_type: Option, + /// The email address of the recipient. + pub email: Option, +} + +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, Serialize, Deserialize)] +pub struct ReportCompatibleFields { + /// Metrics which are compatible to be selected in the "metricNames" section of the report. + pub metrics: Option>, + /// The kind of resource this is, in this case dfareporting#reportCompatibleFields. + pub kind: Option, + /// Metrics which are compatible to be selected as activity metrics to pivot on in the "activities" section of the report. + #[serde(rename="pivotedActivityMetrics")] + pub pivoted_activity_metrics: Option>, + /// Dimensions which are compatible to be selected in the "dimensions" section of the report. + pub dimensions: Option>, + /// Dimensions which are compatible to be selected in the "dimensionFilters" section of the report. + #[serde(rename="dimensionFilters")] + pub dimension_filters: Option>, +} + +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, Serialize, Deserialize)] +pub struct AdvertiserGroupsListResponse { + /// Pagination token to be used for the next list operation. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#advertiserGroupsListResponse". + pub kind: Option, + /// Advertiser group collection. + #[serde(rename="advertiserGroups")] + pub advertiser_groups: Option>, +} + +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, Serialize, Deserialize)] +pub struct PlacementGroupsListResponse { + /// Pagination token to be used for the next list operation. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#placementGroupsListResponse". + pub kind: Option, + /// Placement group collection. + #[serde(rename="placementGroups")] + pub placement_groups: Option>, +} + +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(rename="clicksLookbackWindow")] + pub clicks_lookback_window: Option, + /// Enable pivoting on interaction path. + #[serde(rename="pivotOnInteractionPath")] + pub pivot_on_interaction_path: Option, + /// 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(rename="impressionsLookbackWindow")] + pub impressions_lookback_window: Option, + /// 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(rename="includeUnattributedIPConversions")] + pub include_unattributed_ip_conversions: Option, + /// 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(rename="includeUnattributedCookieConversions")] + pub include_unattributed_cookie_conversions: Option, + /// The maximum amount of time that can take place between interactions (clicks or impressions) by the same user. Valid values: 1-90. + #[serde(rename="maximumInteractionGap")] + pub maximum_interaction_gap: Option, + /// Deprecated: has no effect. + #[serde(rename="includeAttributedIPConversions")] + pub include_attributed_ip_conversions: Option, + /// 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(rename="maximumClickInteractions")] + pub maximum_click_interactions: Option, + /// 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(rename="maximumImpressionInteractions")] + pub maximum_impression_interactions: Option, +} + +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: Option>, + /// 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(rename="operatingSystems")] + pub operating_systems: Option>, + /// 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(rename="mobileCarriers")] + pub mobile_carriers: Option>, + /// 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(rename="connectionTypes")] + pub connection_types: Option>, + /// 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(rename="platformTypes")] + pub platform_types: Option>, + /// 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(rename="operatingSystemVersions")] + pub operating_system_versions: Option>, +} + +impl Part for TechnologyTargeting {} + + +/// 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, Serialize, 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(rename="nextPageToken")] + pub next_page_token: Option, + /// The reports returned in this response. + pub items: Option>, + /// The kind of list this is, in this case dfareporting#reportList. + pub kind: Option, + /// The eTag of this response for caching purposes. + pub etag: Option, +} + +impl ResponseResult for ReportList {} + + +/// 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: Option, +} + +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(rename="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(rename="detectedFeatures")] + pub detected_features: Option>, + /// List of detected click tags for assets. This is a read-only auto-generated field. + #[serde(rename="clickTags")] + pub click_tags: Option>, + /// ID of the creative asset. This is a required field. + #[serde(rename="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, Serialize, Deserialize)] +pub struct TagData { + /// Tag string to record a click. + #[serde(rename="clickTag")] + pub click_tag: Option, + /// Tag string for serving an ad. + #[serde(rename="impressionTag")] + pub impression_tag: Option, + /// Creative associated with this placement tag. + #[serde(rename="creativeId")] + pub creative_id: Option, + /// Ad associated with this placement tag. + #[serde(rename="adId")] + pub ad_id: Option, + /// TagData tag format of this tag. + pub format: Option, +} + +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(rename="floodlightConfigId")] + pub floodlight_config_id: Option, + /// The list of dimensions the report should include. + pub dimensions: Option>, + /// The list of names of metrics the report should include. + #[serde(rename="metricNames")] + pub metric_names: Option>, + /// The date range this report should be run for. + #[serde(rename="dateRange")] + pub date_range: Option, + /// The list of custom rich media events to include. + #[serde(rename="customRichMediaEvents")] + pub custom_rich_media_events: Option>, + /// 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(rename="dimensionFilters")] + pub dimension_filters: Option>, + /// The properties of the report. + #[serde(rename="reportProperties")] + pub report_properties: Option, +} + +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, Serialize, Deserialize)] +pub struct LandingPagesListResponse { + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#landingPagesListResponse". + pub kind: Option, + /// Landing page collection + #[serde(rename="landingPages")] + pub landing_pages: Option>, +} + +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, Serialize, Deserialize)] +pub struct SitesListResponse { + /// Pagination token to be used for the next list operation. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#sitesListResponse". + pub kind: Option, + /// Site collection. + pub sites: Option>, +} + +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, Deserialize)] +pub struct DimensionFilter { + /// The name of the dimension to filter. + #[serde(rename="dimensionName")] + pub dimension_name: Option, + /// The kind of resource this is, in this case dfareporting#dimensionFilter. + pub kind: Option, + /// The value of the dimension to filter. + pub value: Option, +} + +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*). +/// +/// * [get postal codes](struct.PostalCodeGetCall.html) (response) +/// * [list postal codes](struct.PostalCodeListCall.html) (none) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct PostalCode { + /// Postal code. This is equivalent to the id field. + pub code: Option, + /// 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(rename="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(rename="countryCode")] + pub country_code: Option, +} + +impl Resource for PostalCode {} +impl ResponseResult for PostalCode {} + + +/// Contains properties of a remarketing list. Remarketing enables you to create lists of users who have performed specific actions on a site, then target ads to members of those lists. This resource can be used to manage remarketing lists that are owned by your advertisers. To see all remarketing lists that are visible to your advertisers, including those that are shared to your advertiser or account, use the TargetableRemarketingLists 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 remarketing lists](struct.RemarketingListInsertCall.html) (request|response) +/// * [get remarketing lists](struct.RemarketingListGetCall.html) (response) +/// * [update remarketing lists](struct.RemarketingListUpdateCall.html) (request|response) +/// * [list remarketing lists](struct.RemarketingListListCall.html) (none) +/// * [patch remarketing lists](struct.RemarketingListPatchCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct RemarketingList { + /// Rule used to populate the remarketing list with users. + #[serde(rename="listPopulationRule")] + pub list_population_rule: Option, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#remarketingList". + pub kind: Option, + /// Subaccount ID of this remarketing list. This is a read-only, auto-generated field that is only returned in GET requests. + #[serde(rename="subaccountId")] + pub subaccount_id: Option, + /// Remarketing list description. + pub description: Option, + /// Number of users currently in the list. This is a read-only field. + #[serde(rename="listSize")] + pub list_size: Option, + /// Number of days that a user should remain in the remarketing list without an impression. + #[serde(rename="lifeSpan")] + pub life_span: Option, + /// Dimension value for the advertiser ID that owns this remarketing list. This is a required field. + #[serde(rename="advertiserId")] + pub advertiser_id: Option, + /// Product from which this remarketing list was originated. + #[serde(rename="listSource")] + pub list_source: Option, + /// Whether this remarketing list is active. + pub active: Option, + /// Dimension value for the ID of the advertiser. This is a read-only, auto-generated field. + #[serde(rename="advertiserIdDimensionValue")] + pub advertiser_id_dimension_value: Option, + /// Account ID of this remarketing list. This is a read-only, auto-generated field that is only returned in GET requests. + #[serde(rename="accountId")] + pub account_id: Option, + /// Remarketing list ID. This is a read-only, auto-generated field. + pub id: Option, + /// Name of the remarketing list. This is a required field. Must be no greater than 128 characters long. + pub name: Option, +} + +impl RequestValue for RemarketingList {} +impl Resource for RemarketingList {} +impl ResponseResult for RemarketingList {} + + +/// 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(rename="idDimensionValue")] + pub id_dimension_value: Option, + /// Name of the associated floodlight activity group. This is a read-only field. + #[serde(rename="floodlightActivityGroupName")] + pub floodlight_activity_group_name: Option, + /// Whether the image tag is enabled for this activity. + #[serde(rename="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(rename="advertiserId")] + pub advertiser_id: Option, + /// Code type used for cache busting in the generated tag. + #[serde(rename="cacheBustingType")] + pub cache_busting_type: Option, + /// Dimension value for the ID of the advertiser. This is a read-only, auto-generated field. + #[serde(rename="advertiserIdDimensionValue")] + pub advertiser_id_dimension_value: Option, + /// Floodlight activity group ID of this floodlight activity. This is a required field. + #[serde(rename="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(rename="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(rename="tagString")] + pub tag_string: Option, + /// Tag string of the associated floodlight activity group. This is a read-only field. + #[serde(rename="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(rename="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(rename="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(rename="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(rename="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(rename="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(rename="countingMethod")] + pub counting_method: Option, + /// Dynamic floodlight tags. + #[serde(rename="defaultTags")] + pub default_tags: Option>, + /// Dimension value for the ID of the floodlight configuration. This is a read-only, auto-generated field. + #[serde(rename="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(rename="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(rename="accountId")] + pub account_id: Option, + /// Whether this floodlight activity must be SSL-compliant. + #[serde(rename="sslRequired")] + pub ssl_required: Option, + /// Type of the associated floodlight activity group. This is a read-only field. + #[serde(rename="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(rename="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(rename="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(rename="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(rename="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, Serialize, Deserialize)] +pub struct AccountUserProfilesListResponse { + /// Pagination token to be used for the next list operation. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// Account user profile collection. + #[serde(rename="accountUserProfiles")] + pub account_user_profiles: Option>, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#accountUserProfilesListResponse". + pub kind: Option, +} + +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(rename="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(rename="defaultClickThroughEventTagId")] + pub default_click_through_event_tag_id: Option, + /// Original floodlight configuration before any sharing occurred. Set the floodlightConfigurationId of this advertiser to originalFloodlightConfigurationId to unshare the advertiser's current floodlight configuration. You cannot unshare an advertiser's floodlight configuration if the shared configuration has activities associated with any campaign or placement. + #[serde(rename="originalFloodlightConfigurationId")] + pub original_floodlight_configuration_id: Option, + /// Suffix added to click-through URL of ad creative associations under this advertiser. Must be less than 129 characters long. + #[serde(rename="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(rename="floodlightConfigurationId")] + pub floodlight_configuration_id: 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(rename="advertiserGroupId")] + pub advertiser_group_id: Option, + /// Dimension value for the ID of the floodlight configuration. This is a read-only, auto-generated field. + #[serde(rename="floodlightConfigurationIdDimensionValue")] + pub floodlight_configuration_id_dimension_value: Option, + /// Suspension status of this advertiser. + pub suspended: Option, + /// Dimension value for the ID of this advertiser. This is a read-only, auto-generated field. + #[serde(rename="idDimensionValue")] + pub id_dimension_value: Option, + /// Default email address used in sender field for tag emails. + #[serde(rename="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(rename="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, Serialize, Deserialize)] +pub struct PlatformTypesListResponse { + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#platformTypesListResponse". + pub kind: Option, + /// Platform type collection. + #[serde(rename="platformTypes")] + pub platform_types: Option>, +} + +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, Serialize, Deserialize)] +pub struct ChangeLogsListResponse { + /// Pagination token to be used for the next list operation. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#changeLogsListResponse". + pub kind: Option, + /// Change log collection. + #[serde(rename="changeLogs")] + pub change_logs: Option>, +} + +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, Serialize, Deserialize)] +pub struct PlacementsListResponse { + /// Pagination token to be used for the next list operation. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#placementsListResponse". + pub kind: Option, + /// Placement collection. + pub placements: Option>, +} + +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, Serialize, Deserialize)] +pub struct AdsListResponse { + /// Pagination token to be used for the next list operation. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#adsListResponse". + pub kind: Option, + /// Ad collection. + pub ads: Option>, +} + +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: Option, + /// The list of dimensions the report should include. + pub dimensions: Option>, + /// The list of names of metrics the report should include. + #[serde(rename="metricNames")] + pub metric_names: Option>, + /// The date range this report should be run for. + #[serde(rename="dateRange")] + pub date_range: Option, + /// 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(rename="dimensionFilters")] + pub dimension_filters: Option>, + /// The list of names of Reach By Frequency metrics the report should include. + #[serde(rename="reachByFrequencyMetricNames")] + pub reach_by_frequency_metric_names: Option>, + /// Custom Rich Media Events group. + #[serde(rename="customRichMediaEvents")] + pub custom_rich_media_events: Option, + /// 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(rename="enableAllDimensionCombinations")] + pub enable_all_dimension_combinations: Option, +} + +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, Serialize, Deserialize)] +pub struct FileUrls { + /// The URL for downloading the report data through a browser. + #[serde(rename="browserUrl")] + pub browser_url: Option, + /// The URL for downloading the report data through the API. + #[serde(rename="apiUrl")] + pub api_url: Option, +} + +impl NestedType for FileUrls {} +impl Part for FileUrls {} + + +/// Order document 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 order documents](struct.OrderDocumentListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct OrderDocumentsListResponse { + /// Pagination token to be used for the next list operation. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#orderDocumentsListResponse". + pub kind: Option, + /// Order document collection + #[serde(rename="orderDocuments")] + pub order_documents: Option>, +} + +impl ResponseResult for OrderDocumentsListResponse {} + + +/// 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(rename="dataType")] + pub data_type: Option, + /// 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(rename="reportName")] + pub report_name: Option, + /// Variable name in the tag. This is a required field. + #[serde(rename="variableType")] + pub variable_type: Option, +} + +impl Part for UserDefinedVariableConfiguration {} + + +/// Pricing 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 Pricing { + /// Group type of this inventory item if it represents a placement group. Is null otherwise. There are two type of placement groups: PLANNING_PLACEMENT_GROUP_TYPE_PACKAGE is a simple group of inventory items that acts as a single pricing point for a group of tags. PLANNING_PLACEMENT_GROUP_TYPE_ROADBLOCK is a group of inventory items 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 inventory items to be marked as primary. + #[serde(rename="groupType")] + pub group_type: Option, + /// Start date of this inventory item. + #[serde(rename="startDate")] + pub start_date: Option, + /// Flights of this inventory item. A flight (a.k.a. pricing period) represents the inventory item pricing information for a specific period of time. + pub flights: Option>, + /// End date of this inventory item. + #[serde(rename="endDate")] + pub end_date: Option, + /// Pricing type of this inventory item. + #[serde(rename="pricingType")] + pub pricing_type: Option, + /// Cap cost type of this inventory item. + #[serde(rename="capCostType")] + pub cap_cost_type: Option, +} + +impl Part for Pricing {} + + +/// 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(rename="viewThrough")] + pub view_through: Option, + /// Site ID of this dynamic tag. + #[serde(rename="siteId")] + pub site_id: Option, + /// Whether this tag is applicable only for click-throughs. + #[serde(rename="clickThrough")] + pub click_through: Option, + /// 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(rename="directorySiteId")] + pub directory_site_id: Option, + /// Dimension value for the ID of the site. This is a read-only, auto-generated field. + #[serde(rename="siteIdDimensionValue")] + pub site_id_dimension_value: Option, + /// Dynamic floodlight tag. + #[serde(rename="dynamicTag")] + pub dynamic_tag: Option, +} + +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. It 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: Option, + /// DART ID of the country to which this city belongs. + #[serde(rename="countryDartId")] + pub country_dart_id: Option, + /// Name of this city. + pub name: Option, + /// Country code of the country to which this city belongs. + #[serde(rename="countryCode")] + pub country_code: Option, + /// Metro region code of the metro region (DMA) to which this city belongs. + #[serde(rename="metroCode")] + pub metro_code: Option, + /// Region code of the region to which this city belongs. + #[serde(rename="regionCode")] + pub region_code: Option, + /// ID of the metro region (DMA) to which this city belongs. + #[serde(rename="metroDmaId")] + pub metro_dma_id: Option, + /// DART ID of this city. This is the ID used for targeting and generating reports. + #[serde(rename="dartId")] + pub dart_id: Option, + /// DART ID of the region to which this city belongs. + #[serde(rename="regionDartId")] + pub region_dart_id: Option, +} + +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(rename="clickThroughUrlSuffix")] + pub click_through_url_suffix: Option, + /// Whether this entity should override the inherited click-through URL suffix with its own defined value. + #[serde(rename="overrideInheritedSuffix")] + pub override_inherited_suffix: Option, +} + +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(rename="primaryPlacementId")] + pub primary_placement_id: Option, + /// Campaign ID of this placement group. This field is required on insertion. + #[serde(rename="campaignId")] + pub campaign_id: Option, + /// Dimension value for the ID of the primary placement. This is a read-only, auto-generated field. + #[serde(rename="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(rename="directorySiteIdDimensionValue")] + pub directory_site_id_dimension_value: Option, + /// Advertiser ID of this placement group. This is a required field on insertion. + #[serde(rename="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(rename="directorySiteId")] + pub directory_site_id: Option, + /// Information about the creation of this placement group. This is a read-only field. + #[serde(rename="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(rename="siteId")] + pub site_id: Option, + /// Pricing schedule of this placement group. This field is required on insertion. + #[serde(rename="pricingSchedule")] + pub pricing_schedule: Option, + /// Dimension value for the ID of the site. This is a read-only, auto-generated field. + #[serde(rename="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(rename="placementGroupType")] + pub placement_group_type: Option, + /// Dimension value for the ID of the advertiser. This is a read-only, auto-generated field. + #[serde(rename="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(rename="placementStrategyId")] + pub placement_strategy_id: Option, + /// Account ID of this placement group. This is a read-only field that can be left blank. + #[serde(rename="accountId")] + pub account_id: Option, + /// Dimension value for the ID of the campaign. This is a read-only, auto-generated field. + #[serde(rename="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(rename="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(rename="childPlacementIds")] + pub child_placement_ids: Option>, + /// Information about the most recent modification of this placement group. This is a read-only field. + #[serde(rename="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(rename="contentCategoryId")] + pub content_category_id: Option, + /// External ID for this placement. + #[serde(rename="externalId")] + pub external_id: Option, + /// Dimension value for the ID of this placement group. This is a read-only, auto-generated field. + #[serde(rename="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: Option, + /// Third-party URL type for in-stream video creatives. + #[serde(rename="thirdPartyUrlType")] + pub third_party_url_type: Option, +} + +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(rename="permissionGroupId")] + pub permission_group_id: Option, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#userRolePermission". + pub kind: Option, + /// Levels of availability for a user role permission. + pub availability: Option, + /// ID of this user role permission. + pub id: Option, + /// Name of this user role permission. + pub name: Option, +} + +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, Serialize, Deserialize)] +pub struct MetrosListResponse { + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#metrosListResponse". + pub kind: Option, + /// Metro collection. + pub metros: Option>, +} + +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 must be later than, or the same day as, 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(rename="startDate")] + pub start_date: Option, + /// Placement end date. This date must be later than, or 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(rename="endDate")] + pub end_date: Option, + /// Whether this placement is flighted. If true, pricing periods will be computed automatically. + pub flighted: Option, + /// Whether cap costs are ignored by ad serving. + #[serde(rename="disregardOverdelivery")] + pub disregard_overdelivery: Option, + /// Placement cap cost option. + #[serde(rename="capCostOption")] + pub cap_cost_option: Option, + /// Pricing periods for this placement. + #[serde(rename="pricingPeriods")] + pub pricing_periods: Option>, + /// Placement pricing type. This field is required on insertion. + #[serde(rename="pricingType")] + pub pricing_type: Option, + /// 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(rename="testingStartDate")] + pub testing_start_date: Option, + /// Floodlight activity ID associated with this placement. This field should be set when placement pricing type is set to PRICING_TYPE_CPA. + #[serde(rename="floodlightActivityId")] + pub floodlight_activity_id: Option, +} + +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, Serialize, Deserialize)] +pub struct AccountsListResponse { + /// Pagination token to be used for the next list operation. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#accountsListResponse". + pub kind: Option, + /// Account collection. + pub accounts: Option>, +} + +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*). +/// +/// * [get operating systems](struct.OperatingSystemGetCall.html) (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(rename="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 {} +impl ResponseResult 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: Option, + /// List of activity filters. The dimension values need to be all either of type "dfa:activity" or "dfa:activityGroup". + pub filters: Option>, + /// List of names of floodlight activity metrics. + #[serde(rename="metricNames")] + pub metric_names: Option>, +} + +impl Part for Activities {} + + +/// A group clause made up of list population terms representing constraints joined by ORs. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ListPopulationClause { + /// Terms of this list population clause. Each clause is made up of list population terms representing constraints and are joined by ORs. + pub terms: Option>, +} + +impl Part for ListPopulationClause {} + + +/// Flight +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Flight { + /// Rate or cost of this flight. + #[serde(rename="rateOrCost")] + pub rate_or_cost: Option, + /// Inventory item flight start date. + #[serde(rename="startDate")] + pub start_date: Option, + /// Units of this flight. + pub units: Option, + /// Inventory item flight end date. + #[serde(rename="endDate")] + pub end_date: Option, +} + +impl Part for Flight {} + + +/// 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: Option, + /// The name of the dimension. + pub name: Option, + /// An optional sort order for the dimension column. + #[serde(rename="sortOrder")] + pub sort_order: Option, +} + +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, Serialize, Deserialize)] +pub struct PlacementStrategiesListResponse { + /// Pagination token to be used for the next list operation. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#placementStrategiesListResponse". + pub kind: Option, + /// Placement strategy collection. + #[serde(rename="placementStrategies")] + pub placement_strategies: Option>, +} + +impl ResponseResult for PlacementStrategiesListResponse {} + + +/// Third Party Authentication Token +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ThirdPartyAuthenticationToken { + /// Name of the third-party authentication token. + pub name: Option, + /// Value of the third-party authentication token. This is a read-only, auto-generated field. + pub value: Option, +} + +impl Part for ThirdPartyAuthenticationToken {} + + +/// 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(rename="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(rename="windowHeight")] + pub window_height: Option, + /// Distance from the top of the browser. Applicable when positionOption is DISTANCE_FROM_TOP_LEFT_CORNER. + pub top: Option, + /// Width of the window. + #[serde(rename="windowWidth")] + pub window_width: Option, + /// Position in the browser where the window will open. + #[serde(rename="positionOption")] + pub position_option: Option, + /// Distance from the left of the browser.Applicable when positionOption is DISTANCE_FROM_TOP_LEFT_CORNER. + pub left: Option, +} + +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(rename="optimizationActivitys")] + pub optimization_activitys: Option>, + /// 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: Option, + /// Name of this creative optimization config. This is a required field and must be less than 129 characters long. + pub name: Option, + /// Optimization model for this configuration. + #[serde(rename="optimizationModel")] + pub optimization_model: Option, +} + +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, Serialize, Deserialize)] +pub struct CreativeGroupsListResponse { + /// Pagination token to be used for the next list operation. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// Creative group collection. + #[serde(rename="creativeGroups")] + pub creative_groups: Option>, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#creativeGroupsListResponse". + pub kind: Option, +} + +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: Option, + /// Offset distance from left side of an asset or a window. + pub left: Option, +} + +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(rename="customHtml")] + pub custom_html: Option, + /// Type of browser window for which the backup image of the flash creative can be displayed. + #[serde(rename="targetWindowOption")] + pub target_window_option: Option, +} + +impl Part for TargetWindow {} + + +/// 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 { + /// First name of this site contact. + #[serde(rename="firstName")] + pub first_name: Option, + /// Title or designation of this site contact. + pub title: Option, + /// Last name of this site contact. + #[serde(rename="lastName")] + pub last_name: Option, + /// Site contact type. + #[serde(rename="contactType")] + pub contact_type: Option, + /// ID of this site contact. This is a read-only, auto-generated field. + pub id: Option, + /// Primary phone number of this site contact. + pub phone: Option, + /// Address of this site contact. + pub address: Option, + /// Email address of this site contact. This is a required field. + pub email: Option, +} + +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(rename="creativeAssignments")] + pub creative_assignments: Option>, + /// Strategy for calculating weights. Used with CREATIVE_ROTATION_TYPE_RANDOM. + #[serde(rename="weightCalculationStrategy")] + pub weight_calculation_strategy: Option, + /// 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(rename="creativeOptimizationConfigurationId")] + pub creative_optimization_configuration_id: Option, + /// Type of creative rotation. Can be used to specify whether to use sequential or random rotation. + #[serde(rename="type")] + pub type_: Option, +} + +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(rename="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(rename="countryCode")] + pub country_code: Option, + /// Metro code of this metro region. This is equivalent to dma_id. + #[serde(rename="metroCode")] + pub metro_code: Option, + /// DART ID of this metro region. + #[serde(rename="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(rename="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(rename="dartId")] + pub dart_id: Option, + /// Whether ad serving supports secure servers in this country. + #[serde(rename="sslEnabled")] + pub ssl_enabled: Option, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#country". + pub kind: Option, + /// Country code. + #[serde(rename="countryCode")] + pub country_code: Option, + /// Name of this country. + pub name: Option, +} + +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, Serialize, Deserialize)] +pub struct PostalCodesListResponse { + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#postalCodesListResponse". + pub kind: Option, + /// Postal code collection. + #[serde(rename="postalCodes")] + pub postal_codes: Option>, +} + +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(rename="includeClickThroughUrls")] + pub include_click_through_urls: Option, + /// Whether click-tracking string should be included in the tags. + #[serde(rename="includeClickTracking")] + pub include_click_tracking: Option, + /// 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(rename="additionalKeyValues")] + pub additional_key_values: Option, + /// 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(rename="keywordOption")] + pub keyword_option: Option, +} + +impl Part for TagSetting {} + + +/// 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(rename="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(rename="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(rename="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(rename="accountId")] + pub account_id: Option, +} + +impl RequestValue for CreativeField {} +impl Resource for CreativeField {} +impl ResponseResult for CreativeField {} + + +/// 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, Serialize, Deserialize)] +pub struct CreativeFieldValuesListResponse { + /// Pagination token to be used for the next list operation. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#creativeFieldValuesListResponse". + pub kind: Option, + /// Creative field value collection. + #[serde(rename="creativeFieldValues")] + pub creative_field_values: Option>, +} + +impl ResponseResult for CreativeFieldValuesListResponse {} + + +/// 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(rename="includeUnattributedIPConversions")] + pub include_unattributed_ip_conversions: Option, + /// 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(rename="includeUnattributedCookieConversions")] + pub include_unattributed_cookie_conversions: Option, + /// Include conversions that have no cookie, but do have an exposure path. + #[serde(rename="includeAttributedIPConversions")] + pub include_attributed_ip_conversions: Option, +} + +impl NestedType for ReportFloodlightCriteriaReportProperties {} +impl Part for ReportFloodlightCriteriaReportProperties {} + + +/// 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, Serialize, Deserialize)] +pub struct DirectorySiteContact { + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#directorySiteContact". + pub kind: Option, + /// First name of this directory site contact. + #[serde(rename="firstName")] + pub first_name: Option, + /// Title or designation of this directory site contact. + pub title: Option, + /// Last name of this directory site contact. + #[serde(rename="lastName")] + pub last_name: Option, + /// ID of this directory site contact. This is a read-only, auto-generated field. + pub id: Option, + /// Phone number of this directory site contact. + pub phone: Option, + /// Directory site contact role. + pub role: Option, + /// Address of this directory site contact. + pub address: Option, + /// Directory site contact type. + #[serde(rename="type")] + pub type_: Option, + /// Email address of this directory site contact. + pub email: Option, +} + +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(rename="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(rename="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, Serialize, Deserialize)] +pub struct ContentCategoriesListResponse { + /// Pagination token to be used for the next list operation. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#contentCategoriesListResponse". + pub kind: Option, + /// Content category collection. + #[serde(rename="contentCategories")] + pub content_categories: Option>, +} + +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, Serialize, Deserialize)] +pub struct FloodlightConfigurationsListResponse { + /// Floodlight configuration collection. + #[serde(rename="floodlightConfigurations")] + pub floodlight_configurations: Option>, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#floodlightConfigurationsListResponse". + pub kind: Option, +} + +impl ResponseResult for FloodlightConfigurationsListResponse {} + + +/// Describes properties of a DoubleClick Planning order. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where 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 orders](struct.OrderListCall.html) (none) +/// * [get orders](struct.OrderGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Order { + /// Terms and conditions of this order. + #[serde(rename="termsAndConditions")] + pub terms_and_conditions: Option, + /// Name of the buyer organization. + #[serde(rename="buyerOrganizationName")] + pub buyer_organization_name: Option, + /// Advertiser ID of this order. + #[serde(rename="advertiserId")] + pub advertiser_id: Option, + /// Site IDs this order is associated with. + #[serde(rename="siteId")] + pub site_id: Option>, + /// Buyer invoice ID associated with this order. + #[serde(rename="buyerInvoiceId")] + pub buyer_invoice_id: Option, + /// ID of the terms and conditions template used in this order. + #[serde(rename="planningTermId")] + pub planning_term_id: Option, + /// ID of this order. This is a read-only, auto-generated field. + pub id: Option, + /// Account ID of this order. + #[serde(rename="accountId")] + pub account_id: Option, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#order". + pub kind: Option, + /// Subaccount ID of this order. + #[serde(rename="subaccountId")] + pub subaccount_id: Option, + /// Name of this order. + pub name: Option, + /// Contacts for this order. + pub contacts: Option>, + /// Information about the most recent modification of this order. + #[serde(rename="lastModifiedInfo")] + pub last_modified_info: Option, + /// Notes of this order. + pub notes: Option, + /// Name of the seller organization. + #[serde(rename="sellerOrganizationName")] + pub seller_organization_name: Option, + /// Comments in this order. + pub comments: Option, + /// IDs for users that have to approve documents created for this order. + #[serde(rename="approverUserProfileIds")] + pub approver_user_profile_ids: Option>, + /// Seller order ID associated with this order. + #[serde(rename="sellerOrderId")] + pub seller_order_id: Option, + /// Project ID of this order. + #[serde(rename="projectId")] + pub project_id: Option, + /// Free-form site names this order is associated with. + #[serde(rename="siteNames")] + pub site_names: Option>, +} + +impl Resource for Order {} +impl ResponseResult for Order {} + + +/// 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(rename="showStatusBar")] + pub show_status_bar: Option, + /// Whether to display the browser scroll bar. + #[serde(rename="showScrollBar")] + pub show_scroll_bar: Option, + /// Whether to display the browser address bar. + #[serde(rename="showAddressBar")] + pub show_address_bar: Option, + /// Whether to display the browser menu bar. + #[serde(rename="showMenuBar")] + pub show_menu_bar: Option, + /// Title of popup window. + pub title: Option, + /// Upper-left corner coordinates of the popup window. Applicable if positionType is COORDINATES. + pub offset: Option, + /// Popup window position either centered or at specific coordinate. + #[serde(rename="positionType")] + pub position_type: Option, + /// Whether to display the browser tool bar. + #[serde(rename="showToolBar")] + pub show_tool_bar: Option, + /// 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: Option, +} + +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, Serialize, Deserialize)] +pub struct AccountPermission { + /// Permission group of this account permission. + #[serde(rename="permissionGroupId")] + pub permission_group_id: Option, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#accountPermission". + pub kind: Option, + /// Name of this account permission. + pub name: Option, + /// Administrative level required to enable this account permission. + pub level: Option, + /// Account profiles associated with this account permission. + /// + /// Possible values are: + /// - "ACCOUNT_PROFILE_BASIC" + /// - "ACCOUNT_PROFILE_STANDARD" + #[serde(rename="accountProfiles")] + pub account_profiles: Option>, + /// ID of this account permission. + pub id: Option, +} + +impl Resource for AccountPermission {} +impl ResponseResult for AccountPermission {} + + +/// Contains properties of a DoubleClick Planning project. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where 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) +/// * [list projects](struct.ProjectListCall.html) (none) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Project { + /// Start date of the project. + #[serde(rename="startDate")] + pub start_date: Option, + /// CPM that the advertiser is targeting. + #[serde(rename="targetCpmNanos")] + pub target_cpm_nanos: Option, + /// End date of the project. + #[serde(rename="endDate")] + pub end_date: Option, + /// Client billing code of this project. + #[serde(rename="clientBillingCode")] + pub client_billing_code: Option, + /// Overview of this project. + pub overview: Option, + /// Number of clicks that the advertiser is targeting. + #[serde(rename="targetClicks")] + pub target_clicks: Option, + /// CPA that the advertiser is targeting. + #[serde(rename="targetCpaNanos")] + pub target_cpa_nanos: Option, + /// Advertiser ID of this project. + #[serde(rename="advertiserId")] + pub advertiser_id: Option, + /// Number of impressions that the advertiser is targeting. + #[serde(rename="targetImpressions")] + pub target_impressions: Option, + /// Subaccount ID of this project. + #[serde(rename="subaccountId")] + pub subaccount_id: Option, + /// Audience gender of this project. + #[serde(rename="audienceGender")] + pub audience_gender: Option, + /// ID of this project. This is a read-only, auto-generated field. + pub id: Option, + /// Account ID of this project. + #[serde(rename="accountId")] + pub account_id: Option, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#project". + pub kind: Option, + /// CPC that the advertiser is targeting. + #[serde(rename="targetCpcNanos")] + pub target_cpc_nanos: Option, + /// Name of this project. + pub name: Option, + /// Information about the most recent modification of this project. + #[serde(rename="lastModifiedInfo")] + pub last_modified_info: Option, + /// Budget of this project in the currency specified by the current account. The value stored in this field represents only the non-fractional amount. For example, for USD, the smallest value that can be represented by this field is 1 US dollar. + pub budget: Option, + /// Audience age group of this project. + #[serde(rename="audienceAgeGroup")] + pub audience_age_group: Option, + /// Number of conversions that the advertiser is targeting. + #[serde(rename="targetConversions")] + pub target_conversions: Option, + /// Name of the project client. + #[serde(rename="clientName")] + pub client_name: Option, +} + +impl Resource for Project {} +impl ResponseResult for Project {} + + +/// 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(rename="clickThroughUrlSuffixProperties")] + pub click_through_url_suffix_properties: Option, + /// Campaign ID of this ad. This is a required field on insertion. + #[serde(rename="campaignId")] + pub campaign_id: Option, + /// Advertiser ID of this ad. This is a required field on insertion. + #[serde(rename="advertiserId")] + pub advertiser_id: Option, + /// Geographical targeting information for this ad.Applicable when type is AD_SERVING_STANDARD_AD. + #[serde(rename="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(rename="deliverySchedule")] + pub delivery_schedule: Option, + /// Dimension value for the ID of the advertiser. This is a read-only, auto-generated field. + #[serde(rename="advertiserIdDimensionValue")] + pub advertiser_id_dimension_value: Option, + /// Event tag overrides for this ad. + #[serde(rename="eventTagOverrides")] + pub event_tag_overrides: Option>, + /// ID of this ad. This is a read-only, auto-generated field. + pub id: 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(rename="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(rename="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(rename="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(rename="creativeGroupAssignments")] + pub creative_group_assignments: Option>, + /// Applicable when type is AD_SERVING_STANDARD_AD. Remarketing list targeting expression for this ad. + #[serde(rename="remarketingListExpression")] + pub remarketing_list_expression: Option, + /// Dimension value for the ID of this ad. This is a read-only, auto-generated field. + #[serde(rename="idDimensionValue")] + pub id_dimension_value: Option, + /// Account ID of this ad. This is a read-only field that can be left blank. + #[serde(rename="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(rename="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(rename="sslRequired")] + pub ssl_required: Option, + /// Audience segment ID that is being targeted for this ad. Applicable when type is AD_SERVING_STANDARD_AD. + #[serde(rename="audienceSegmentId")] + pub audience_segment_id: Option, + /// Key-value targeting information for this ad. Applicable when type is AD_SERVING_STANDARD_AD. + #[serde(rename="keyValueTargetingExpression")] + pub key_value_targeting_expression: Option, + /// Dimension value for the ID of the campaign. This is a read-only, auto-generated field. + #[serde(rename="campaignIdDimensionValue")] + pub campaign_id_dimension_value: Option, + /// Default click-through event tag properties for this ad. + #[serde(rename="defaultClickThroughEventTagProperties")] + pub default_click_through_event_tag_properties: Option, + /// Information about the creation of this ad.This is a read-only field. + #[serde(rename="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(rename="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(rename="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(rename="dayPartTargeting")] + pub day_part_targeting: Option, + /// Information about the most recent modification of this ad. This is a read-only field. + #[serde(rename="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(rename="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(rename="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(rename="dynamicClickTracker")] + pub dynamic_click_tracker: Option, + /// Placement assignments for this ad. + #[serde(rename="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: Option, + /// Pricing period start date. This date must be later than, or the same day as, 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(rename="startDate")] + pub start_date: Option, + /// Rate or cost of this pricing period. + #[serde(rename="rateOrCostNanos")] + pub rate_or_cost_nanos: Option, + /// Pricing period end date. This date must be later than, or 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(rename="endDate")] + pub end_date: Option, + /// Comments for this pricing period. + #[serde(rename="pricingComment")] + pub pricing_comment: Option, +} + +impl Part for PricingSchedulePricingPeriod {} + + +/// 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(rename="siteIds")] + pub site_ids: Option>, + /// Campaign ID of this event tag. This field or the advertiserId field is required on insertion. + #[serde(rename="campaignId")] + pub campaign_id: Option, + /// Dimension value for the ID of the campaign. This is a read-only, auto-generated field. + #[serde(rename="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(rename="enabledByDefault")] + pub enabled_by_default: Option, + /// Advertiser ID of this event tag. This field or the campaignId field is required on insertion. + #[serde(rename="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(rename="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(rename="type")] + pub type_: Option, + /// Dimension value for the ID of the advertiser. This is a read-only, auto-generated field. + #[serde(rename="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(rename="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(rename="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. This is a read-only field. + #[serde(rename="sslCompliant")] + pub ssl_compliant: Option, + /// Whether to remove this event tag from ads that are trafficked through DoubleClick Bid Manager to Ad Exchange. This may be useful if the event tag uses a pixel that is unapproved for Ad Exchange bids on one or more networks, such as the Google Display Network. + #[serde(rename="excludeFromAdxRequests")] + pub exclude_from_adx_requests: 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(rename="urlEscapeLevels")] + pub url_escape_levels: Option, +} + +impl RequestValue for EventTag {} +impl Resource for EventTag {} +impl ResponseResult for EventTag {} + + +/// 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: Option, + /// Dimension value for the ID of the placement. This is a read-only, auto-generated field. + #[serde(rename="placementIdDimensionValue")] + pub placement_id_dimension_value: Option, + /// ID of the placement to be assigned. This is a required field. + #[serde(rename="placementId")] + pub placement_id: Option, + /// 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(rename="sslRequired")] + pub ssl_required: Option, +} + +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, Serialize, Deserialize)] +pub struct ReachReportCompatibleFields { + /// Metrics which are compatible to be selected in the "metricNames" section of the report. + pub metrics: Option>, + /// The kind of resource this is, in this case dfareporting#reachReportCompatibleFields. + pub kind: Option, + /// Dimensions which are compatible to be selected in the "dimensions" section of the report. + pub dimensions: Option>, + /// Metrics which are compatible to be selected in the "reachByFrequencyMetricNames" section of the report. + #[serde(rename="reachByFrequencyMetrics")] + pub reach_by_frequency_metrics: Option>, + /// Dimensions which are compatible to be selected in the "dimensionFilters" section of the report. + #[serde(rename="dimensionFilters")] + pub dimension_filters: Option>, + /// Metrics which are compatible to be selected as activity metrics to pivot on in the "activities" section of the report. + #[serde(rename="pivotedActivityMetrics")] + pub pivoted_activity_metrics: Option>, +} + +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(rename="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(rename="directorySiteIdDimensionValue")] + pub directory_site_id_dimension_value: Option, + /// Site-wide settings. + #[serde(rename="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(rename="directorySiteId")] + pub directory_site_id: Option, + /// Site contacts. + #[serde(rename="siteContacts")] + pub site_contacts: Option>, + /// Key name of this site. This is a read-only, auto-generated field. + #[serde(rename="keyName")] + pub key_name: Option, + /// Dimension value for the ID of this site. This is a read-only, auto-generated field. + #[serde(rename="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(rename="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, Serialize, Deserialize)] +pub struct DfpSettings { + /// DFP network name for this directory site. + pub dfp_network_name: Option, + /// DFP network code for this directory site. + pub dfp_network_code: Option, + /// Whether this directory site is available only via DoubleClick Publisher Portal. + #[serde(rename="publisherPortalOnly")] + pub publisher_portal_only: Option, + /// Whether this directory site accepts programmatic placements. + #[serde(rename="programmaticPlacementAccepted")] + pub programmatic_placement_accepted: Option, + /// Whether this directory site accepts publisher-paid tags. + #[serde(rename="pubPaidPlacementAccepted")] + pub pub_paid_placement_accepted: Option, +} + +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, Serialize, Deserialize)] +pub struct ConnectionTypesListResponse { + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#connectionTypesListResponse". + pub kind: Option, + /// Collection of connection types such as broadband and mobile. + #[serde(rename="connectionTypes")] + pub connection_types: Option>, +} + +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(rename="userDefinedVariableConfigurations")] + pub user_defined_variable_configurations: Option>, + /// List of third-party authentication tokens enabled for this configuration. + #[serde(rename="thirdPartyAuthenticationTokens")] + pub third_party_authentication_tokens: 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(rename="advertiserId")] + pub advertiser_id: Option, + /// Configuration settings for dynamic and image floodlight tags. + #[serde(rename="tagSettings")] + pub tag_settings: Option, + /// Whether in-app attribution tracking is enabled. + #[serde(rename="inAppAttributionTrackingEnabled")] + pub in_app_attribution_tracking_enabled: Option, + /// Dimension value for the ID of the advertiser. This is a read-only, auto-generated field. + #[serde(rename="advertiserIdDimensionValue")] + pub advertiser_id_dimension_value: Option, + /// Subaccount ID of this floodlight configuration. This is a read-only field that can be left blank. + #[serde(rename="subaccountId")] + pub subaccount_id: 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(rename="accountId")] + pub account_id: Option, + /// Types of attribution options for natural search conversions. + #[serde(rename="naturalSearchConversionAttributionOption")] + pub natural_search_conversion_attribution_option: Option, + /// Settings for DCM Omniture integration. + #[serde(rename="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(rename="exposureToConversionEnabled")] + pub exposure_to_conversion_enabled: Option, + /// Lookback window settings for this floodlight configuration. + #[serde(rename="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(rename="firstDayOfWeek")] + pub first_day_of_week: Option, + /// List of standard variables enabled for this configuration. + /// + /// Acceptable values are: + /// - "ORD" + /// - "NUM" + #[serde(rename="standardVariableTypes")] + pub standard_variable_types: Option>, + /// Whether advertiser data is shared with Google Analytics. + #[serde(rename="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(rename="idDimensionValue")] + pub id_dimension_value: Option, + /// Whether floodlight activities owned by this configuration are required to be SSL-compliant. + #[serde(rename="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(rename="startDate")] + pub start_date: Option, + /// The kind of resource this is, in this case dfareporting#dateRange. + pub kind: Option, + /// The end date of the date range, inclusive. A string of the format: "yyyy-MM-dd". + #[serde(rename="endDate")] + pub end_date: Option, + /// The date range relative to the date of when the report is run. + #[serde(rename="relativeDateRange")] + pub relative_date_range: Option, +} + +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, Serialize, Deserialize)] +pub struct AccountPermissionGroupsListResponse { + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#accountPermissionGroupsListResponse". + pub kind: Option, + /// Account permission group collection. + #[serde(rename="accountPermissionGroups")] + pub account_permission_groups: Option>, +} + +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, Serialize, Deserialize)] +pub struct SizesListResponse { + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#sizesListResponse". + pub kind: Option, + /// Size collection. + pub sizes: Option>, +} + +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, Serialize, Deserialize)] +pub struct UserRolesListResponse { + /// Pagination token to be used for the next list operation. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// Identifies what kind of resource this is. Value: the fixed string "dfareporting#userRolesListResponse". + pub kind: Option, + /// User role collection. + #[serde(rename="userRoles")] + pub user_roles: Option>, +} + +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_dfareporting2d2 as dfareporting2d2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, A> MethodsBuilder for UserRolePermissionGroupMethods<'a, C, A> {} + +impl<'a, C, A> UserRolePermissionGroupMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Gets one user role permission group by ID. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + /// * `id` - User role permission group ID. + pub fn get(&self, profile_id: &str, id: &str) -> UserRolePermissionGroupGetCall<'a, C, 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. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + pub fn list(&self, profile_id: &str) -> UserRolePermissionGroupListCall<'a, C, 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_dfareporting2d2 as dfareporting2d2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2d2::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.platform_types(); +/// # } +/// ``` +pub struct PlatformTypeMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, A> MethodsBuilder for PlatformTypeMethods<'a, C, A> {} + +impl<'a, C, A> PlatformTypeMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Gets one platform type by ID. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + /// * `id` - Platform type ID. + pub fn get(&self, profile_id: &str, id: &str) -> PlatformTypeGetCall<'a, C, A> { + PlatformTypeGetCall { + 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 platform types. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + pub fn list(&self, profile_id: &str) -> PlatformTypeListCall<'a, C, 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 *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_dfareporting2d2 as dfareporting2d2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, A> MethodsBuilder for CreativeFieldValueMethods<'a, C, A> {} + +impl<'a, C, A> CreativeFieldValueMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing creative field value. This method supports patch semantics. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + /// * `creativeFieldId` - Creative field ID for this creative field value. + /// * `id` - Creative Field Value ID + pub fn patch(&self, request: CreativeFieldValue, profile_id: &str, creative_field_id: &str, id: &str) -> CreativeFieldValuePatchCall<'a, C, A> { + CreativeFieldValuePatchCall { + hub: self.hub, + _request: request, + _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: + /// + /// Gets one creative field value by ID. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + /// * `creativeFieldId` - Creative field ID for this creative field value. + /// * `id` - Creative Field Value ID + pub fn get(&self, profile_id: &str, creative_field_id: &str, id: &str) -> CreativeFieldValueGetCall<'a, C, 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: + /// + /// Deletes an existing creative field value. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + /// * `creativeFieldId` - Creative field ID for this creative field value. + /// * `id` - Creative Field Value ID + pub fn delete(&self, profile_id: &str, creative_field_id: &str, id: &str) -> CreativeFieldValueDeleteCall<'a, C, 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. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + /// * `creativeFieldId` - Creative field ID for this creative field value. + pub fn insert(&self, request: CreativeFieldValue, profile_id: &str, creative_field_id: &str) -> CreativeFieldValueInsertCall<'a, C, A> { + CreativeFieldValueInsertCall { + hub: self.hub, + _request: request, + _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. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + /// * `creativeFieldId` - Creative field ID for this creative field value. + pub fn update(&self, request: CreativeFieldValue, profile_id: &str, creative_field_id: &str) -> CreativeFieldValueUpdateCall<'a, C, A> { + CreativeFieldValueUpdateCall { + hub: self.hub, + _request: request, + _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: + /// + /// Retrieves a list of creative field values, possibly filtered. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + /// * `creativeFieldId` - Creative field ID for this creative field value. + pub fn list(&self, profile_id: &str, creative_field_id: &str) -> CreativeFieldValueListCall<'a, C, 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 *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_dfareporting2d2 as dfareporting2d2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, A> MethodsBuilder for CreativeFieldMethods<'a, C, A> {} + +impl<'a, C, A> CreativeFieldMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing creative field. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + pub fn update(&self, request: CreativeField, profile_id: &str) -> CreativeFieldUpdateCall<'a, C, A> { + CreativeFieldUpdateCall { + hub: self.hub, + _request: request, + _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. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + pub fn list(&self, profile_id: &str) -> CreativeFieldListCall<'a, C, 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. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + /// * `id` - Creative Field ID + pub fn delete(&self, profile_id: &str, id: &str) -> CreativeFieldDeleteCall<'a, C, 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. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + /// * `id` - Creative Field ID + pub fn get(&self, profile_id: &str, id: &str) -> CreativeFieldGetCall<'a, C, 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. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + pub fn insert(&self, request: CreativeField, profile_id: &str) -> CreativeFieldInsertCall<'a, C, A> { + CreativeFieldInsertCall { + hub: self.hub, + _request: request, + _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. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + /// * `id` - Creative Field ID + pub fn patch(&self, request: CreativeField, profile_id: &str, id: &str) -> CreativeFieldPatchCall<'a, C, A> { + CreativeFieldPatchCall { + hub: self.hub, + _request: request, + _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_dfareporting2d2 as dfareporting2d2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, A> MethodsBuilder for UserRoleMethods<'a, C, A> {} + +impl<'a, C, A> UserRoleMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Inserts a new user role. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + pub fn insert(&self, request: UserRole, profile_id: &str) -> UserRoleInsertCall<'a, C, A> { + UserRoleInsertCall { + hub: self.hub, + _request: request, + _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. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + /// * `id` - User role ID. + pub fn get(&self, profile_id: &str, id: &str) -> UserRoleGetCall<'a, C, 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. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + pub fn update(&self, request: UserRole, profile_id: &str) -> UserRoleUpdateCall<'a, C, A> { + UserRoleUpdateCall { + hub: self.hub, + _request: request, + _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. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + /// * `id` - User role ID. + pub fn delete(&self, profile_id: &str, id: &str) -> UserRoleDeleteCall<'a, C, 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. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + /// * `id` - User role ID. + pub fn patch(&self, request: UserRole, profile_id: &str, id: &str) -> UserRolePatchCall<'a, C, A> { + UserRolePatchCall { + hub: self.hub, + _request: request, + _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. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + pub fn list(&self, profile_id: &str) -> UserRoleListCall<'a, C, 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_dfareporting2d2 as dfareporting2d2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2d2::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.operating_system_versions(); +/// # } +/// ``` +pub struct OperatingSystemVersionMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, A> MethodsBuilder for OperatingSystemVersionMethods<'a, C, A> {} + +impl<'a, C, A> OperatingSystemVersionMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Gets one operating system version by ID. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + /// * `id` - Operating system version ID. + pub fn get(&self, profile_id: &str, id: &str) -> OperatingSystemVersionGetCall<'a, C, A> { + OperatingSystemVersionGetCall { + 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 operating system versions. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + pub fn list(&self, profile_id: &str) -> OperatingSystemVersionListCall<'a, C, 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_dfareporting2d2 as dfareporting2d2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, A> MethodsBuilder for LandingPageMethods<'a, C, A> {} + +impl<'a, C, A> LandingPageMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Gets one campaign landing page by ID. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + /// * `campaignId` - Landing page campaign ID. + /// * `id` - Landing page ID. + pub fn get(&self, profile_id: &str, campaign_id: &str, id: &str) -> LandingPageGetCall<'a, C, 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. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + /// * `campaignId` - Landing page campaign ID. + pub fn update(&self, request: LandingPage, profile_id: &str, campaign_id: &str) -> LandingPageUpdateCall<'a, C, A> { + LandingPageUpdateCall { + hub: self.hub, + _request: request, + _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. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + /// * `campaignId` - Landing page campaign ID. + pub fn list(&self, profile_id: &str, campaign_id: &str) -> LandingPageListCall<'a, C, 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. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + /// * `campaignId` - Landing page campaign ID. + pub fn insert(&self, request: LandingPage, profile_id: &str, campaign_id: &str) -> LandingPageInsertCall<'a, C, A> { + LandingPageInsertCall { + hub: self.hub, + _request: request, + _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. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + /// * `campaignId` - Landing page campaign ID. + /// * `id` - Landing page ID. + pub fn patch(&self, request: LandingPage, profile_id: &str, campaign_id: &str, id: &str) -> LandingPagePatchCall<'a, C, A> { + LandingPagePatchCall { + hub: self.hub, + _request: request, + _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. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + /// * `campaignId` - Landing page campaign ID. + /// * `id` - Landing page ID. + pub fn delete(&self, profile_id: &str, campaign_id: &str, id: &str) -> LandingPageDeleteCall<'a, C, 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 *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_dfareporting2d2 as dfareporting2d2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, A> MethodsBuilder for CreativeAssetMethods<'a, C, A> {} + +impl<'a, C, A> CreativeAssetMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Inserts a new creative asset. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + /// * `advertiserId` - Advertiser ID of this creative. This is a required field. + pub fn insert(&self, request: CreativeAssetMetadata, profile_id: &str, advertiser_id: &str) -> CreativeAssetInsertCall<'a, C, A> { + CreativeAssetInsertCall { + hub: self.hub, + _request: request, + _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 *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_dfareporting2d2 as dfareporting2d2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, A> MethodsBuilder for CampaignCreativeAssociationMethods<'a, C, A> {} + +impl<'a, C, A> CampaignCreativeAssociationMethods<'a, C, 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. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + /// * `campaignId` - Campaign ID in this association. + pub fn insert(&self, request: CampaignCreativeAssociation, profile_id: &str, campaign_id: &str) -> CampaignCreativeAssociationInsertCall<'a, C, A> { + CampaignCreativeAssociationInsertCall { + hub: self.hub, + _request: request, + _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. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + /// * `campaignId` - Campaign ID in this association. + pub fn list(&self, profile_id: &str, campaign_id: &str) -> CampaignCreativeAssociationListCall<'a, C, 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_dfareporting2d2 as dfareporting2d2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, A> MethodsBuilder for ChangeLogMethods<'a, C, A> {} + +impl<'a, C, A> ChangeLogMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a list of change logs. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + pub fn list(&self, profile_id: &str) -> ChangeLogListCall<'a, C, 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. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + /// * `id` - Change log ID. + pub fn get(&self, profile_id: &str, id: &str) -> ChangeLogGetCall<'a, C, 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 *remarketingListShare* 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_dfareporting2d2 as dfareporting2d2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2d2::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(...)`, `patch(...)` and `update(...)` +/// // to build up your call. +/// let rb = hub.remarketing_list_shares(); +/// # } +/// ``` +pub struct RemarketingListShareMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, A> MethodsBuilder for RemarketingListShareMethods<'a, C, A> {} + +impl<'a, C, A> RemarketingListShareMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Gets one remarketing list share by remarketing list ID. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + /// * `remarketingListId` - Remarketing list ID. + pub fn get(&self, profile_id: &str, remarketing_list_id: &str) -> RemarketingListShareGetCall<'a, C, A> { + RemarketingListShareGetCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _remarketing_list_id: remarketing_list_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 remarketing list share. This method supports patch semantics. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + /// * `remarketingListId` - Remarketing list ID. + pub fn patch(&self, request: RemarketingListShare, profile_id: &str, remarketing_list_id: &str) -> RemarketingListSharePatchCall<'a, C, A> { + RemarketingListSharePatchCall { + hub: self.hub, + _request: request, + _profile_id: profile_id.to_string(), + _remarketing_list_id: remarketing_list_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 remarketing list share. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + pub fn update(&self, request: RemarketingListShare, profile_id: &str) -> RemarketingListShareUpdateCall<'a, C, A> { + RemarketingListShareUpdateCall { + hub: self.hub, + _request: request, + _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 *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_dfareporting2d2 as dfareporting2d2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, A> MethodsBuilder for ReportMethods<'a, C, A> {} + +impl<'a, C, A> ReportMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Runs a report. + /// + /// # Arguments + /// + /// * `profileId` - The DFA profile ID. + /// * `reportId` - The ID of the report. + pub fn run(&self, profile_id: &str, report_id: &str) -> ReportRunCall<'a, C, 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. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - The DFA user profile ID. + /// * `reportId` - The ID of the report. + pub fn patch(&self, request: Report, profile_id: &str, report_id: &str) -> ReportPatchCall<'a, C, A> { + ReportPatchCall { + hub: self.hub, + _request: request, + _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. + /// + /// # Arguments + /// + /// * `profileId` - The DFA profile ID. + /// * `reportId` - The ID of the parent report. + pub fn files_list(&self, profile_id: &str, report_id: &str) -> ReportFileListCall<'a, C, 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. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - The DFA user profile ID. + pub fn insert(&self, request: Report, profile_id: &str) -> ReportInsertCall<'a, C, A> { + ReportInsertCall { + hub: self.hub, + _request: request, + _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 a report. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - The DFA user profile ID. + /// * `reportId` - The ID of the report. + pub fn update(&self, request: Report, profile_id: &str, report_id: &str) -> ReportUpdateCall<'a, C, A> { + ReportUpdateCall { + hub: self.hub, + _request: request, + _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: + /// + /// 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. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - The DFA user profile ID. + pub fn compatible_fields_query(&self, request: Report, profile_id: &str) -> ReportCompatibleFieldQueryCall<'a, C, A> { + ReportCompatibleFieldQueryCall { + hub: self.hub, + _request: request, + _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. + /// + /// # Arguments + /// + /// * `profileId` - The DFA user profile ID. + /// * `reportId` - The ID of the report. + pub fn get(&self, profile_id: &str, report_id: &str) -> ReportGetCall<'a, C, 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. + /// + /// # Arguments + /// + /// * `profileId` - The DFA profile ID. + /// * `reportId` - The ID of the report. + /// * `fileId` - The ID of the report file. + pub fn files_get(&self, profile_id: &str, report_id: &str, file_id: &str) -> ReportFileGetCall<'a, C, 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. + /// + /// # Arguments + /// + /// * `profileId` - The DFA user profile ID. + /// * `reportId` - The ID of the report. + pub fn delete(&self, profile_id: &str, report_id: &str) -> ReportDeleteCall<'a, C, 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. + /// + /// # Arguments + /// + /// * `profileId` - The DFA user profile ID. + pub fn list(&self, profile_id: &str) -> ReportListCall<'a, C, 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 *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_dfareporting2d2 as dfareporting2d2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, A> MethodsBuilder for AdvertiserMethods<'a, C, A> {} + +impl<'a, C, A> AdvertiserMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Inserts a new advertiser. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + pub fn insert(&self, request: Advertiser, profile_id: &str) -> AdvertiserInsertCall<'a, C, A> { + AdvertiserInsertCall { + hub: self.hub, + _request: request, + _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. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + /// * `id` - Advertiser ID. + pub fn patch(&self, request: Advertiser, profile_id: &str, id: &str) -> AdvertiserPatchCall<'a, C, A> { + AdvertiserPatchCall { + hub: self.hub, + _request: request, + _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. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + pub fn list(&self, profile_id: &str) -> AdvertiserListCall<'a, C, 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. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + pub fn update(&self, request: Advertiser, profile_id: &str) -> AdvertiserUpdateCall<'a, C, A> { + AdvertiserUpdateCall { + hub: self.hub, + _request: request, + _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. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + /// * `id` - Advertiser ID. + pub fn get(&self, profile_id: &str, id: &str) -> AdvertiserGetCall<'a, C, 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_dfareporting2d2 as dfareporting2d2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, A> MethodsBuilder for DimensionValueMethods<'a, C, A> {} + +impl<'a, C, A> DimensionValueMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves list of report dimension values for a list of filters. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - The DFA user profile ID. + pub fn query(&self, request: DimensionValueRequest, profile_id: &str) -> DimensionValueQueryCall<'a, C, A> { + DimensionValueQueryCall { + hub: self.hub, + _request: request, + _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_dfareporting2d2 as dfareporting2d2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, A> MethodsBuilder for FloodlightActivityGroupMethods<'a, C, A> {} + +impl<'a, C, A> FloodlightActivityGroupMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Deletes an existing floodlight activity group. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + /// * `id` - Floodlight activity Group ID. + pub fn delete(&self, profile_id: &str, id: &str) -> FloodlightActivityGroupDeleteCall<'a, C, 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. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + /// * `id` - Floodlight activity Group ID. + pub fn get(&self, profile_id: &str, id: &str) -> FloodlightActivityGroupGetCall<'a, C, 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. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + /// * `id` - Floodlight activity Group ID. + pub fn patch(&self, request: FloodlightActivityGroup, profile_id: &str, id: &str) -> FloodlightActivityGroupPatchCall<'a, C, A> { + FloodlightActivityGroupPatchCall { + hub: self.hub, + _request: request, + _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. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + pub fn list(&self, profile_id: &str) -> FloodlightActivityGroupListCall<'a, C, 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. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + pub fn insert(&self, request: FloodlightActivityGroup, profile_id: &str) -> FloodlightActivityGroupInsertCall<'a, C, A> { + FloodlightActivityGroupInsertCall { + hub: self.hub, + _request: request, + _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. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + pub fn update(&self, request: FloodlightActivityGroup, profile_id: &str) -> FloodlightActivityGroupUpdateCall<'a, C, A> { + FloodlightActivityGroupUpdateCall { + hub: self.hub, + _request: request, + _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_dfareporting2d2 as dfareporting2d2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, A> MethodsBuilder for MetroMethods<'a, C, A> {} + +impl<'a, C, A> MetroMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a list of metros. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + pub fn list(&self, profile_id: &str) -> MetroListCall<'a, C, 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 *order* 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_dfareporting2d2 as dfareporting2d2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2d2::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.orders(); +/// # } +/// ``` +pub struct OrderMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, A> MethodsBuilder for OrderMethods<'a, C, A> {} + +impl<'a, C, A> OrderMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a list of orders, possibly filtered. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + /// * `projectId` - Project ID for orders. + pub fn list(&self, profile_id: &str, project_id: &str) -> OrderListCall<'a, C, A> { + OrderListCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _project_id: project_id.to_string(), + _sort_order: Default::default(), + _sort_field: Default::default(), + _site_id: 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: + /// + /// Gets one order by ID. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + /// * `projectId` - Project ID for orders. + /// * `id` - Order ID. + pub fn get(&self, profile_id: &str, project_id: &str, id: &str) -> OrderGetCall<'a, C, A> { + OrderGetCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _project_id: project_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 *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_dfareporting2d2 as dfareporting2d2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, A> MethodsBuilder for DirectorySiteContactMethods<'a, C, A> {} + +impl<'a, C, A> DirectorySiteContactMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Gets one directory site contact by ID. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + /// * `id` - Directory site contact ID. + pub fn get(&self, profile_id: &str, id: &str) -> DirectorySiteContactGetCall<'a, C, 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. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + pub fn list(&self, profile_id: &str) -> DirectorySiteContactListCall<'a, C, 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_dfareporting2d2 as dfareporting2d2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, A> MethodsBuilder for UserProfileMethods<'a, C, A> {} + +impl<'a, C, A> UserProfileMethods<'a, C, 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, 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. + /// + /// # Arguments + /// + /// * `profileId` - The user profile ID. + pub fn get(&self, profile_id: &str) -> UserProfileGetCall<'a, C, 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_dfareporting2d2 as dfareporting2d2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, A> MethodsBuilder for AdMethods<'a, C, A> {} + +impl<'a, C, A> AdMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing ad. This method supports patch semantics. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + /// * `id` - Ad ID. + pub fn patch(&self, request: Ad, profile_id: &str, id: &str) -> AdPatchCall<'a, C, A> { + AdPatchCall { + hub: self.hub, + _request: request, + _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. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + pub fn insert(&self, request: Ad, profile_id: &str) -> AdInsertCall<'a, C, A> { + AdInsertCall { + hub: self.hub, + _request: request, + _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. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + pub fn list(&self, profile_id: &str) -> AdListCall<'a, C, 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. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + /// * `id` - Ad ID. + pub fn get(&self, profile_id: &str, id: &str) -> AdGetCall<'a, C, 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. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + pub fn update(&self, request: Ad, profile_id: &str) -> AdUpdateCall<'a, C, A> { + AdUpdateCall { + hub: self.hub, + _request: request, + _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_dfareporting2d2 as dfareporting2d2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, A> MethodsBuilder for AccountPermissionMethods<'a, C, A> {} + +impl<'a, C, A> AccountPermissionMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Gets one account permission by ID. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + /// * `id` - Account permission ID. + pub fn get(&self, profile_id: &str, id: &str) -> AccountPermissionGetCall<'a, C, 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. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + pub fn list(&self, profile_id: &str) -> AccountPermissionListCall<'a, C, 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_dfareporting2d2 as dfareporting2d2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2d2::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.connection_types(); +/// # } +/// ``` +pub struct ConnectionTypeMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, A> MethodsBuilder for ConnectionTypeMethods<'a, C, A> {} + +impl<'a, C, A> ConnectionTypeMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a list of connection types. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + pub fn list(&self, profile_id: &str) -> ConnectionTypeListCall<'a, C, A> { + ConnectionTypeListCall { + 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 connection type by ID. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + /// * `id` - Connection type ID. + pub fn get(&self, profile_id: &str, id: &str) -> ConnectionTypeGetCall<'a, C, A> { + ConnectionTypeGetCall { + 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 *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_dfareporting2d2 as dfareporting2d2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, A> MethodsBuilder for AdvertiserGroupMethods<'a, C, A> {} + +impl<'a, C, A> AdvertiserGroupMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Gets one advertiser group by ID. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + /// * `id` - Advertiser group ID. + pub fn get(&self, profile_id: &str, id: &str) -> AdvertiserGroupGetCall<'a, C, 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. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + pub fn list(&self, profile_id: &str) -> AdvertiserGroupListCall<'a, C, 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. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + pub fn insert(&self, request: AdvertiserGroup, profile_id: &str) -> AdvertiserGroupInsertCall<'a, C, A> { + AdvertiserGroupInsertCall { + hub: self.hub, + _request: request, + _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. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + pub fn update(&self, request: AdvertiserGroup, profile_id: &str) -> AdvertiserGroupUpdateCall<'a, C, A> { + AdvertiserGroupUpdateCall { + hub: self.hub, + _request: request, + _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. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + /// * `id` - Advertiser group ID. + pub fn patch(&self, request: AdvertiserGroup, profile_id: &str, id: &str) -> AdvertiserGroupPatchCall<'a, C, A> { + AdvertiserGroupPatchCall { + hub: self.hub, + _request: request, + _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. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + /// * `id` - Advertiser group ID. + pub fn delete(&self, profile_id: &str, id: &str) -> AdvertiserGroupDeleteCall<'a, C, 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_dfareporting2d2 as dfareporting2d2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, A> MethodsBuilder for SiteMethods<'a, C, A> {} + +impl<'a, C, A> SiteMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Inserts a new site. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + pub fn insert(&self, request: Site, profile_id: &str) -> SiteInsertCall<'a, C, A> { + SiteInsertCall { + hub: self.hub, + _request: request, + _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. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + /// * `id` - Site ID. + pub fn get(&self, profile_id: &str, id: &str) -> SiteGetCall<'a, C, 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. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + pub fn list(&self, profile_id: &str) -> SiteListCall<'a, C, 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. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + pub fn update(&self, request: Site, profile_id: &str) -> SiteUpdateCall<'a, C, A> { + SiteUpdateCall { + hub: self.hub, + _request: request, + _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. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + /// * `id` - Site ID. + pub fn patch(&self, request: Site, profile_id: &str, id: &str) -> SitePatchCall<'a, C, A> { + SitePatchCall { + hub: self.hub, + _request: request, + _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_dfareporting2d2 as dfareporting2d2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, A> MethodsBuilder for FloodlightActivityMethods<'a, C, A> {} + +impl<'a, C, A> FloodlightActivityMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Gets one floodlight activity by ID. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + /// * `id` - Floodlight activity ID. + pub fn get(&self, profile_id: &str, id: &str) -> FloodlightActivityGetCall<'a, C, 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. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + pub fn list(&self, profile_id: &str) -> FloodlightActivityListCall<'a, C, 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. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + pub fn insert(&self, request: FloodlightActivity, profile_id: &str) -> FloodlightActivityInsertCall<'a, C, A> { + FloodlightActivityInsertCall { + hub: self.hub, + _request: request, + _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. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + /// * `id` - Floodlight activity ID. + pub fn delete(&self, profile_id: &str, id: &str) -> FloodlightActivityDeleteCall<'a, C, 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. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + /// * `id` - Floodlight activity ID. + pub fn patch(&self, request: FloodlightActivity, profile_id: &str, id: &str) -> FloodlightActivityPatchCall<'a, C, A> { + FloodlightActivityPatchCall { + hub: self.hub, + _request: request, + _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. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + pub fn generatetag(&self, profile_id: &str) -> FloodlightActivityGeneratetagCall<'a, C, 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. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + pub fn update(&self, request: FloodlightActivity, profile_id: &str) -> FloodlightActivityUpdateCall<'a, C, A> { + FloodlightActivityUpdateCall { + hub: self.hub, + _request: request, + _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_dfareporting2d2 as dfareporting2d2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, A> MethodsBuilder for RegionMethods<'a, C, A> {} + +impl<'a, C, A> RegionMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a list of regions. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + pub fn list(&self, profile_id: &str) -> RegionListCall<'a, C, 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_dfareporting2d2 as dfareporting2d2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, A> MethodsBuilder for CreativeGroupMethods<'a, C, A> {} + +impl<'a, C, A> CreativeGroupMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Inserts a new creative group. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + pub fn insert(&self, request: CreativeGroup, profile_id: &str) -> CreativeGroupInsertCall<'a, C, A> { + CreativeGroupInsertCall { + hub: self.hub, + _request: request, + _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. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + /// * `id` - Creative group ID. + pub fn get(&self, profile_id: &str, id: &str) -> CreativeGroupGetCall<'a, C, 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. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + pub fn update(&self, request: CreativeGroup, profile_id: &str) -> CreativeGroupUpdateCall<'a, C, A> { + CreativeGroupUpdateCall { + hub: self.hub, + _request: request, + _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. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + pub fn list(&self, profile_id: &str) -> CreativeGroupListCall<'a, C, 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. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + /// * `id` - Creative group ID. + pub fn patch(&self, request: CreativeGroup, profile_id: &str, id: &str) -> CreativeGroupPatchCall<'a, C, A> { + CreativeGroupPatchCall { + hub: self.hub, + _request: request, + _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 *targetableRemarketingList* 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_dfareporting2d2 as dfareporting2d2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2d2::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.targetable_remarketing_lists(); +/// # } +/// ``` +pub struct TargetableRemarketingListMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, A> MethodsBuilder for TargetableRemarketingListMethods<'a, C, A> {} + +impl<'a, C, A> TargetableRemarketingListMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a list of targetable remarketing lists, possibly filtered. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + /// * `advertiserId` - Select only targetable remarketing lists targetable by these advertisers. + pub fn list(&self, profile_id: &str, advertiser_id: &str) -> TargetableRemarketingListListCall<'a, C, A> { + TargetableRemarketingListListCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _advertiser_id: advertiser_id.to_string(), + _sort_order: Default::default(), + _sort_field: Default::default(), + _page_token: Default::default(), + _name: Default::default(), + _max_results: 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 remarketing list by ID. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + /// * `id` - Remarketing list ID. + pub fn get(&self, profile_id: &str, id: &str) -> TargetableRemarketingListGetCall<'a, C, A> { + TargetableRemarketingListGetCall { + 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 *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_dfareporting2d2 as dfareporting2d2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, A> MethodsBuilder for SubaccountMethods<'a, C, A> {} + +impl<'a, C, A> SubaccountMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing subaccount. This method supports patch semantics. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + /// * `id` - Subaccount ID. + pub fn patch(&self, request: Subaccount, profile_id: &str, id: &str) -> SubaccountPatchCall<'a, C, A> { + SubaccountPatchCall { + hub: self.hub, + _request: request, + _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. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + pub fn insert(&self, request: Subaccount, profile_id: &str) -> SubaccountInsertCall<'a, C, A> { + SubaccountInsertCall { + hub: self.hub, + _request: request, + _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. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + pub fn list(&self, profile_id: &str) -> SubaccountListCall<'a, C, 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. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + pub fn update(&self, request: Subaccount, profile_id: &str) -> SubaccountUpdateCall<'a, C, A> { + SubaccountUpdateCall { + hub: self.hub, + _request: request, + _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. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + /// * `id` - Subaccount ID. + pub fn get(&self, profile_id: &str, id: &str) -> SubaccountGetCall<'a, C, 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_dfareporting2d2 as dfareporting2d2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2d2::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.mobile_carriers(); +/// # } +/// ``` +pub struct MobileCarrierMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, A> MethodsBuilder for MobileCarrierMethods<'a, C, A> {} + +impl<'a, C, A> MobileCarrierMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Gets one mobile carrier by ID. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + /// * `id` - Mobile carrier ID. + pub fn get(&self, profile_id: &str, id: &str) -> MobileCarrierGetCall<'a, C, A> { + MobileCarrierGetCall { + 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 mobile carriers. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + pub fn list(&self, profile_id: &str) -> MobileCarrierListCall<'a, C, 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_dfareporting2d2 as dfareporting2d2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, A> MethodsBuilder for FloodlightConfigurationMethods<'a, C, A> {} + +impl<'a, C, A> FloodlightConfigurationMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Gets one floodlight configuration by ID. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + /// * `id` - Floodlight configuration ID. + pub fn get(&self, profile_id: &str, id: &str) -> FloodlightConfigurationGetCall<'a, C, 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: + /// + /// Updates an existing floodlight configuration. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + pub fn update(&self, request: FloodlightConfiguration, profile_id: &str) -> FloodlightConfigurationUpdateCall<'a, C, A> { + FloodlightConfigurationUpdateCall { + hub: self.hub, + _request: request, + _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. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + /// * `id` - Floodlight configuration ID. + pub fn patch(&self, request: FloodlightConfiguration, profile_id: &str, id: &str) -> FloodlightConfigurationPatchCall<'a, C, A> { + FloodlightConfigurationPatchCall { + hub: self.hub, + _request: request, + _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. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + pub fn list(&self, profile_id: &str) -> FloodlightConfigurationListCall<'a, C, 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_dfareporting2d2 as dfareporting2d2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2d2::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.operating_systems(); +/// # } +/// ``` +pub struct OperatingSystemMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, A> MethodsBuilder for OperatingSystemMethods<'a, C, A> {} + +impl<'a, C, A> OperatingSystemMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a list of operating systems. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + pub fn list(&self, profile_id: &str) -> OperatingSystemListCall<'a, C, A> { + OperatingSystemListCall { + 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 operating system by DART ID. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + /// * `dartId` - Operating system DART ID. + pub fn get(&self, profile_id: &str, dart_id: &str) -> OperatingSystemGetCall<'a, C, A> { + OperatingSystemGetCall { + 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 *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_dfareporting2d2 as dfareporting2d2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, A> MethodsBuilder for FileMethods<'a, C, A> {} + +impl<'a, C, A> FileMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Lists files for a user profile. + /// + /// # Arguments + /// + /// * `profileId` - The DFA profile ID. + pub fn list(&self, profile_id: &str) -> FileListCall<'a, C, 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. + /// + /// # Arguments + /// + /// * `reportId` - The ID of the report. + /// * `fileId` - The ID of the report file. + pub fn get(&self, report_id: &str, file_id: &str) -> FileGetCall<'a, C, 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_dfareporting2d2 as dfareporting2d2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, A> MethodsBuilder for PlacementGroupMethods<'a, C, A> {} + +impl<'a, C, A> PlacementGroupMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a list of placement groups, possibly filtered. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + pub fn list(&self, profile_id: &str) -> PlacementGroupListCall<'a, C, 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(), + _min_start_date: Default::default(), + _min_end_date: Default::default(), + _max_start_date: Default::default(), + _max_results: Default::default(), + _max_end_date: 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. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + pub fn update(&self, request: PlacementGroup, profile_id: &str) -> PlacementGroupUpdateCall<'a, C, A> { + PlacementGroupUpdateCall { + hub: self.hub, + _request: request, + _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. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + pub fn insert(&self, request: PlacementGroup, profile_id: &str) -> PlacementGroupInsertCall<'a, C, A> { + PlacementGroupInsertCall { + hub: self.hub, + _request: request, + _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. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + /// * `id` - Placement group ID. + pub fn get(&self, profile_id: &str, id: &str) -> PlacementGroupGetCall<'a, C, 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. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + /// * `id` - Placement group ID. + pub fn patch(&self, request: PlacementGroup, profile_id: &str, id: &str) -> PlacementGroupPatchCall<'a, C, A> { + PlacementGroupPatchCall { + hub: self.hub, + _request: request, + _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 *inventoryItem* 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_dfareporting2d2 as dfareporting2d2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2d2::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.inventory_items(); +/// # } +/// ``` +pub struct InventoryItemMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, A> MethodsBuilder for InventoryItemMethods<'a, C, A> {} + +impl<'a, C, A> InventoryItemMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a list of inventory items, possibly filtered. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + /// * `projectId` - Project ID for order documents. + pub fn list(&self, profile_id: &str, project_id: &str) -> InventoryItemListCall<'a, C, A> { + InventoryItemListCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _project_id: project_id.to_string(), + _sort_order: Default::default(), + _sort_field: Default::default(), + _site_id: Default::default(), + _page_token: Default::default(), + _order_id: Default::default(), + _max_results: Default::default(), + _in_plan: 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: + /// + /// Gets one inventory item by ID. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + /// * `projectId` - Project ID for order documents. + /// * `id` - Inventory item ID. + pub fn get(&self, profile_id: &str, project_id: &str, id: &str) -> InventoryItemGetCall<'a, C, A> { + InventoryItemGetCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _project_id: project_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 *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_dfareporting2d2 as dfareporting2d2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, A> MethodsBuilder for UserRolePermissionMethods<'a, C, A> {} + +impl<'a, C, A> UserRolePermissionMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Gets one user role permission by ID. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + /// * `id` - User role permission ID. + pub fn get(&self, profile_id: &str, id: &str) -> UserRolePermissionGetCall<'a, C, 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. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + pub fn list(&self, profile_id: &str) -> UserRolePermissionListCall<'a, C, 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_dfareporting2d2 as dfareporting2d2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, A> MethodsBuilder for AccountPermissionGroupMethods<'a, C, A> {} + +impl<'a, C, A> AccountPermissionGroupMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves the list of account permission groups. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + pub fn list(&self, profile_id: &str) -> AccountPermissionGroupListCall<'a, C, 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. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + /// * `id` - Account permission group ID. + pub fn get(&self, profile_id: &str, id: &str) -> AccountPermissionGroupGetCall<'a, C, 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_dfareporting2d2 as dfareporting2d2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, A> MethodsBuilder for ContentCategoryMethods<'a, C, A> {} + +impl<'a, C, A> ContentCategoryMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a list of content categories, possibly filtered. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + pub fn list(&self, profile_id: &str) -> ContentCategoryListCall<'a, C, 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. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + pub fn update(&self, request: ContentCategory, profile_id: &str) -> ContentCategoryUpdateCall<'a, C, A> { + ContentCategoryUpdateCall { + hub: self.hub, + _request: request, + _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. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + pub fn insert(&self, request: ContentCategory, profile_id: &str) -> ContentCategoryInsertCall<'a, C, A> { + ContentCategoryInsertCall { + hub: self.hub, + _request: request, + _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. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + /// * `id` - Content category ID. + pub fn delete(&self, profile_id: &str, id: &str) -> ContentCategoryDeleteCall<'a, C, 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. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + /// * `id` - Content category ID. + pub fn get(&self, profile_id: &str, id: &str) -> ContentCategoryGetCall<'a, C, 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. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + /// * `id` - Content category ID. + pub fn patch(&self, request: ContentCategory, profile_id: &str, id: &str) -> ContentCategoryPatchCall<'a, C, A> { + ContentCategoryPatchCall { + hub: self.hub, + _request: request, + _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_dfareporting2d2 as dfareporting2d2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, A> MethodsBuilder for CreativeMethods<'a, C, A> {} + +impl<'a, C, A> CreativeMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing creative. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + pub fn update(&self, request: Creative, profile_id: &str) -> CreativeUpdateCall<'a, C, A> { + CreativeUpdateCall { + hub: self.hub, + _request: request, + _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 creative. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + pub fn insert(&self, request: Creative, profile_id: &str) -> CreativeInsertCall<'a, C, A> { + CreativeInsertCall { + hub: self.hub, + _request: request, + _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. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + /// * `id` - Creative ID. + pub fn get(&self, profile_id: &str, id: &str) -> CreativeGetCall<'a, C, 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. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + pub fn list(&self, profile_id: &str) -> CreativeListCall<'a, C, 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. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + /// * `id` - Creative ID. + pub fn patch(&self, request: Creative, profile_id: &str, id: &str) -> CreativePatchCall<'a, C, A> { + CreativePatchCall { + hub: self.hub, + _request: request, + _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_dfareporting2d2 as dfareporting2d2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, A> MethodsBuilder for CampaignMethods<'a, C, A> {} + +impl<'a, C, A> CampaignMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Gets one campaign by ID. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + /// * `id` - Campaign ID. + pub fn get(&self, profile_id: &str, id: &str) -> CampaignGetCall<'a, C, 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. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + /// * `defaultLandingPageName` - Default landing page name for this new campaign. Must be less than 256 characters long. + /// * `defaultLandingPageUrl` - Default landing page URL for this new campaign. + pub fn insert(&self, request: Campaign, profile_id: &str, default_landing_page_name: &str, default_landing_page_url: &str) -> CampaignInsertCall<'a, C, A> { + CampaignInsertCall { + hub: self.hub, + _request: request, + _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. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + /// * `id` - Campaign ID. + pub fn patch(&self, request: Campaign, profile_id: &str, id: &str) -> CampaignPatchCall<'a, C, A> { + CampaignPatchCall { + hub: self.hub, + _request: request, + _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. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + pub fn update(&self, request: Campaign, profile_id: &str) -> CampaignUpdateCall<'a, C, A> { + CampaignUpdateCall { + hub: self.hub, + _request: request, + _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. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + pub fn list(&self, profile_id: &str) -> CampaignListCall<'a, C, 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_dfareporting2d2 as dfareporting2d2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, A> MethodsBuilder for EventTagMethods<'a, C, A> {} + +impl<'a, C, A> EventTagMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Deletes an existing event tag. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + /// * `id` - Event tag ID. + pub fn delete(&self, profile_id: &str, id: &str) -> EventTagDeleteCall<'a, C, 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. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + pub fn list(&self, profile_id: &str) -> EventTagListCall<'a, C, 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. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + pub fn insert(&self, request: EventTag, profile_id: &str) -> EventTagInsertCall<'a, C, A> { + EventTagInsertCall { + hub: self.hub, + _request: request, + _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. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + /// * `id` - Event tag ID. + pub fn patch(&self, request: EventTag, profile_id: &str, id: &str) -> EventTagPatchCall<'a, C, A> { + EventTagPatchCall { + hub: self.hub, + _request: request, + _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. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + pub fn update(&self, request: EventTag, profile_id: &str) -> EventTagUpdateCall<'a, C, A> { + EventTagUpdateCall { + hub: self.hub, + _request: request, + _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. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + /// * `id` - Event tag ID. + pub fn get(&self, profile_id: &str, id: &str) -> EventTagGetCall<'a, C, 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 *remarketingList* 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_dfareporting2d2 as dfareporting2d2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2d2::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.remarketing_lists(); +/// # } +/// ``` +pub struct RemarketingListMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, A> MethodsBuilder for RemarketingListMethods<'a, C, A> {} + +impl<'a, C, A> RemarketingListMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Gets one remarketing list by ID. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + /// * `id` - Remarketing list ID. + pub fn get(&self, profile_id: &str, id: &str) -> RemarketingListGetCall<'a, C, A> { + RemarketingListGetCall { + 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 remarketing list. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + pub fn update(&self, request: RemarketingList, profile_id: &str) -> RemarketingListUpdateCall<'a, C, A> { + RemarketingListUpdateCall { + hub: self.hub, + _request: request, + _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 remarketing lists, possibly filtered. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + /// * `advertiserId` - Select only remarketing lists owned by this advertiser. + pub fn list(&self, profile_id: &str, advertiser_id: &str) -> RemarketingListListCall<'a, C, A> { + RemarketingListListCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _advertiser_id: advertiser_id.to_string(), + _sort_order: Default::default(), + _sort_field: Default::default(), + _page_token: Default::default(), + _name: Default::default(), + _max_results: Default::default(), + _floodlight_activity_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 remarketing list. This method supports patch semantics. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + /// * `id` - Remarketing list ID. + pub fn patch(&self, request: RemarketingList, profile_id: &str, id: &str) -> RemarketingListPatchCall<'a, C, A> { + RemarketingListPatchCall { + hub: self.hub, + _request: request, + _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 remarketing list. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + pub fn insert(&self, request: RemarketingList, profile_id: &str) -> RemarketingListInsertCall<'a, C, A> { + RemarketingListInsertCall { + hub: self.hub, + _request: request, + _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 *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_dfareporting2d2 as dfareporting2d2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, A> MethodsBuilder for CityMethods<'a, C, A> {} + +impl<'a, C, A> CityMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a list of cities, possibly filtered. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + pub fn list(&self, profile_id: &str) -> CityListCall<'a, C, 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_dfareporting2d2 as dfareporting2d2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, A> MethodsBuilder for PlacementStrategyMethods<'a, C, A> {} + +impl<'a, C, A> PlacementStrategyMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing placement strategy. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + pub fn update(&self, request: PlacementStrategy, profile_id: &str) -> PlacementStrategyUpdateCall<'a, C, A> { + PlacementStrategyUpdateCall { + hub: self.hub, + _request: request, + _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. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + /// * `id` - Placement strategy ID. + pub fn get(&self, profile_id: &str, id: &str) -> PlacementStrategyGetCall<'a, C, 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: + /// + /// Retrieves a list of placement strategies, possibly filtered. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + pub fn list(&self, profile_id: &str) -> PlacementStrategyListCall<'a, C, 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: + /// + /// Deletes an existing placement strategy. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + /// * `id` - Placement strategy ID. + pub fn delete(&self, profile_id: &str, id: &str) -> PlacementStrategyDeleteCall<'a, C, 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. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + pub fn insert(&self, request: PlacementStrategy, profile_id: &str) -> PlacementStrategyInsertCall<'a, C, A> { + PlacementStrategyInsertCall { + hub: self.hub, + _request: request, + _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. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + /// * `id` - Placement strategy ID. + pub fn patch(&self, request: PlacementStrategy, profile_id: &str, id: &str) -> PlacementStrategyPatchCall<'a, C, A> { + PlacementStrategyPatchCall { + hub: self.hub, + _request: request, + _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 *project* 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_dfareporting2d2 as dfareporting2d2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2d2::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.projects(); +/// # } +/// ``` +pub struct ProjectMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, A> MethodsBuilder for ProjectMethods<'a, C, A> {} + +impl<'a, C, A> ProjectMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a list of projects, possibly filtered. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + pub fn list(&self, profile_id: &str) -> ProjectListCall<'a, C, A> { + ProjectListCall { + 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: + /// + /// Gets one project by ID. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + /// * `id` - Project ID. + pub fn get(&self, profile_id: &str, id: &str) -> ProjectGetCall<'a, C, A> { + ProjectGetCall { + 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 *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_dfareporting2d2 as dfareporting2d2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2d2::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.directory_sites(); +/// # } +/// ``` +pub struct DirectorySiteMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, A> MethodsBuilder for DirectorySiteMethods<'a, C, A> {} + +impl<'a, C, A> DirectorySiteMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Inserts a new directory site. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + pub fn insert(&self, request: DirectorySite, profile_id: &str) -> DirectorySiteInsertCall<'a, C, A> { + DirectorySiteInsertCall { + hub: self.hub, + _request: request, + _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 directory sites, possibly filtered. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + pub fn list(&self, profile_id: &str) -> DirectorySiteListCall<'a, C, 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. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + /// * `id` - Directory site ID. + pub fn get(&self, profile_id: &str, id: &str) -> DirectorySiteGetCall<'a, C, 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_dfareporting2d2 as dfareporting2d2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, A> MethodsBuilder for SizeMethods<'a, C, A> {} + +impl<'a, C, A> SizeMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Inserts a new size. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + pub fn insert(&self, request: Size, profile_id: &str) -> SizeInsertCall<'a, C, A> { + SizeInsertCall { + hub: self.hub, + _request: request, + _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. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + pub fn list(&self, profile_id: &str) -> SizeListCall<'a, C, 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. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + /// * `id` - Size ID. + pub fn get(&self, profile_id: &str, id: &str) -> SizeGetCall<'a, C, 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_dfareporting2d2 as dfareporting2d2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, A> MethodsBuilder for AccountActiveAdSummaryMethods<'a, C, A> {} + +impl<'a, C, A> AccountActiveAdSummaryMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Gets the account's active ad summary by account ID. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + /// * `summaryAccountId` - Account ID. + pub fn get(&self, profile_id: &str, summary_account_id: &str) -> AccountActiveAdSummaryGetCall<'a, C, 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_dfareporting2d2 as dfareporting2d2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2d2::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.account_user_profiles(); +/// # } +/// ``` +pub struct AccountUserProfileMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, A> MethodsBuilder for AccountUserProfileMethods<'a, C, A> {} + +impl<'a, C, A> AccountUserProfileMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing account user profile. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + pub fn update(&self, request: AccountUserProfile, profile_id: &str) -> AccountUserProfileUpdateCall<'a, C, A> { + AccountUserProfileUpdateCall { + hub: self.hub, + _request: request, + _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. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + pub fn list(&self, profile_id: &str) -> AccountUserProfileListCall<'a, C, 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: + /// + /// Inserts a new account user profile. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + pub fn insert(&self, request: AccountUserProfile, profile_id: &str) -> AccountUserProfileInsertCall<'a, C, A> { + AccountUserProfileInsertCall { + hub: self.hub, + _request: request, + _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 user profile. This method supports patch semantics. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + /// * `id` - User profile ID. + pub fn patch(&self, request: AccountUserProfile, profile_id: &str, id: &str) -> AccountUserProfilePatchCall<'a, C, A> { + AccountUserProfilePatchCall { + hub: self.hub, + _request: request, + _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. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + /// * `id` - User profile ID. + pub fn get(&self, profile_id: &str, id: &str) -> AccountUserProfileGetCall<'a, C, 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_dfareporting2d2 as dfareporting2d2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, A> MethodsBuilder for CountryMethods<'a, C, A> {} + +impl<'a, C, A> CountryMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a list of countries. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + pub fn list(&self, profile_id: &str) -> CountryListCall<'a, C, 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. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + /// * `dartId` - Country DART ID. + pub fn get(&self, profile_id: &str, dart_id: &str) -> CountryGetCall<'a, C, 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 *orderDocument* 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_dfareporting2d2 as dfareporting2d2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2d2::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.order_documents(); +/// # } +/// ``` +pub struct OrderDocumentMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, A> MethodsBuilder for OrderDocumentMethods<'a, C, A> {} + +impl<'a, C, A> OrderDocumentMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Gets one order document by ID. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + /// * `projectId` - Project ID for order documents. + /// * `id` - Order document ID. + pub fn get(&self, profile_id: &str, project_id: &str, id: &str) -> OrderDocumentGetCall<'a, C, A> { + OrderDocumentGetCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _project_id: project_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 order documents, possibly filtered. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + /// * `projectId` - Project ID for order documents. + pub fn list(&self, profile_id: &str, project_id: &str) -> OrderDocumentListCall<'a, C, A> { + OrderDocumentListCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _project_id: project_id.to_string(), + _sort_order: Default::default(), + _sort_field: Default::default(), + _site_id: Default::default(), + _search_string: Default::default(), + _page_token: Default::default(), + _order_id: Default::default(), + _max_results: Default::default(), + _ids: Default::default(), + _approved: Default::default(), + _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_dfareporting2d2 as dfareporting2d2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2d2::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.postal_codes(); +/// # } +/// ``` +pub struct PostalCodeMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, A> MethodsBuilder for PostalCodeMethods<'a, C, A> {} + +impl<'a, C, A> PostalCodeMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Gets one postal code by ID. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + /// * `code` - Postal code ID. + pub fn get(&self, profile_id: &str, code: &str) -> PostalCodeGetCall<'a, C, A> { + PostalCodeGetCall { + hub: self.hub, + _profile_id: profile_id.to_string(), + _code: code.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 postal codes. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + pub fn list(&self, profile_id: &str) -> PostalCodeListCall<'a, C, 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 *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_dfareporting2d2 as dfareporting2d2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, A> MethodsBuilder for BrowserMethods<'a, C, A> {} + +impl<'a, C, A> BrowserMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Retrieves a list of browsers. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + pub fn list(&self, profile_id: &str) -> BrowserListCall<'a, C, 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 *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_dfareporting2d2 as dfareporting2d2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, A> MethodsBuilder for AccountMethods<'a, C, A> {} + +impl<'a, C, A> AccountMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Gets one account by ID. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + /// * `id` - Account ID. + pub fn get(&self, profile_id: &str, id: &str) -> AccountGetCall<'a, C, 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. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + pub fn list(&self, profile_id: &str) -> AccountListCall<'a, C, 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. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + pub fn update(&self, request: Account, profile_id: &str) -> AccountUpdateCall<'a, C, A> { + AccountUpdateCall { + hub: self.hub, + _request: request, + _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. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + /// * `id` - Account ID. + pub fn patch(&self, request: Account, profile_id: &str, id: &str) -> AccountPatchCall<'a, C, A> { + AccountPatchCall { + hub: self.hub, + _request: request, + _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 *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_dfareporting2d2 as dfareporting2d2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, +} + +impl<'a, C, A> MethodsBuilder for PlacementMethods<'a, C, A> {} + +impl<'a, C, A> PlacementMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Updates an existing placement. This method supports patch semantics. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + /// * `id` - Placement ID. + pub fn patch(&self, request: Placement, profile_id: &str, id: &str) -> PlacementPatchCall<'a, C, A> { + PlacementPatchCall { + hub: self.hub, + _request: request, + _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. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + pub fn list(&self, profile_id: &str) -> PlacementListCall<'a, C, 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(), + _min_start_date: Default::default(), + _min_end_date: Default::default(), + _max_start_date: Default::default(), + _max_results: Default::default(), + _max_end_date: 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: + /// + /// Inserts a new placement. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + pub fn insert(&self, request: Placement, profile_id: &str) -> PlacementInsertCall<'a, C, A> { + PlacementInsertCall { + hub: self.hub, + _request: request, + _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. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `profileId` - User profile ID associated with this request. + pub fn update(&self, request: Placement, profile_id: &str) -> PlacementUpdateCall<'a, C, A> { + PlacementUpdateCall { + hub: self.hub, + _request: request, + _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. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + pub fn generatetags(&self, profile_id: &str) -> PlacementGeneratetagCall<'a, C, 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(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets one placement by ID. + /// + /// # Arguments + /// + /// * `profileId` - User profile ID associated with this request. + /// * `id` - Placement ID. + pub fn get(&self, profile_id: &str, id: &str) -> PlacementGetCall<'a, C, 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(), + } + } +} + + + + + +// ################### +// 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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for UserRolePermissionGroupGetCall<'a, C, A> {} + +impl<'a, C, A> UserRolePermissionGroupGetCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/userRolePermissionGroups/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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 ["id", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> UserRolePermissionGroupGetCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// User role permission group ID. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> UserRolePermissionGroupGetCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserRolePermissionGroupGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for UserRolePermissionGroupListCall<'a, C, A> {} + +impl<'a, C, A> UserRolePermissionGroupListCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/userRolePermissionGroups".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> UserRolePermissionGroupListCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserRolePermissionGroupListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Gets one platform type by ID. +/// +/// A builder for the *get* method supported by a *platformType* resource. +/// It is not used directly, but through a `PlatformTypeMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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().get("profileId", "id") +/// .doit(); +/// # } +/// ``` +pub struct PlatformTypeGetCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for PlatformTypeGetCall<'a, C, A> {} + +impl<'a, C, A> PlatformTypeGetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, PlatformType)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/platformTypes/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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 ["id", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> PlatformTypeGetCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Platform type ID. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> PlatformTypeGetCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PlatformTypeGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PlatformTypeGetCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PlatformTypeGetCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for PlatformTypeListCall<'a, C, A> {} + +impl<'a, C, A> PlatformTypeListCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/platformTypes".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> PlatformTypeListCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PlatformTypeListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::CreativeFieldValue; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: '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, A> CallBuilder for CreativeFieldValuePatchCall<'a, C, A> {} + +impl<'a, C, A> CreativeFieldValuePatchCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/creativeFields/{creativeFieldId}/creativeFieldValues".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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 ["creativeFieldId", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> CreativeFieldValuePatchCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Creative field ID for this creative field value. + /// + /// 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. + pub fn creative_field_id(mut self, new_value: &str) -> CreativeFieldValuePatchCall<'a, C, A> { + self._creative_field_id = new_value.to_string(); + self + } + /// Creative Field Value ID + /// + /// 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. + pub fn id(mut self, new_value: &str) -> CreativeFieldValuePatchCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CreativeFieldValuePatchCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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, A> + where C: '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, A> CallBuilder for CreativeFieldValueGetCall<'a, C, A> {} + +impl<'a, C, A> CreativeFieldValueGetCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/creativeFields/{creativeFieldId}/creativeFieldValues/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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 ["id", "creativeFieldId", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> CreativeFieldValueGetCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Creative field ID for this creative field value. + /// + /// 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. + pub fn creative_field_id(mut self, new_value: &str) -> CreativeFieldValueGetCall<'a, C, A> { + self._creative_field_id = new_value.to_string(); + self + } + /// Creative Field Value ID + /// + /// 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. + pub fn id(mut self, new_value: &str) -> CreativeFieldValueGetCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CreativeFieldValueGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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, A> + where C: '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, A> CallBuilder for CreativeFieldValueDeleteCall<'a, C, A> {} + +impl<'a, C, A> CreativeFieldValueDeleteCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/dfareporting/v2.2/userprofiles/{profileId}/creativeFields/{creativeFieldId}/creativeFieldValues/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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 ["id", "creativeFieldId", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = res; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> CreativeFieldValueDeleteCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Creative field ID for this creative field value. + /// + /// 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. + pub fn creative_field_id(mut self, new_value: &str) -> CreativeFieldValueDeleteCall<'a, C, A> { + self._creative_field_id = new_value.to_string(); + self + } + /// Creative Field Value ID + /// + /// 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. + pub fn id(mut self, new_value: &str) -> CreativeFieldValueDeleteCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CreativeFieldValueDeleteCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::CreativeFieldValue; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: '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, A> CallBuilder for CreativeFieldValueInsertCall<'a, C, A> {} + +impl<'a, C, A> CreativeFieldValueInsertCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/creativeFields/{creativeFieldId}/creativeFieldValues".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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 ["creativeFieldId", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> CreativeFieldValueInsertCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Creative field ID for this creative field value. + /// + /// 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. + pub fn creative_field_id(mut self, new_value: &str) -> CreativeFieldValueInsertCall<'a, C, A> { + self._creative_field_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CreativeFieldValueInsertCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::CreativeFieldValue; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: '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, A> CallBuilder for CreativeFieldValueUpdateCall<'a, C, A> {} + +impl<'a, C, A> CreativeFieldValueUpdateCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/creativeFields/{creativeFieldId}/creativeFieldValues".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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 ["creativeFieldId", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> CreativeFieldValueUpdateCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Creative field ID for this creative field value. + /// + /// 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. + pub fn creative_field_id(mut self, new_value: &str) -> CreativeFieldValueUpdateCall<'a, C, A> { + self._creative_field_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CreativeFieldValueUpdateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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("eos") +/// .sort_field("erat") +/// .search_string("sadipscing") +/// .page_token("dolor") +/// .max_results(-39) +/// .add_ids("elitr") +/// .doit(); +/// # } +/// ``` +pub struct CreativeFieldValueListCall<'a, C, A> + where C: '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, A> CallBuilder for CreativeFieldValueListCall<'a, C, A> {} + +impl<'a, C, A> CreativeFieldValueListCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/creativeFields/{creativeFieldId}/creativeFieldValues".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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 ["creativeFieldId", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> CreativeFieldValueListCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Creative field ID for this creative field value. + /// + /// 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. + pub fn creative_field_id(mut self, new_value: &str) -> CreativeFieldValueListCall<'a, C, A> { + self._creative_field_id = new_value.to_string(); + self + } + /// Order of sorted results, default is ASCENDING. + /// + /// Sets the *sort order* query property to the given value. + pub fn sort_order(mut self, new_value: &str) -> CreativeFieldValueListCall<'a, C, A> { + self._sort_order = Some(new_value.to_string()); + self + } + /// Field by which to sort the list. + /// + /// Sets the *sort field* query property to the given value. + pub fn sort_field(mut self, new_value: &str) -> CreativeFieldValueListCall<'a, C, A> { + self._sort_field = Some(new_value.to_string()); + self + } + /// Allows searching for creative field values by their values. Wildcards (e.g. *) are not allowed. + /// + /// Sets the *search string* query property to the given value. + pub fn search_string(mut self, new_value: &str) -> CreativeFieldValueListCall<'a, C, A> { + self._search_string = Some(new_value.to_string()); + self + } + /// Value of the nextPageToken from the previous result page. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> CreativeFieldValueListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Maximum number of results to return. + /// + /// Sets the *max results* query property to the given value. + pub fn max_results(mut self, new_value: i32) -> CreativeFieldValueListCall<'a, C, A> { + self._max_results = Some(new_value); + self + } + /// Select only creative field values with these IDs. + /// + /// 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. + pub fn add_ids(mut self, new_value: &str) -> CreativeFieldValueListCall<'a, C, A> { + self._ids.push(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CreativeFieldValueListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::CreativeField; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: CreativeField, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for CreativeFieldUpdateCall<'a, C, A> {} + +impl<'a, C, A> CreativeFieldUpdateCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/creativeFields".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> CreativeFieldUpdateCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CreativeFieldUpdateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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("labore") +/// .sort_field("eirmod") +/// .search_string("dolore") +/// .page_token("invidunt") +/// .max_results(-82) +/// .add_ids("accusam") +/// .add_advertiser_ids("Lorem") +/// .doit(); +/// # } +/// ``` +pub struct CreativeFieldListCall<'a, C, A> + where C: '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, A> CallBuilder for CreativeFieldListCall<'a, C, A> {} + +impl<'a, C, A> CreativeFieldListCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/creativeFields".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> CreativeFieldListCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Order of sorted results, default is ASCENDING. + /// + /// Sets the *sort order* query property to the given value. + pub fn sort_order(mut self, new_value: &str) -> CreativeFieldListCall<'a, C, A> { + self._sort_order = Some(new_value.to_string()); + self + } + /// Field by which to sort the list. + /// + /// Sets the *sort field* query property to the given value. + pub fn sort_field(mut self, new_value: &str) -> CreativeFieldListCall<'a, C, A> { + self._sort_field = Some(new_value.to_string()); + self + } + /// 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". + /// + /// Sets the *search string* query property to the given value. + pub fn search_string(mut self, new_value: &str) -> CreativeFieldListCall<'a, C, A> { + self._search_string = Some(new_value.to_string()); + self + } + /// Value of the nextPageToken from the previous result page. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> CreativeFieldListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Maximum number of results to return. + /// + /// Sets the *max results* query property to the given value. + pub fn max_results(mut self, new_value: i32) -> CreativeFieldListCall<'a, C, A> { + self._max_results = Some(new_value); + self + } + /// Select only creative fields with these IDs. + /// + /// 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. + pub fn add_ids(mut self, new_value: &str) -> CreativeFieldListCall<'a, C, A> { + self._ids.push(new_value.to_string()); + self + } + /// Select only creative fields that belong to these advertisers. + /// + /// 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. + pub fn add_advertiser_ids(mut self, new_value: &str) -> CreativeFieldListCall<'a, C, A> { + self._advertiser_ids.push(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CreativeFieldListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for CreativeFieldDeleteCall<'a, C, A> {} + +impl<'a, C, A> CreativeFieldDeleteCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/dfareporting/v2.2/userprofiles/{profileId}/creativeFields/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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 ["id", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = res; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> CreativeFieldDeleteCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Creative Field ID + /// + /// 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. + pub fn id(mut self, new_value: &str) -> CreativeFieldDeleteCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CreativeFieldDeleteCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for CreativeFieldGetCall<'a, C, A> {} + +impl<'a, C, A> CreativeFieldGetCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/creativeFields/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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 ["id", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> CreativeFieldGetCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Creative Field ID + /// + /// 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. + pub fn id(mut self, new_value: &str) -> CreativeFieldGetCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CreativeFieldGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::CreativeField; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: CreativeField, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for CreativeFieldInsertCall<'a, C, A> {} + +impl<'a, C, A> CreativeFieldInsertCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/creativeFields".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> CreativeFieldInsertCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CreativeFieldInsertCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::CreativeField; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: '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, A> CallBuilder for CreativeFieldPatchCall<'a, C, A> {} + +impl<'a, C, A> CreativeFieldPatchCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/creativeFields".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> CreativeFieldPatchCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Creative Field ID + /// + /// 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. + pub fn id(mut self, new_value: &str) -> CreativeFieldPatchCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CreativeFieldPatchCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::UserRole; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: UserRole, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for UserRoleInsertCall<'a, C, A> {} + +impl<'a, C, A> UserRoleInsertCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/userRoles".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> UserRoleInsertCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserRoleInsertCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for UserRoleGetCall<'a, C, A> {} + +impl<'a, C, A> UserRoleGetCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/userRoles/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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 ["id", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> UserRoleGetCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// User role ID. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> UserRoleGetCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserRoleGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::UserRole; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: UserRole, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for UserRoleUpdateCall<'a, C, A> {} + +impl<'a, C, A> UserRoleUpdateCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/userRoles".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> UserRoleUpdateCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserRoleUpdateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for UserRoleDeleteCall<'a, C, A> {} + +impl<'a, C, A> UserRoleDeleteCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/dfareporting/v2.2/userprofiles/{profileId}/userRoles/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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 ["id", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = res; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> UserRoleDeleteCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// User role ID. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> UserRoleDeleteCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserRoleDeleteCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::UserRole; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: '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, A> CallBuilder for UserRolePatchCall<'a, C, A> {} + +impl<'a, C, A> UserRolePatchCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/userRoles".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> UserRolePatchCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// User role ID. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> UserRolePatchCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserRolePatchCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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("et") +/// .sort_order("consetetur") +/// .sort_field("amet.") +/// .search_string("voluptua.") +/// .page_token("Lorem") +/// .max_results(-11) +/// .add_ids("justo") +/// .account_user_role_only(false) +/// .doit(); +/// # } +/// ``` +pub struct UserRoleListCall<'a, C, A> + where C: '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, A> CallBuilder for UserRoleListCall<'a, C, A> {} + +impl<'a, C, A> UserRoleListCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/userRoles".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> UserRoleListCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Select only user roles that belong to this subaccount. + /// + /// Sets the *subaccount id* query property to the given value. + pub fn subaccount_id(mut self, new_value: &str) -> UserRoleListCall<'a, C, A> { + self._subaccount_id = Some(new_value.to_string()); + self + } + /// Order of sorted results, default is ASCENDING. + /// + /// Sets the *sort order* query property to the given value. + pub fn sort_order(mut self, new_value: &str) -> UserRoleListCall<'a, C, A> { + self._sort_order = Some(new_value.to_string()); + self + } + /// Field by which to sort the list. + /// + /// Sets the *sort field* query property to the given value. + pub fn sort_field(mut self, new_value: &str) -> UserRoleListCall<'a, C, A> { + self._sort_field = Some(new_value.to_string()); + self + } + /// 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". + /// + /// Sets the *search string* query property to the given value. + pub fn search_string(mut self, new_value: &str) -> UserRoleListCall<'a, C, A> { + self._search_string = Some(new_value.to_string()); + self + } + /// Value of the nextPageToken from the previous result page. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> UserRoleListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Maximum number of results to return. + /// + /// Sets the *max results* query property to the given value. + pub fn max_results(mut self, new_value: i32) -> UserRoleListCall<'a, C, A> { + self._max_results = Some(new_value); + self + } + /// Select only user roles with the specified IDs. + /// + /// 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. + pub fn add_ids(mut self, new_value: &str) -> UserRoleListCall<'a, C, A> { + self._ids.push(new_value.to_string()); + self + } + /// Select only account level user roles not associated with any specific subaccount. + /// + /// Sets the *account user role only* query property to the given value. + pub fn account_user_role_only(mut self, new_value: bool) -> UserRoleListCall<'a, C, A> { + self._account_user_role_only = Some(new_value); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserRoleListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Gets one operating system version by ID. +/// +/// A builder for the *get* method supported by a *operatingSystemVersion* resource. +/// It is not used directly, but through a `OperatingSystemVersionMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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().get("profileId", "id") +/// .doit(); +/// # } +/// ``` +pub struct OperatingSystemVersionGetCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for OperatingSystemVersionGetCall<'a, C, A> {} + +impl<'a, C, A> OperatingSystemVersionGetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, OperatingSystemVersion)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/operatingSystemVersions/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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 ["id", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> OperatingSystemVersionGetCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Operating system version ID. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> OperatingSystemVersionGetCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> OperatingSystemVersionGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> OperatingSystemVersionGetCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> OperatingSystemVersionGetCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for OperatingSystemVersionListCall<'a, C, A> {} + +impl<'a, C, A> OperatingSystemVersionListCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/operatingSystemVersions".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> OperatingSystemVersionListCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> OperatingSystemVersionListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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, A> + where C: '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, A> CallBuilder for LandingPageGetCall<'a, C, A> {} + +impl<'a, C, A> LandingPageGetCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/campaigns/{campaignId}/landingPages/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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 ["id", "campaignId", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> LandingPageGetCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Landing page campaign ID. + /// + /// 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. + pub fn campaign_id(mut self, new_value: &str) -> LandingPageGetCall<'a, C, A> { + self._campaign_id = new_value.to_string(); + self + } + /// Landing page ID. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> LandingPageGetCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> LandingPageGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::LandingPage; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: '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, A> CallBuilder for LandingPageUpdateCall<'a, C, A> {} + +impl<'a, C, A> LandingPageUpdateCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/campaigns/{campaignId}/landingPages".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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 ["campaignId", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> LandingPageUpdateCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Landing page campaign ID. + /// + /// 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. + pub fn campaign_id(mut self, new_value: &str) -> LandingPageUpdateCall<'a, C, A> { + self._campaign_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> LandingPageUpdateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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, A> + where C: '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, A> CallBuilder for LandingPageListCall<'a, C, A> {} + +impl<'a, C, A> LandingPageListCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/campaigns/{campaignId}/landingPages".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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 ["campaignId", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> LandingPageListCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Landing page campaign ID. + /// + /// 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. + pub fn campaign_id(mut self, new_value: &str) -> LandingPageListCall<'a, C, A> { + self._campaign_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> LandingPageListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::LandingPage; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: '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, A> CallBuilder for LandingPageInsertCall<'a, C, A> {} + +impl<'a, C, A> LandingPageInsertCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/campaigns/{campaignId}/landingPages".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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 ["campaignId", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> LandingPageInsertCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Landing page campaign ID. + /// + /// 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. + pub fn campaign_id(mut self, new_value: &str) -> LandingPageInsertCall<'a, C, A> { + self._campaign_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> LandingPageInsertCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::LandingPage; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: '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, A> CallBuilder for LandingPagePatchCall<'a, C, A> {} + +impl<'a, C, A> LandingPagePatchCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/campaigns/{campaignId}/landingPages".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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 ["campaignId", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> LandingPagePatchCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Landing page campaign ID. + /// + /// 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. + pub fn campaign_id(mut self, new_value: &str) -> LandingPagePatchCall<'a, C, A> { + self._campaign_id = new_value.to_string(); + self + } + /// Landing page ID. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> LandingPagePatchCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> LandingPagePatchCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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, A> + where C: '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, A> CallBuilder for LandingPageDeleteCall<'a, C, A> {} + +impl<'a, C, A> LandingPageDeleteCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/dfareporting/v2.2/userprofiles/{profileId}/campaigns/{campaignId}/landingPages/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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 ["id", "campaignId", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = res; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> LandingPageDeleteCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Landing page campaign ID. + /// + /// 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. + pub fn campaign_id(mut self, new_value: &str) -> LandingPageDeleteCall<'a, C, A> { + self._campaign_id = new_value.to_string(); + self + } + /// Landing page ID. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> LandingPageDeleteCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> LandingPageDeleteCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::CreativeAssetMetadata; +/// use std::fs; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // 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, A> + where C: '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, A> CallBuilder for CreativeAssetInsertCall<'a, C, A> {} + +impl<'a, C, A> CreativeAssetInsertCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let (mut url, upload_type) = + if protocol == "simple" { + ("https://www.googleapis.com/upload/dfareporting/v2.2/userprofiles/{profileId}/creativeAssets/{advertiserId}/creativeAssets".to_string(), "multipart") + } else if protocol == "resumable" { + ("https://www.googleapis.com/resumable/upload/dfareporting/v2.2/userprofiles/{profileId}/creativeAssets/{advertiserId}/creativeAssets".to_string(), "resumable") + } else { + unreachable!() + }; + params.push(("uploadType", upload_type.to_string())); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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 ["advertiserId", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + 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 token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.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 url = upload_url.as_ref().and_then(|s| Some(hyper::Url::parse(s).unwrap())).unwrap(); + hyper::client::Response::new(url, Box::new(cmn::DummyNetworkStream)).and_then(|mut res| { + res.status = hyper::status::StatusCode::Ok; + res.headers.set(Location(upload_url.as_ref().unwrap().clone())); + Ok(res) + }) + } 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 > 104857600 { + return Err(Error::UploadSizeLimitExceeded(size, 104857600)) + } + 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) + .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_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + if protocol == "resumable" { + let size = reader.seek(io::SeekFrom::End(0)).unwrap(); + reader.seek(io::SeekFrom::Start(0)).unwrap(); + if size > 104857600 { + return Err(Error::UploadSizeLimitExceeded(size, 104857600)) + } + let mut client = &mut *self.hub.client.borrow_mut(); + let upload_result = { + let url_str = &res.headers.get::().expect("Location header is part of protocol").0; + if upload_url_from_server { + dlg.store_upload_url(Some(url_str)); + } + + 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_str, + reader: &mut reader, + media_type: reader_mime_type.clone(), + content_length: size + }.upload() + }; + match upload_result { + None => { + dlg.finished(false); + return Err(Error::Cancelled) + } + Some(Err(err)) => { + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Some(Ok(upload_result)) => { + res = upload_result; + if !res.status.is_success() { + dlg.store_upload_url(None); + dlg.finished(false); + return Err(Error::Failure(res)) + } + } + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(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 resumable 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. + /// + /// The delegate will be asked for an `upload_url()`, and if not provided, will be asked to store an upload URL + /// that was provided by the server, using `store_upload_url(...)`. The upload will be done in chunks, the delegate + /// may specify the `chunk_size()` and may cancel the operation before each chunk is uploaded, using + /// `cancel_chunk_upload(...)`. + /// + /// * *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, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> CreativeAssetInsertCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Advertiser ID of this creative. This is a required field. + /// + /// 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. + pub fn advertiser_id(mut self, new_value: &str) -> CreativeAssetInsertCall<'a, C, A> { + self._advertiser_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CreativeAssetInsertCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::CampaignCreativeAssociation; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: '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, A> CallBuilder for CampaignCreativeAssociationInsertCall<'a, C, A> {} + +impl<'a, C, A> CampaignCreativeAssociationInsertCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/campaigns/{campaignId}/campaignCreativeAssociations".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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 ["campaignId", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> CampaignCreativeAssociationInsertCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Campaign ID in this association. + /// + /// 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. + pub fn campaign_id(mut self, new_value: &str) -> CampaignCreativeAssociationInsertCall<'a, C, A> { + self._campaign_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CampaignCreativeAssociationInsertCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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("ea") +/// .page_token("sadipscing") +/// .max_results(-66) +/// .doit(); +/// # } +/// ``` +pub struct CampaignCreativeAssociationListCall<'a, C, A> + where C: '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, A> CallBuilder for CampaignCreativeAssociationListCall<'a, C, A> {} + +impl<'a, C, A> CampaignCreativeAssociationListCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/campaigns/{campaignId}/campaignCreativeAssociations".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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 ["campaignId", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> CampaignCreativeAssociationListCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Campaign ID in this association. + /// + /// 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. + pub fn campaign_id(mut self, new_value: &str) -> CampaignCreativeAssociationListCall<'a, C, A> { + self._campaign_id = new_value.to_string(); + self + } + /// Order of sorted results, default is ASCENDING. + /// + /// Sets the *sort order* query property to the given value. + pub fn sort_order(mut self, new_value: &str) -> CampaignCreativeAssociationListCall<'a, C, A> { + self._sort_order = Some(new_value.to_string()); + self + } + /// Value of the nextPageToken from the previous result page. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> CampaignCreativeAssociationListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Maximum number of results to return. + /// + /// Sets the *max results* query property to the given value. + pub fn max_results(mut self, new_value: i32) -> CampaignCreativeAssociationListCall<'a, C, A> { + self._max_results = Some(new_value); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CampaignCreativeAssociationListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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("nonumy") +/// .search_string("sed") +/// .page_token("aliquyam") +/// .object_type("sit") +/// .add_object_ids("eirmod") +/// .min_change_time("consetetur") +/// .max_results(-85) +/// .max_change_time("sed") +/// .add_ids("ea") +/// .action("gubergren") +/// .doit(); +/// # } +/// ``` +pub struct ChangeLogListCall<'a, C, A> + where C: '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, A> CallBuilder for ChangeLogListCall<'a, C, A> {} + +impl<'a, C, A> ChangeLogListCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/changeLogs".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> ChangeLogListCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Select only change logs with these user profile IDs. + /// + /// 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. + pub fn add_user_profile_ids(mut self, new_value: &str) -> ChangeLogListCall<'a, C, A> { + self._user_profile_ids.push(new_value.to_string()); + self + } + /// Select only change logs whose object ID, user name, old or new values match the search string. + /// + /// Sets the *search string* query property to the given value. + pub fn search_string(mut self, new_value: &str) -> ChangeLogListCall<'a, C, A> { + self._search_string = Some(new_value.to_string()); + self + } + /// Value of the nextPageToken from the previous result page. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> ChangeLogListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Select only change logs with the specified object type. + /// + /// Sets the *object type* query property to the given value. + pub fn object_type(mut self, new_value: &str) -> ChangeLogListCall<'a, C, A> { + self._object_type = Some(new_value.to_string()); + self + } + /// Select only change logs with these object IDs. + /// + /// 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. + pub fn add_object_ids(mut self, new_value: &str) -> ChangeLogListCall<'a, C, A> { + self._object_ids.push(new_value.to_string()); + self + } + /// 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. + /// + /// Sets the *min change time* query property to the given value. + pub fn min_change_time(mut self, new_value: &str) -> ChangeLogListCall<'a, C, A> { + self._min_change_time = Some(new_value.to_string()); + self + } + /// Maximum number of results to return. + /// + /// Sets the *max results* query property to the given value. + pub fn max_results(mut self, new_value: i32) -> ChangeLogListCall<'a, C, A> { + self._max_results = Some(new_value); + self + } + /// 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. + /// + /// Sets the *max change time* query property to the given value. + pub fn max_change_time(mut self, new_value: &str) -> ChangeLogListCall<'a, C, A> { + self._max_change_time = Some(new_value.to_string()); + self + } + /// Select only change logs with these IDs. + /// + /// 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. + pub fn add_ids(mut self, new_value: &str) -> ChangeLogListCall<'a, C, A> { + self._ids.push(new_value.to_string()); + self + } + /// Select only change logs with the specified action. + /// + /// Sets the *action* query property to the given value. + pub fn action(mut self, new_value: &str) -> ChangeLogListCall<'a, C, A> { + self._action = Some(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ChangeLogListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ChangeLogGetCall<'a, C, A> {} + +impl<'a, C, A> ChangeLogGetCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/changeLogs/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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 ["id", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> ChangeLogGetCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Change log ID. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> ChangeLogGetCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ChangeLogGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Gets one remarketing list share by remarketing list ID. +/// +/// A builder for the *get* method supported by a *remarketingListShare* resource. +/// It is not used directly, but through a `RemarketingListShareMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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.remarketing_list_shares().get("profileId", "remarketingListId") +/// .doit(); +/// # } +/// ``` +pub struct RemarketingListShareGetCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _remarketing_list_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for RemarketingListShareGetCall<'a, C, A> {} + +impl<'a, C, A> RemarketingListShareGetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, RemarketingListShare)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.remarketingListShares.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(("remarketingListId", self._remarketing_list_id.to_string())); + for &field in ["alt", "profileId", "remarketingListId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/remarketingListShares/{remarketingListId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId"), ("{remarketingListId}", "remarketingListId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["remarketingListId", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> RemarketingListShareGetCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Remarketing list ID. + /// + /// Sets the *remarketing list id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn remarketing_list_id(mut self, new_value: &str) -> RemarketingListShareGetCall<'a, C, A> { + self._remarketing_list_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> RemarketingListShareGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> RemarketingListShareGetCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> RemarketingListShareGetCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Updates an existing remarketing list share. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *remarketingListShare* resource. +/// It is not used directly, but through a `RemarketingListShareMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::RemarketingListShare; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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 = RemarketingListShare::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.remarketing_list_shares().patch(req, "profileId", "remarketingListId") +/// .doit(); +/// # } +/// ``` +pub struct RemarketingListSharePatchCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: RemarketingListShare, + _profile_id: String, + _remarketing_list_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for RemarketingListSharePatchCall<'a, C, A> {} + +impl<'a, C, A> RemarketingListSharePatchCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, RemarketingListShare)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.remarketingListShares.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(("remarketingListId", self._remarketing_list_id.to_string())); + for &field in ["alt", "profileId", "remarketingListId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/remarketingListShares".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: RemarketingListShare) -> RemarketingListSharePatchCall<'a, C, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> RemarketingListSharePatchCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Remarketing list ID. + /// + /// Sets the *remarketing list 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. + pub fn remarketing_list_id(mut self, new_value: &str) -> RemarketingListSharePatchCall<'a, C, A> { + self._remarketing_list_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> RemarketingListSharePatchCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> RemarketingListSharePatchCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> RemarketingListSharePatchCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Updates an existing remarketing list share. +/// +/// A builder for the *update* method supported by a *remarketingListShare* resource. +/// It is not used directly, but through a `RemarketingListShareMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::RemarketingListShare; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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 = RemarketingListShare::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.remarketing_list_shares().update(req, "profileId") +/// .doit(); +/// # } +/// ``` +pub struct RemarketingListShareUpdateCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: RemarketingListShare, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for RemarketingListShareUpdateCall<'a, C, A> {} + +impl<'a, C, A> RemarketingListShareUpdateCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, RemarketingListShare)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.remarketingListShares.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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/remarketingListShares".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: RemarketingListShare) -> RemarketingListShareUpdateCall<'a, C, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> RemarketingListShareUpdateCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> RemarketingListShareUpdateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> RemarketingListShareUpdateCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> RemarketingListShareUpdateCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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, A> + where C: '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, A> CallBuilder for ReportRunCall<'a, C, A> {} + +impl<'a, C, A> ReportRunCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/reports/{reportId}/run".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_ref().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 ["reportId", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The DFA profile ID. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> ReportRunCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// The ID of the report. + /// + /// 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. + pub fn report_id(mut self, new_value: &str) -> ReportRunCall<'a, C, A> { + self._report_id = new_value.to_string(); + self + } + /// If set and true, tries to run the report synchronously. + /// + /// Sets the *synchronous* query property to the given value. + pub fn synchronous(mut self, new_value: bool) -> ReportRunCall<'a, C, A> { + self._synchronous = Some(new_value); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ReportRunCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Full`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::Report; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: '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, A> CallBuilder for ReportPatchCall<'a, C, A> {} + +impl<'a, C, A> ReportPatchCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/reports/{reportId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_ref().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 ["reportId", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// The DFA user profile ID. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> ReportPatchCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// The ID of the report. + /// + /// 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. + pub fn report_id(mut self, new_value: &str) -> ReportPatchCall<'a, C, A> { + self._report_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ReportPatchCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Full`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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("clita") +/// .page_token("diam") +/// .max_results(-71) +/// .doit(); +/// # } +/// ``` +pub struct ReportFileListCall<'a, C, A> + where C: '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, A> CallBuilder for ReportFileListCall<'a, C, A> {} + +impl<'a, C, A> ReportFileListCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/reports/{reportId}/files".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_ref().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 ["reportId", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The DFA profile ID. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> ReportFileListCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// The ID of the parent report. + /// + /// 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. + pub fn report_id(mut self, new_value: &str) -> ReportFileListCall<'a, C, A> { + self._report_id = new_value.to_string(); + self + } + /// Order of sorted results, default is 'DESCENDING'. + /// + /// Sets the *sort order* query property to the given value. + pub fn sort_order(mut self, new_value: &str) -> ReportFileListCall<'a, C, A> { + self._sort_order = Some(new_value.to_string()); + self + } + /// The field by which to sort the list. + /// + /// Sets the *sort field* query property to the given value. + pub fn sort_field(mut self, new_value: &str) -> ReportFileListCall<'a, C, A> { + self._sort_field = Some(new_value.to_string()); + self + } + /// The value of the nextToken from the previous result page. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> ReportFileListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Maximum number of results to return. + /// + /// Sets the *max results* query property to the given value. + pub fn max_results(mut self, new_value: i32) -> ReportFileListCall<'a, C, A> { + self._max_results = Some(new_value); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ReportFileListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Full`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::Report; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: Report, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ReportInsertCall<'a, C, A> {} + +impl<'a, C, A> ReportInsertCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/reports".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// The DFA user profile ID. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> ReportInsertCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ReportInsertCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Full`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::Report; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: '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, A> CallBuilder for ReportUpdateCall<'a, C, A> {} + +impl<'a, C, A> ReportUpdateCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/reports/{reportId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_ref().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 ["reportId", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// The DFA user profile ID. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> ReportUpdateCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// The ID of the report. + /// + /// 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. + pub fn report_id(mut self, new_value: &str) -> ReportUpdateCall<'a, C, A> { + self._report_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ReportUpdateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Full`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::Report; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: Report, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ReportCompatibleFieldQueryCall<'a, C, A> {} + +impl<'a, C, A> ReportCompatibleFieldQueryCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/reports/compatiblefields/query".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// The DFA user profile ID. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> ReportCompatibleFieldQueryCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ReportCompatibleFieldQueryCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Full`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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, A> + where C: '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, A> CallBuilder for ReportGetCall<'a, C, A> {} + +impl<'a, C, A> ReportGetCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/reports/{reportId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_ref().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 ["reportId", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The DFA user profile ID. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> ReportGetCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// The ID of the report. + /// + /// 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. + pub fn report_id(mut self, new_value: &str) -> ReportGetCall<'a, C, A> { + self._report_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ReportGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Full`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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, A> + where C: '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, A> CallBuilder for ReportFileGetCall<'a, C, A> {} + +impl<'a, C, A> ReportFileGetCall<'a, C, A> where 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 Err(Error::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 >::as_ref(&value) != "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.2/userprofiles/{profileId}/reports/{reportId}/files/{fileId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_ref().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 ["fileId", "reportId", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + 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 Err(Error::JsonDecodeError(json_response, err)); + } + } + } else { (res, Default::default()) }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The DFA profile ID. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> ReportFileGetCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// The ID of the report. + /// + /// 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. + pub fn report_id(mut self, new_value: &str) -> ReportFileGetCall<'a, C, A> { + self._report_id = new_value.to_string(); + self + } + /// The ID of the report file. + /// + /// 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. + pub fn file_id(mut self, new_value: &str) -> ReportFileGetCall<'a, C, A> { + self._file_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ReportFileGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Full`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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, A> + where C: '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, A> CallBuilder for ReportDeleteCall<'a, C, A> {} + +impl<'a, C, A> ReportDeleteCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/dfareporting/v2.2/userprofiles/{profileId}/reports/{reportId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_ref().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 ["reportId", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = res; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The DFA user profile ID. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> ReportDeleteCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// The ID of the report. + /// + /// 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. + pub fn report_id(mut self, new_value: &str) -> ReportDeleteCall<'a, C, A> { + self._report_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ReportDeleteCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Full`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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("et") +/// .sort_field("dolor") +/// .scope("diam") +/// .page_token("kasd") +/// .max_results(-87) +/// .doit(); +/// # } +/// ``` +pub struct ReportListCall<'a, C, A> + where C: '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, A> CallBuilder for ReportListCall<'a, C, A> {} + +impl<'a, C, A> ReportListCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/reports".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The DFA user profile ID. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> ReportListCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Order of sorted results, default is 'DESCENDING'. + /// + /// Sets the *sort order* query property to the given value. + pub fn sort_order(mut self, new_value: &str) -> ReportListCall<'a, C, A> { + self._sort_order = Some(new_value.to_string()); + self + } + /// The field by which to sort the list. + /// + /// Sets the *sort field* query property to the given value. + pub fn sort_field(mut self, new_value: &str) -> ReportListCall<'a, C, A> { + self._sort_field = Some(new_value.to_string()); + self + } + /// The scope that defines which results are returned, default is 'MINE'. + /// + /// Sets the *scope* query property to the given value. + pub fn scope(mut self, new_value: &str) -> ReportListCall<'a, C, A> { + self._scope = Some(new_value.to_string()); + self + } + /// The value of the nextToken from the previous result page. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> ReportListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Maximum number of results to return. + /// + /// Sets the *max results* query property to the given value. + pub fn max_results(mut self, new_value: i32) -> ReportListCall<'a, C, A> { + self._max_results = Some(new_value); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ReportListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Full`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::Advertiser; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: Advertiser, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for AdvertiserInsertCall<'a, C, A> {} + +impl<'a, C, A> AdvertiserInsertCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/advertisers".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> AdvertiserInsertCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AdvertiserInsertCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::Advertiser; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: '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, A> CallBuilder for AdvertiserPatchCall<'a, C, A> {} + +impl<'a, C, A> AdvertiserPatchCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/advertisers".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> AdvertiserPatchCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Advertiser ID. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> AdvertiserPatchCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AdvertiserPatchCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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("eirmod") +/// .status("At") +/// .sort_order("consetetur") +/// .sort_field("et") +/// .search_string("sed") +/// .page_token("sit") +/// .only_parent(true) +/// .max_results(-43) +/// .include_advertisers_without_groups_only(false) +/// .add_ids("rebum.") +/// .add_floodlight_configuration_ids("Lorem") +/// .add_advertiser_group_ids("Lorem") +/// .doit(); +/// # } +/// ``` +pub struct AdvertiserListCall<'a, C, A> + where C: '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, A> CallBuilder for AdvertiserListCall<'a, C, A> {} + +impl<'a, C, A> AdvertiserListCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/advertisers".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> AdvertiserListCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Select only advertisers with these subaccount IDs. + /// + /// Sets the *subaccount id* query property to the given value. + pub fn subaccount_id(mut self, new_value: &str) -> AdvertiserListCall<'a, C, A> { + self._subaccount_id = Some(new_value.to_string()); + self + } + /// Select only advertisers with the specified status. + /// + /// Sets the *status* query property to the given value. + pub fn status(mut self, new_value: &str) -> AdvertiserListCall<'a, C, A> { + self._status = Some(new_value.to_string()); + self + } + /// Order of sorted results, default is ASCENDING. + /// + /// Sets the *sort order* query property to the given value. + pub fn sort_order(mut self, new_value: &str) -> AdvertiserListCall<'a, C, A> { + self._sort_order = Some(new_value.to_string()); + self + } + /// Field by which to sort the list. + /// + /// Sets the *sort field* query property to the given value. + pub fn sort_field(mut self, new_value: &str) -> AdvertiserListCall<'a, C, A> { + self._sort_field = Some(new_value.to_string()); + self + } + /// 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". + /// + /// Sets the *search string* query property to the given value. + pub fn search_string(mut self, new_value: &str) -> AdvertiserListCall<'a, C, A> { + self._search_string = Some(new_value.to_string()); + self + } + /// Value of the nextPageToken from the previous result page. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> AdvertiserListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Select only advertisers which use another advertiser's floodlight configuration. + /// + /// Sets the *only parent* query property to the given value. + pub fn only_parent(mut self, new_value: bool) -> AdvertiserListCall<'a, C, A> { + self._only_parent = Some(new_value); + self + } + /// Maximum number of results to return. + /// + /// Sets the *max results* query property to the given value. + pub fn max_results(mut self, new_value: i32) -> AdvertiserListCall<'a, C, A> { + self._max_results = Some(new_value); + self + } + /// Select only advertisers which do not belong to any advertiser group. + /// + /// Sets the *include advertisers without groups only* query property to the given value. + pub fn include_advertisers_without_groups_only(mut self, new_value: bool) -> AdvertiserListCall<'a, C, A> { + self._include_advertisers_without_groups_only = Some(new_value); + self + } + /// Select only advertisers with these IDs. + /// + /// 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. + pub fn add_ids(mut self, new_value: &str) -> AdvertiserListCall<'a, C, A> { + self._ids.push(new_value.to_string()); + self + } + /// Select only advertisers with these floodlight configuration IDs. + /// + /// 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. + pub fn add_floodlight_configuration_ids(mut self, new_value: &str) -> AdvertiserListCall<'a, C, A> { + self._floodlight_configuration_ids.push(new_value.to_string()); + self + } + /// Select only advertisers with these advertiser group IDs. + /// + /// 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. + pub fn add_advertiser_group_ids(mut self, new_value: &str) -> AdvertiserListCall<'a, C, A> { + self._advertiser_group_ids.push(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AdvertiserListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::Advertiser; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: Advertiser, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for AdvertiserUpdateCall<'a, C, A> {} + +impl<'a, C, A> AdvertiserUpdateCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/advertisers".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> AdvertiserUpdateCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AdvertiserUpdateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for AdvertiserGetCall<'a, C, A> {} + +impl<'a, C, A> AdvertiserGetCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/advertisers/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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 ["id", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> AdvertiserGetCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Advertiser ID. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> AdvertiserGetCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AdvertiserGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::DimensionValueRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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("ipsum") +/// .max_results(-87) +/// .doit(); +/// # } +/// ``` +pub struct DimensionValueQueryCall<'a, C, A> + where C: '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, A> CallBuilder for DimensionValueQueryCall<'a, C, A> {} + +impl<'a, C, A> DimensionValueQueryCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/dimensionvalues/query".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// The DFA user profile ID. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> DimensionValueQueryCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// The value of the nextToken from the previous result page. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> DimensionValueQueryCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Maximum number of results to return. + /// + /// Sets the *max results* query property to the given value. + pub fn max_results(mut self, new_value: i32) -> DimensionValueQueryCall<'a, C, A> { + self._max_results = Some(new_value); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DimensionValueQueryCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Full`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for FloodlightActivityGroupDeleteCall<'a, C, A> {} + +impl<'a, C, A> FloodlightActivityGroupDeleteCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/dfareporting/v2.2/userprofiles/{profileId}/floodlightActivityGroups/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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 ["id", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = res; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> FloodlightActivityGroupDeleteCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Floodlight activity Group ID. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> FloodlightActivityGroupDeleteCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> FloodlightActivityGroupDeleteCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for FloodlightActivityGroupGetCall<'a, C, A> {} + +impl<'a, C, A> FloodlightActivityGroupGetCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/floodlightActivityGroups/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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 ["id", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> FloodlightActivityGroupGetCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Floodlight activity Group ID. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> FloodlightActivityGroupGetCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> FloodlightActivityGroupGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::FloodlightActivityGroup; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: '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, A> CallBuilder for FloodlightActivityGroupPatchCall<'a, C, A> {} + +impl<'a, C, A> FloodlightActivityGroupPatchCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/floodlightActivityGroups".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> FloodlightActivityGroupPatchCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Floodlight activity Group ID. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> FloodlightActivityGroupPatchCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> FloodlightActivityGroupPatchCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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_("et") +/// .sort_order("et") +/// .sort_field("vero") +/// .search_string("ut") +/// .page_token("sed") +/// .max_results(-21) +/// .add_ids("ipsum") +/// .floodlight_configuration_id("justo") +/// .advertiser_id("dolore") +/// .doit(); +/// # } +/// ``` +pub struct FloodlightActivityGroupListCall<'a, C, A> + where C: '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, A> CallBuilder for FloodlightActivityGroupListCall<'a, C, A> {} + +impl<'a, C, A> FloodlightActivityGroupListCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/floodlightActivityGroups".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> FloodlightActivityGroupListCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Select only floodlight activity groups with the specified floodlight activity group type. + /// + /// Sets the *type* query property to the given value. + pub fn type_(mut self, new_value: &str) -> FloodlightActivityGroupListCall<'a, C, A> { + self._type_ = Some(new_value.to_string()); + self + } + /// Order of sorted results, default is ASCENDING. + /// + /// Sets the *sort order* query property to the given value. + pub fn sort_order(mut self, new_value: &str) -> FloodlightActivityGroupListCall<'a, C, A> { + self._sort_order = Some(new_value.to_string()); + self + } + /// Field by which to sort the list. + /// + /// Sets the *sort field* query property to the given value. + pub fn sort_field(mut self, new_value: &str) -> FloodlightActivityGroupListCall<'a, C, A> { + self._sort_field = Some(new_value.to_string()); + self + } + /// 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". + /// + /// Sets the *search string* query property to the given value. + pub fn search_string(mut self, new_value: &str) -> FloodlightActivityGroupListCall<'a, C, A> { + self._search_string = Some(new_value.to_string()); + self + } + /// Value of the nextPageToken from the previous result page. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> FloodlightActivityGroupListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Maximum number of results to return. + /// + /// Sets the *max results* query property to the given value. + pub fn max_results(mut self, new_value: i32) -> FloodlightActivityGroupListCall<'a, C, A> { + self._max_results = Some(new_value); + self + } + /// Select only floodlight activity groups with the specified IDs. Must specify either advertiserId or floodlightConfigurationId for a non-empty result. + /// + /// 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. + pub fn add_ids(mut self, new_value: &str) -> FloodlightActivityGroupListCall<'a, C, A> { + self._ids.push(new_value.to_string()); + self + } + /// Select only floodlight activity groups with the specified floodlight configuration ID. Must specify either advertiserId, or floodlightConfigurationId for a non-empty result. + /// + /// Sets the *floodlight configuration id* query property to the given value. + pub fn floodlight_configuration_id(mut self, new_value: &str) -> FloodlightActivityGroupListCall<'a, C, A> { + self._floodlight_configuration_id = Some(new_value.to_string()); + self + } + /// Select only floodlight activity groups with the specified advertiser ID. Must specify either advertiserId or floodlightConfigurationId for a non-empty result. + /// + /// Sets the *advertiser id* query property to the given value. + pub fn advertiser_id(mut self, new_value: &str) -> FloodlightActivityGroupListCall<'a, C, A> { + self._advertiser_id = Some(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> FloodlightActivityGroupListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::FloodlightActivityGroup; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: FloodlightActivityGroup, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for FloodlightActivityGroupInsertCall<'a, C, A> {} + +impl<'a, C, A> FloodlightActivityGroupInsertCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/floodlightActivityGroups".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> FloodlightActivityGroupInsertCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> FloodlightActivityGroupInsertCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::FloodlightActivityGroup; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: FloodlightActivityGroup, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for FloodlightActivityGroupUpdateCall<'a, C, A> {} + +impl<'a, C, A> FloodlightActivityGroupUpdateCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/floodlightActivityGroups".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> FloodlightActivityGroupUpdateCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> FloodlightActivityGroupUpdateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for MetroListCall<'a, C, A> {} + +impl<'a, C, A> MetroListCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/metros".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> MetroListCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> MetroListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Retrieves a list of orders, possibly filtered. +/// +/// A builder for the *list* method supported by a *order* resource. +/// It is not used directly, but through a `OrderMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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.orders().list("profileId", "projectId") +/// .sort_order("et") +/// .sort_field("sed") +/// .add_site_id("no") +/// .search_string("invidunt") +/// .page_token("rebum.") +/// .max_results(-86) +/// .add_ids("aliquyam") +/// .doit(); +/// # } +/// ``` +pub struct OrderListCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _project_id: String, + _sort_order: Option, + _sort_field: Option, + _site_id: Vec, + _search_string: Option, + _page_token: Option, + _max_results: Option, + _ids: Vec, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for OrderListCall<'a, C, A> {} + +impl<'a, C, A> OrderListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, OrdersListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.orders.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())); + params.push(("projectId", self._project_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_id.len() > 0 { + let mut s = String::new(); + for f in self._site_id.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("siteId", 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._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", "projectId", "sortOrder", "sortField", "siteId", "searchString", "pageToken", "maxResults", "ids"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/projects/{projectId}/orders".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId"), ("{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(2); + for param_name in ["projectId", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> OrderListCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Project ID for orders. + /// + /// 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. + pub fn project_id(mut self, new_value: &str) -> OrderListCall<'a, C, A> { + self._project_id = new_value.to_string(); + self + } + /// Order of sorted results, default is ASCENDING. + /// + /// Sets the *sort order* query property to the given value. + pub fn sort_order(mut self, new_value: &str) -> OrderListCall<'a, C, A> { + self._sort_order = Some(new_value.to_string()); + self + } + /// Field by which to sort the list. + /// + /// Sets the *sort field* query property to the given value. + pub fn sort_field(mut self, new_value: &str) -> OrderListCall<'a, C, A> { + self._sort_field = Some(new_value.to_string()); + self + } + /// Select only orders that are associated with these site IDs. + /// + /// Append the given value to the *site id* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + pub fn add_site_id(mut self, new_value: &str) -> OrderListCall<'a, C, A> { + self._site_id.push(new_value.to_string()); + self + } + /// Allows searching for orders by name or ID. Wildcards (*) are allowed. For example, "order*2015" will return orders with names like "order June 2015", "order April 2015", or simply "order 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 "order" will match orders with name "my order", "order 2015", or simply "order". + /// + /// Sets the *search string* query property to the given value. + pub fn search_string(mut self, new_value: &str) -> OrderListCall<'a, C, A> { + self._search_string = Some(new_value.to_string()); + self + } + /// Value of the nextPageToken from the previous result page. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> OrderListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Maximum number of results to return. + /// + /// Sets the *max results* query property to the given value. + pub fn max_results(mut self, new_value: i32) -> OrderListCall<'a, C, A> { + self._max_results = Some(new_value); + self + } + /// Select only orders with these IDs. + /// + /// 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. + pub fn add_ids(mut self, new_value: &str) -> OrderListCall<'a, C, A> { + self._ids.push(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> OrderListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> OrderListCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> OrderListCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Gets one order by ID. +/// +/// A builder for the *get* method supported by a *order* resource. +/// It is not used directly, but through a `OrderMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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.orders().get("profileId", "projectId", "id") +/// .doit(); +/// # } +/// ``` +pub struct OrderGetCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _project_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for OrderGetCall<'a, C, A> {} + +impl<'a, C, A> OrderGetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Order)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.orders.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(("projectId", self._project_id.to_string())); + params.push(("id", self._id.to_string())); + for &field in ["alt", "profileId", "projectId", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/projects/{projectId}/orders/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId"), ("{projectId}", "projectId"), ("{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 ["id", "projectId", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> OrderGetCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Project ID for orders. + /// + /// 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. + pub fn project_id(mut self, new_value: &str) -> OrderGetCall<'a, C, A> { + self._project_id = new_value.to_string(); + self + } + /// Order ID. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> OrderGetCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> OrderGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> OrderGetCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> OrderGetCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for DirectorySiteContactGetCall<'a, C, A> {} + +impl<'a, C, A> DirectorySiteContactGetCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/directorySiteContacts/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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 ["id", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> DirectorySiteContactGetCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Directory site contact ID. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> DirectorySiteContactGetCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DirectorySiteContactGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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("consetetur") +/// .sort_field("diam") +/// .search_string("accusam") +/// .page_token("dolores") +/// .max_results(-46) +/// .add_ids("dolor") +/// .add_directory_site_ids("aliquyam") +/// .doit(); +/// # } +/// ``` +pub struct DirectorySiteContactListCall<'a, C, A> + where C: '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, A> CallBuilder for DirectorySiteContactListCall<'a, C, A> {} + +impl<'a, C, A> DirectorySiteContactListCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/directorySiteContacts".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> DirectorySiteContactListCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Order of sorted results, default is ASCENDING. + /// + /// Sets the *sort order* query property to the given value. + pub fn sort_order(mut self, new_value: &str) -> DirectorySiteContactListCall<'a, C, A> { + self._sort_order = Some(new_value.to_string()); + self + } + /// Field by which to sort the list. + /// + /// Sets the *sort field* query property to the given value. + pub fn sort_field(mut self, new_value: &str) -> DirectorySiteContactListCall<'a, C, A> { + self._sort_field = Some(new_value.to_string()); + self + } + /// 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". + /// + /// Sets the *search string* query property to the given value. + pub fn search_string(mut self, new_value: &str) -> DirectorySiteContactListCall<'a, C, A> { + self._search_string = Some(new_value.to_string()); + self + } + /// Value of the nextPageToken from the previous result page. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> DirectorySiteContactListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Maximum number of results to return. + /// + /// Sets the *max results* query property to the given value. + pub fn max_results(mut self, new_value: i32) -> DirectorySiteContactListCall<'a, C, A> { + self._max_results = Some(new_value); + self + } + /// Select only directory site contacts with these IDs. + /// + /// 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. + pub fn add_ids(mut self, new_value: &str) -> DirectorySiteContactListCall<'a, C, A> { + self._ids.push(new_value.to_string()); + self + } + /// Select only directory site contacts with these directory site IDs. This is a required field. + /// + /// 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. + pub fn add_directory_site_ids(mut self, new_value: &str) -> DirectorySiteContactListCall<'a, C, A> { + self._directory_site_ids.push(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DirectorySiteContactListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for UserProfileListCall<'a, C, A> {} + +impl<'a, C, A> UserProfileListCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_ref().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserProfileListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Full`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for UserProfileGetCall<'a, C, A> {} + +impl<'a, C, A> UserProfileGetCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The user profile ID. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> UserProfileGetCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserProfileGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Full`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::Ad; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: '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, A> CallBuilder for AdPatchCall<'a, C, A> {} + +impl<'a, C, A> AdPatchCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/ads".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> AdPatchCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Ad ID. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> AdPatchCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AdPatchCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::Ad; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: Ad, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for AdInsertCall<'a, C, A> {} + +impl<'a, C, A> AdInsertCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/ads".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> AdInsertCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AdInsertCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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("dolor") +/// .ssl_required(true) +/// .ssl_compliant(true) +/// .sort_order("Lorem") +/// .sort_field("consetetur") +/// .add_size_ids("consetetur") +/// .search_string("eirmod") +/// .add_remarketing_list_ids("labore") +/// .add_placement_ids("gubergren") +/// .page_token("et") +/// .overridden_event_tag_id("sadipscing") +/// .max_results(-73) +/// .add_landing_page_ids("magna") +/// .add_ids("Lorem") +/// .dynamic_click_tracker(true) +/// .creative_type("et") +/// .add_creative_optimization_configuration_ids("clita") +/// .add_creative_ids("eos") +/// .compatibility("dolores") +/// .add_campaign_ids("vero") +/// .add_audience_segment_ids("consetetur") +/// .archived(true) +/// .advertiser_id("consetetur") +/// .active(true) +/// .doit(); +/// # } +/// ``` +pub struct AdListCall<'a, C, A> + where C: '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, A> CallBuilder for AdListCall<'a, C, A> {} + +impl<'a, C, A> AdListCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/ads".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> AdListCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Select only ads with these types. + /// + /// 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. + pub fn add_type(mut self, new_value: &str) -> AdListCall<'a, C, A> { + self._type_.push(new_value.to_string()); + self + } + /// Select only ads that require SSL. + /// + /// Sets the *ssl required* query property to the given value. + pub fn ssl_required(mut self, new_value: bool) -> AdListCall<'a, C, A> { + self._ssl_required = Some(new_value); + self + } + /// Select only ads that are SSL-compliant. + /// + /// Sets the *ssl compliant* query property to the given value. + pub fn ssl_compliant(mut self, new_value: bool) -> AdListCall<'a, C, A> { + self._ssl_compliant = Some(new_value); + self + } + /// Order of sorted results, default is ASCENDING. + /// + /// Sets the *sort order* query property to the given value. + pub fn sort_order(mut self, new_value: &str) -> AdListCall<'a, C, A> { + self._sort_order = Some(new_value.to_string()); + self + } + /// Field by which to sort the list. + /// + /// Sets the *sort field* query property to the given value. + pub fn sort_field(mut self, new_value: &str) -> AdListCall<'a, C, A> { + self._sort_field = Some(new_value.to_string()); + self + } + /// Select only ads with these size IDs. + /// + /// 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. + pub fn add_size_ids(mut self, new_value: &str) -> AdListCall<'a, C, A> { + self._size_ids.push(new_value.to_string()); + self + } + /// 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". + /// + /// Sets the *search string* query property to the given value. + pub fn search_string(mut self, new_value: &str) -> AdListCall<'a, C, A> { + self._search_string = Some(new_value.to_string()); + self + } + /// Select only ads whose list targeting expression use these remarketing list IDs. + /// + /// 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. + pub fn add_remarketing_list_ids(mut self, new_value: &str) -> AdListCall<'a, C, A> { + self._remarketing_list_ids.push(new_value.to_string()); + self + } + /// Select only ads with these placement IDs assigned. + /// + /// 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. + pub fn add_placement_ids(mut self, new_value: &str) -> AdListCall<'a, C, A> { + self._placement_ids.push(new_value.to_string()); + self + } + /// Value of the nextPageToken from the previous result page. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> AdListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Select only ads with this event tag override ID. + /// + /// Sets the *overridden event tag id* query property to the given value. + pub fn overridden_event_tag_id(mut self, new_value: &str) -> AdListCall<'a, C, A> { + self._overridden_event_tag_id = Some(new_value.to_string()); + self + } + /// Maximum number of results to return. + /// + /// Sets the *max results* query property to the given value. + pub fn max_results(mut self, new_value: i32) -> AdListCall<'a, C, A> { + self._max_results = Some(new_value); + self + } + /// Select only ads with these landing page IDs. + /// + /// 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. + pub fn add_landing_page_ids(mut self, new_value: &str) -> AdListCall<'a, C, A> { + self._landing_page_ids.push(new_value.to_string()); + self + } + /// Select only ads with these IDs. + /// + /// 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. + pub fn add_ids(mut self, new_value: &str) -> AdListCall<'a, C, A> { + self._ids.push(new_value.to_string()); + self + } + /// 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. + /// + /// Sets the *dynamic click tracker* query property to the given value. + pub fn dynamic_click_tracker(mut self, new_value: bool) -> AdListCall<'a, C, A> { + self._dynamic_click_tracker = Some(new_value); + self + } + /// Select only ads with the specified creativeType. + /// + /// Sets the *creative type* query property to the given value. + pub fn creative_type(mut self, new_value: &str) -> AdListCall<'a, C, A> { + self._creative_type = Some(new_value.to_string()); + self + } + /// Select only ads with these creative optimization configuration IDs. + /// + /// 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. + pub fn add_creative_optimization_configuration_ids(mut self, new_value: &str) -> AdListCall<'a, C, A> { + self._creative_optimization_configuration_ids.push(new_value.to_string()); + self + } + /// Select only ads with these creative IDs assigned. + /// + /// 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. + pub fn add_creative_ids(mut self, new_value: &str) -> AdListCall<'a, C, A> { + self._creative_ids.push(new_value.to_string()); + self + } + /// 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. + /// + /// Sets the *compatibility* query property to the given value. + pub fn compatibility(mut self, new_value: &str) -> AdListCall<'a, C, A> { + self._compatibility = Some(new_value.to_string()); + self + } + /// Select only ads with these campaign IDs. + /// + /// 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. + pub fn add_campaign_ids(mut self, new_value: &str) -> AdListCall<'a, C, A> { + self._campaign_ids.push(new_value.to_string()); + self + } + /// Select only ads with these audience segment IDs. + /// + /// 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. + pub fn add_audience_segment_ids(mut self, new_value: &str) -> AdListCall<'a, C, A> { + self._audience_segment_ids.push(new_value.to_string()); + self + } + /// Select only archived ads. + /// + /// Sets the *archived* query property to the given value. + pub fn archived(mut self, new_value: bool) -> AdListCall<'a, C, A> { + self._archived = Some(new_value); + self + } + /// Select only ads with this advertiser ID. + /// + /// Sets the *advertiser id* query property to the given value. + pub fn advertiser_id(mut self, new_value: &str) -> AdListCall<'a, C, A> { + self._advertiser_id = Some(new_value.to_string()); + self + } + /// Select only active ads. + /// + /// Sets the *active* query property to the given value. + pub fn active(mut self, new_value: bool) -> AdListCall<'a, C, A> { + self._active = Some(new_value); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AdListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for AdGetCall<'a, C, A> {} + +impl<'a, C, A> AdGetCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/ads/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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 ["id", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> AdGetCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Ad ID. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> AdGetCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AdGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::Ad; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: Ad, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for AdUpdateCall<'a, C, A> {} + +impl<'a, C, A> AdUpdateCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/ads".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> AdUpdateCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AdUpdateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for AccountPermissionGetCall<'a, C, A> {} + +impl<'a, C, A> AccountPermissionGetCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/accountPermissions/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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 ["id", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> AccountPermissionGetCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Account permission ID. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> AccountPermissionGetCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountPermissionGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for AccountPermissionListCall<'a, C, A> {} + +impl<'a, C, A> AccountPermissionListCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/accountPermissions".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> AccountPermissionListCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountPermissionListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ConnectionTypeListCall<'a, C, A> {} + +impl<'a, C, A> ConnectionTypeListCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/connectionTypes".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> ConnectionTypeListCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ConnectionTypeListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Gets one connection type by ID. +/// +/// A builder for the *get* method supported by a *connectionType* resource. +/// It is not used directly, but through a `ConnectionTypeMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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().get("profileId", "id") +/// .doit(); +/// # } +/// ``` +pub struct ConnectionTypeGetCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ConnectionTypeGetCall<'a, C, A> {} + +impl<'a, C, A> ConnectionTypeGetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ConnectionType)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/connectionTypes/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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 ["id", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> ConnectionTypeGetCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Connection type ID. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> ConnectionTypeGetCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ConnectionTypeGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> ConnectionTypeGetCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ConnectionTypeGetCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for AdvertiserGroupGetCall<'a, C, A> {} + +impl<'a, C, A> AdvertiserGroupGetCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/advertiserGroups/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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 ["id", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> AdvertiserGroupGetCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Advertiser group ID. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> AdvertiserGroupGetCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AdvertiserGroupGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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("labore") +/// .sort_field("diam") +/// .search_string("nonumy") +/// .page_token("sed") +/// .max_results(-79) +/// .add_ids("magna") +/// .doit(); +/// # } +/// ``` +pub struct AdvertiserGroupListCall<'a, C, A> + where C: '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, A> CallBuilder for AdvertiserGroupListCall<'a, C, A> {} + +impl<'a, C, A> AdvertiserGroupListCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/advertiserGroups".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> AdvertiserGroupListCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Order of sorted results, default is ASCENDING. + /// + /// Sets the *sort order* query property to the given value. + pub fn sort_order(mut self, new_value: &str) -> AdvertiserGroupListCall<'a, C, A> { + self._sort_order = Some(new_value.to_string()); + self + } + /// Field by which to sort the list. + /// + /// Sets the *sort field* query property to the given value. + pub fn sort_field(mut self, new_value: &str) -> AdvertiserGroupListCall<'a, C, A> { + self._sort_field = Some(new_value.to_string()); + self + } + /// 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". + /// + /// Sets the *search string* query property to the given value. + pub fn search_string(mut self, new_value: &str) -> AdvertiserGroupListCall<'a, C, A> { + self._search_string = Some(new_value.to_string()); + self + } + /// Value of the nextPageToken from the previous result page. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> AdvertiserGroupListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Maximum number of results to return. + /// + /// Sets the *max results* query property to the given value. + pub fn max_results(mut self, new_value: i32) -> AdvertiserGroupListCall<'a, C, A> { + self._max_results = Some(new_value); + self + } + /// Select only advertiser groups with these IDs. + /// + /// 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. + pub fn add_ids(mut self, new_value: &str) -> AdvertiserGroupListCall<'a, C, A> { + self._ids.push(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AdvertiserGroupListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::AdvertiserGroup; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: AdvertiserGroup, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for AdvertiserGroupInsertCall<'a, C, A> {} + +impl<'a, C, A> AdvertiserGroupInsertCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/advertiserGroups".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> AdvertiserGroupInsertCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AdvertiserGroupInsertCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::AdvertiserGroup; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: AdvertiserGroup, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for AdvertiserGroupUpdateCall<'a, C, A> {} + +impl<'a, C, A> AdvertiserGroupUpdateCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/advertiserGroups".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> AdvertiserGroupUpdateCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AdvertiserGroupUpdateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::AdvertiserGroup; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: '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, A> CallBuilder for AdvertiserGroupPatchCall<'a, C, A> {} + +impl<'a, C, A> AdvertiserGroupPatchCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/advertiserGroups".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> AdvertiserGroupPatchCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Advertiser group ID. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> AdvertiserGroupPatchCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AdvertiserGroupPatchCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for AdvertiserGroupDeleteCall<'a, C, A> {} + +impl<'a, C, A> AdvertiserGroupDeleteCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/dfareporting/v2.2/userprofiles/{profileId}/advertiserGroups/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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 ["id", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = res; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> AdvertiserGroupDeleteCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Advertiser group ID. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> AdvertiserGroupDeleteCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AdvertiserGroupDeleteCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::Site; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: Site, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for SiteInsertCall<'a, C, A> {} + +impl<'a, C, A> SiteInsertCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/sites".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> SiteInsertCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> SiteInsertCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for SiteGetCall<'a, C, A> {} + +impl<'a, C, A> SiteGetCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/sites/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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 ["id", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> SiteGetCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Site ID. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> SiteGetCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> SiteGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(true) +/// .subaccount_id("dolores") +/// .sort_order("et") +/// .sort_field("sed") +/// .search_string("et") +/// .page_token("aliquyam") +/// .max_results(-91) +/// .add_ids("sit") +/// .add_directory_site_ids("aliquyam") +/// .add_campaign_ids("sadipscing") +/// .approved(true) +/// .ad_words_site(false) +/// .accepts_publisher_paid_placements(false) +/// .accepts_interstitial_placements(false) +/// .accepts_in_stream_video_placements(true) +/// .doit(); +/// # } +/// ``` +pub struct SiteListCall<'a, C, A> + where C: '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, A> CallBuilder for SiteListCall<'a, C, A> {} + +impl<'a, C, A> SiteListCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/sites".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> SiteListCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Select only sites that have not been mapped to a directory site. + /// + /// Sets the *unmapped site* query property to the given value. + pub fn unmapped_site(mut self, new_value: bool) -> SiteListCall<'a, C, A> { + self._unmapped_site = Some(new_value); + self + } + /// Select only sites with this subaccount ID. + /// + /// Sets the *subaccount id* query property to the given value. + pub fn subaccount_id(mut self, new_value: &str) -> SiteListCall<'a, C, A> { + self._subaccount_id = Some(new_value.to_string()); + self + } + /// Order of sorted results, default is ASCENDING. + /// + /// Sets the *sort order* query property to the given value. + pub fn sort_order(mut self, new_value: &str) -> SiteListCall<'a, C, A> { + self._sort_order = Some(new_value.to_string()); + self + } + /// Field by which to sort the list. + /// + /// Sets the *sort field* query property to the given value. + pub fn sort_field(mut self, new_value: &str) -> SiteListCall<'a, C, A> { + self._sort_field = Some(new_value.to_string()); + self + } + /// 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". + /// + /// Sets the *search string* query property to the given value. + pub fn search_string(mut self, new_value: &str) -> SiteListCall<'a, C, A> { + self._search_string = Some(new_value.to_string()); + self + } + /// Value of the nextPageToken from the previous result page. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> SiteListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Maximum number of results to return. + /// + /// Sets the *max results* query property to the given value. + pub fn max_results(mut self, new_value: i32) -> SiteListCall<'a, C, A> { + self._max_results = Some(new_value); + self + } + /// Select only sites with these IDs. + /// + /// 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. + pub fn add_ids(mut self, new_value: &str) -> SiteListCall<'a, C, A> { + self._ids.push(new_value.to_string()); + self + } + /// Select only sites with these directory site IDs. + /// + /// 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. + pub fn add_directory_site_ids(mut self, new_value: &str) -> SiteListCall<'a, C, A> { + self._directory_site_ids.push(new_value.to_string()); + self + } + /// Select only sites with these campaign IDs. + /// + /// 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. + pub fn add_campaign_ids(mut self, new_value: &str) -> SiteListCall<'a, C, A> { + self._campaign_ids.push(new_value.to_string()); + self + } + /// Select only approved sites. + /// + /// Sets the *approved* query property to the given value. + pub fn approved(mut self, new_value: bool) -> SiteListCall<'a, C, A> { + self._approved = Some(new_value); + self + } + /// Select only AdWords sites. + /// + /// Sets the *ad words site* query property to the given value. + pub fn ad_words_site(mut self, new_value: bool) -> SiteListCall<'a, C, A> { + self._ad_words_site = Some(new_value); + self + } + /// Select only sites that accept publisher paid placements. + /// + /// Sets the *accepts publisher paid placements* query property to the given value. + pub fn accepts_publisher_paid_placements(mut self, new_value: bool) -> SiteListCall<'a, C, A> { + self._accepts_publisher_paid_placements = Some(new_value); + self + } + /// This search filter is no longer supported and will have no effect on the results returned. + /// + /// Sets the *accepts interstitial placements* query property to the given value. + pub fn accepts_interstitial_placements(mut self, new_value: bool) -> SiteListCall<'a, C, A> { + self._accepts_interstitial_placements = Some(new_value); + self + } + /// This search filter is no longer supported and will have no effect on the results returned. + /// + /// Sets the *accepts in stream video placements* query property to the given value. + pub fn accepts_in_stream_video_placements(mut self, new_value: bool) -> SiteListCall<'a, C, A> { + self._accepts_in_stream_video_placements = Some(new_value); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> SiteListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::Site; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: Site, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for SiteUpdateCall<'a, C, A> {} + +impl<'a, C, A> SiteUpdateCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/sites".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> SiteUpdateCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> SiteUpdateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::Site; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: '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, A> CallBuilder for SitePatchCall<'a, C, A> {} + +impl<'a, C, A> SitePatchCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/sites".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> SitePatchCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Site ID. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> SitePatchCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> SitePatchCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for FloodlightActivityGetCall<'a, C, A> {} + +impl<'a, C, A> FloodlightActivityGetCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/floodlightActivities/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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 ["id", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> FloodlightActivityGetCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Floodlight activity ID. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> FloodlightActivityGetCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> FloodlightActivityGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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("eirmod") +/// .sort_order("sadipscing") +/// .sort_field("Lorem") +/// .search_string("sed") +/// .page_token("sit") +/// .max_results(-33) +/// .add_ids("et") +/// .floodlight_configuration_id("At") +/// .floodlight_activity_group_type("sit") +/// .floodlight_activity_group_tag_string("ut") +/// .floodlight_activity_group_name("diam") +/// .add_floodlight_activity_group_ids("tempor") +/// .advertiser_id("et") +/// .doit(); +/// # } +/// ``` +pub struct FloodlightActivityListCall<'a, C, A> + where C: '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, A> CallBuilder for FloodlightActivityListCall<'a, C, A> {} + +impl<'a, C, A> FloodlightActivityListCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/floodlightActivities".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> FloodlightActivityListCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Select only floodlight activities with the specified tag string. + /// + /// Sets the *tag string* query property to the given value. + pub fn tag_string(mut self, new_value: &str) -> FloodlightActivityListCall<'a, C, A> { + self._tag_string = Some(new_value.to_string()); + self + } + /// Order of sorted results, default is ASCENDING. + /// + /// Sets the *sort order* query property to the given value. + pub fn sort_order(mut self, new_value: &str) -> FloodlightActivityListCall<'a, C, A> { + self._sort_order = Some(new_value.to_string()); + self + } + /// Field by which to sort the list. + /// + /// Sets the *sort field* query property to the given value. + pub fn sort_field(mut self, new_value: &str) -> FloodlightActivityListCall<'a, C, A> { + self._sort_field = Some(new_value.to_string()); + self + } + /// 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". + /// + /// Sets the *search string* query property to the given value. + pub fn search_string(mut self, new_value: &str) -> FloodlightActivityListCall<'a, C, A> { + self._search_string = Some(new_value.to_string()); + self + } + /// Value of the nextPageToken from the previous result page. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> FloodlightActivityListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Maximum number of results to return. + /// + /// Sets the *max results* query property to the given value. + pub fn max_results(mut self, new_value: i32) -> FloodlightActivityListCall<'a, C, A> { + self._max_results = Some(new_value); + self + } + /// Select only floodlight activities with the specified IDs. Must specify either ids, advertiserId, or floodlightConfigurationId for a non-empty result. + /// + /// 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. + pub fn add_ids(mut self, new_value: &str) -> FloodlightActivityListCall<'a, C, A> { + self._ids.push(new_value.to_string()); + self + } + /// Select only floodlight activities for the specified floodlight configuration ID. Must specify either ids, advertiserId, or floodlightConfigurationId for a non-empty result. + /// + /// Sets the *floodlight configuration id* query property to the given value. + pub fn floodlight_configuration_id(mut self, new_value: &str) -> FloodlightActivityListCall<'a, C, A> { + self._floodlight_configuration_id = Some(new_value.to_string()); + self + } + /// Select only floodlight activities with the specified floodlight activity group type. + /// + /// Sets the *floodlight activity group type* query property to the given value. + pub fn floodlight_activity_group_type(mut self, new_value: &str) -> FloodlightActivityListCall<'a, C, A> { + self._floodlight_activity_group_type = Some(new_value.to_string()); + self + } + /// Select only floodlight activities with the specified floodlight activity group tag string. + /// + /// Sets the *floodlight activity group tag string* query property to the given value. + pub fn floodlight_activity_group_tag_string(mut self, new_value: &str) -> FloodlightActivityListCall<'a, C, A> { + self._floodlight_activity_group_tag_string = Some(new_value.to_string()); + self + } + /// Select only floodlight activities with the specified floodlight activity group name. + /// + /// Sets the *floodlight activity group name* query property to the given value. + pub fn floodlight_activity_group_name(mut self, new_value: &str) -> FloodlightActivityListCall<'a, C, A> { + self._floodlight_activity_group_name = Some(new_value.to_string()); + self + } + /// Select only floodlight activities with the specified floodlight activity group IDs. + /// + /// 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. + pub fn add_floodlight_activity_group_ids(mut self, new_value: &str) -> FloodlightActivityListCall<'a, C, A> { + self._floodlight_activity_group_ids.push(new_value.to_string()); + self + } + /// Select only floodlight activities for the specified advertiser ID. Must specify either ids, advertiserId, or floodlightConfigurationId for a non-empty result. + /// + /// Sets the *advertiser id* query property to the given value. + pub fn advertiser_id(mut self, new_value: &str) -> FloodlightActivityListCall<'a, C, A> { + self._advertiser_id = Some(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> FloodlightActivityListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::FloodlightActivity; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: FloodlightActivity, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for FloodlightActivityInsertCall<'a, C, A> {} + +impl<'a, C, A> FloodlightActivityInsertCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/floodlightActivities".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> FloodlightActivityInsertCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> FloodlightActivityInsertCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for FloodlightActivityDeleteCall<'a, C, A> {} + +impl<'a, C, A> FloodlightActivityDeleteCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/dfareporting/v2.2/userprofiles/{profileId}/floodlightActivities/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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 ["id", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = res; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> FloodlightActivityDeleteCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Floodlight activity ID. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> FloodlightActivityDeleteCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> FloodlightActivityDeleteCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::FloodlightActivity; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: '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, A> CallBuilder for FloodlightActivityPatchCall<'a, C, A> {} + +impl<'a, C, A> FloodlightActivityPatchCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/floodlightActivities".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> FloodlightActivityPatchCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Floodlight activity ID. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> FloodlightActivityPatchCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> FloodlightActivityPatchCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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("dolores") +/// .doit(); +/// # } +/// ``` +pub struct FloodlightActivityGeneratetagCall<'a, C, A> + where C: '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, A> CallBuilder for FloodlightActivityGeneratetagCall<'a, C, A> {} + +impl<'a, C, A> FloodlightActivityGeneratetagCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/floodlightActivities/generatetag".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> FloodlightActivityGeneratetagCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Floodlight activity ID for which we want to generate a tag. + /// + /// Sets the *floodlight activity id* query property to the given value. + pub fn floodlight_activity_id(mut self, new_value: &str) -> FloodlightActivityGeneratetagCall<'a, C, A> { + self._floodlight_activity_id = Some(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> FloodlightActivityGeneratetagCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::FloodlightActivity; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: FloodlightActivity, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for FloodlightActivityUpdateCall<'a, C, A> {} + +impl<'a, C, A> FloodlightActivityUpdateCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/floodlightActivities".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> FloodlightActivityUpdateCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> FloodlightActivityUpdateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for RegionListCall<'a, C, A> {} + +impl<'a, C, A> RegionListCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/regions".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> RegionListCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> RegionListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::CreativeGroup; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: CreativeGroup, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for CreativeGroupInsertCall<'a, C, A> {} + +impl<'a, C, A> CreativeGroupInsertCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/creativeGroups".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> CreativeGroupInsertCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CreativeGroupInsertCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for CreativeGroupGetCall<'a, C, A> {} + +impl<'a, C, A> CreativeGroupGetCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/creativeGroups/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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 ["id", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> CreativeGroupGetCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Creative group ID. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> CreativeGroupGetCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CreativeGroupGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::CreativeGroup; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: CreativeGroup, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for CreativeGroupUpdateCall<'a, C, A> {} + +impl<'a, C, A> CreativeGroupUpdateCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/creativeGroups".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> CreativeGroupUpdateCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CreativeGroupUpdateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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("erat") +/// .search_string("gubergren") +/// .page_token("erat") +/// .max_results(-85) +/// .add_ids("amet") +/// .group_number(-101) +/// .add_advertiser_ids("voluptua.") +/// .doit(); +/// # } +/// ``` +pub struct CreativeGroupListCall<'a, C, A> + where C: '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, A> CallBuilder for CreativeGroupListCall<'a, C, A> {} + +impl<'a, C, A> CreativeGroupListCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/creativeGroups".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> CreativeGroupListCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Order of sorted results, default is ASCENDING. + /// + /// Sets the *sort order* query property to the given value. + pub fn sort_order(mut self, new_value: &str) -> CreativeGroupListCall<'a, C, A> { + self._sort_order = Some(new_value.to_string()); + self + } + /// Field by which to sort the list. + /// + /// Sets the *sort field* query property to the given value. + pub fn sort_field(mut self, new_value: &str) -> CreativeGroupListCall<'a, C, A> { + self._sort_field = Some(new_value.to_string()); + self + } + /// 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". + /// + /// Sets the *search string* query property to the given value. + pub fn search_string(mut self, new_value: &str) -> CreativeGroupListCall<'a, C, A> { + self._search_string = Some(new_value.to_string()); + self + } + /// Value of the nextPageToken from the previous result page. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> CreativeGroupListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Maximum number of results to return. + /// + /// Sets the *max results* query property to the given value. + pub fn max_results(mut self, new_value: i32) -> CreativeGroupListCall<'a, C, A> { + self._max_results = Some(new_value); + self + } + /// Select only creative groups with these IDs. + /// + /// 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. + pub fn add_ids(mut self, new_value: &str) -> CreativeGroupListCall<'a, C, A> { + self._ids.push(new_value.to_string()); + self + } + /// Select only creative groups that belong to this subgroup. + /// + /// Sets the *group number* query property to the given value. + pub fn group_number(mut self, new_value: i32) -> CreativeGroupListCall<'a, C, A> { + self._group_number = Some(new_value); + self + } + /// Select only creative groups that belong to these advertisers. + /// + /// 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. + pub fn add_advertiser_ids(mut self, new_value: &str) -> CreativeGroupListCall<'a, C, A> { + self._advertiser_ids.push(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CreativeGroupListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::CreativeGroup; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: '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, A> CallBuilder for CreativeGroupPatchCall<'a, C, A> {} + +impl<'a, C, A> CreativeGroupPatchCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/creativeGroups".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> CreativeGroupPatchCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Creative group ID. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> CreativeGroupPatchCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CreativeGroupPatchCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Retrieves a list of targetable remarketing lists, possibly filtered. +/// +/// A builder for the *list* method supported by a *targetableRemarketingList* resource. +/// It is not used directly, but through a `TargetableRemarketingListMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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.targetable_remarketing_lists().list("profileId", "advertiserId") +/// .sort_order("takimata") +/// .sort_field("dolor") +/// .page_token("takimata") +/// .name("voluptua.") +/// .max_results(-61) +/// .active(false) +/// .doit(); +/// # } +/// ``` +pub struct TargetableRemarketingListListCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _advertiser_id: String, + _sort_order: Option, + _sort_field: Option, + _page_token: Option, + _name: Option, + _max_results: Option, + _active: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for TargetableRemarketingListListCall<'a, C, A> {} + +impl<'a, C, A> TargetableRemarketingListListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, TargetableRemarketingListsListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.targetableRemarketingLists.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(("advertiserId", self._advertiser_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._name { + params.push(("name", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._active { + params.push(("active", value.to_string())); + } + for &field in ["alt", "profileId", "advertiserId", "sortOrder", "sortField", "pageToken", "name", "maxResults", "active"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/targetableRemarketingLists".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> TargetableRemarketingListListCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Select only targetable remarketing lists targetable by these advertisers. + /// + /// 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. + pub fn advertiser_id(mut self, new_value: &str) -> TargetableRemarketingListListCall<'a, C, A> { + self._advertiser_id = new_value.to_string(); + self + } + /// Order of sorted results, default is ASCENDING. + /// + /// Sets the *sort order* query property to the given value. + pub fn sort_order(mut self, new_value: &str) -> TargetableRemarketingListListCall<'a, C, A> { + self._sort_order = Some(new_value.to_string()); + self + } + /// Field by which to sort the list. + /// + /// Sets the *sort field* query property to the given value. + pub fn sort_field(mut self, new_value: &str) -> TargetableRemarketingListListCall<'a, C, A> { + self._sort_field = Some(new_value.to_string()); + self + } + /// Value of the nextPageToken from the previous result page. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> TargetableRemarketingListListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Allows searching for objects by name or ID. Wildcards (*) are allowed. For example, "remarketing list*2015" will return objects with names like "remarketing list June 2015", "remarketing list April 2015", or simply "remarketing list 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 "remarketing list" will match objects with name "my remarketing list", "remarketing list 2015", or simply "remarketing list". + /// + /// Sets the *name* query property to the given value. + pub fn name(mut self, new_value: &str) -> TargetableRemarketingListListCall<'a, C, A> { + self._name = Some(new_value.to_string()); + self + } + /// Maximum number of results to return. + /// + /// Sets the *max results* query property to the given value. + pub fn max_results(mut self, new_value: i32) -> TargetableRemarketingListListCall<'a, C, A> { + self._max_results = Some(new_value); + self + } + /// Select only active or only inactive targetable remarketing lists. + /// + /// Sets the *active* query property to the given value. + pub fn active(mut self, new_value: bool) -> TargetableRemarketingListListCall<'a, C, A> { + self._active = Some(new_value); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> TargetableRemarketingListListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> TargetableRemarketingListListCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> TargetableRemarketingListListCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Gets one remarketing list by ID. +/// +/// A builder for the *get* method supported by a *targetableRemarketingList* resource. +/// It is not used directly, but through a `TargetableRemarketingListMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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.targetable_remarketing_lists().get("profileId", "id") +/// .doit(); +/// # } +/// ``` +pub struct TargetableRemarketingListGetCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for TargetableRemarketingListGetCall<'a, C, A> {} + +impl<'a, C, A> TargetableRemarketingListGetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, TargetableRemarketingList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.targetableRemarketingLists.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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/targetableRemarketingLists/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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 ["id", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> TargetableRemarketingListGetCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Remarketing list ID. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> TargetableRemarketingListGetCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> TargetableRemarketingListGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> TargetableRemarketingListGetCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> TargetableRemarketingListGetCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::Subaccount; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: '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, A> CallBuilder for SubaccountPatchCall<'a, C, A> {} + +impl<'a, C, A> SubaccountPatchCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/subaccounts".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> SubaccountPatchCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Subaccount ID. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> SubaccountPatchCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> SubaccountPatchCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::Subaccount; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: Subaccount, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for SubaccountInsertCall<'a, C, A> {} + +impl<'a, C, A> SubaccountInsertCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/subaccounts".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> SubaccountInsertCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> SubaccountInsertCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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("consetetur") +/// .sort_field("sea") +/// .search_string("nonumy") +/// .page_token("consetetur") +/// .max_results(-73) +/// .add_ids("clita") +/// .doit(); +/// # } +/// ``` +pub struct SubaccountListCall<'a, C, A> + where C: '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, A> CallBuilder for SubaccountListCall<'a, C, A> {} + +impl<'a, C, A> SubaccountListCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/subaccounts".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> SubaccountListCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Order of sorted results, default is ASCENDING. + /// + /// Sets the *sort order* query property to the given value. + pub fn sort_order(mut self, new_value: &str) -> SubaccountListCall<'a, C, A> { + self._sort_order = Some(new_value.to_string()); + self + } + /// Field by which to sort the list. + /// + /// Sets the *sort field* query property to the given value. + pub fn sort_field(mut self, new_value: &str) -> SubaccountListCall<'a, C, A> { + self._sort_field = Some(new_value.to_string()); + self + } + /// 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". + /// + /// Sets the *search string* query property to the given value. + pub fn search_string(mut self, new_value: &str) -> SubaccountListCall<'a, C, A> { + self._search_string = Some(new_value.to_string()); + self + } + /// Value of the nextPageToken from the previous result page. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> SubaccountListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Maximum number of results to return. + /// + /// Sets the *max results* query property to the given value. + pub fn max_results(mut self, new_value: i32) -> SubaccountListCall<'a, C, A> { + self._max_results = Some(new_value); + self + } + /// Select only subaccounts with these IDs. + /// + /// 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. + pub fn add_ids(mut self, new_value: &str) -> SubaccountListCall<'a, C, A> { + self._ids.push(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> SubaccountListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::Subaccount; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: Subaccount, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for SubaccountUpdateCall<'a, C, A> {} + +impl<'a, C, A> SubaccountUpdateCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/subaccounts".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> SubaccountUpdateCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> SubaccountUpdateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for SubaccountGetCall<'a, C, A> {} + +impl<'a, C, A> SubaccountGetCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/subaccounts/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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 ["id", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> SubaccountGetCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Subaccount ID. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> SubaccountGetCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> SubaccountGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Gets one mobile carrier by ID. +/// +/// A builder for the *get* method supported by a *mobileCarrier* resource. +/// It is not used directly, but through a `MobileCarrierMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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().get("profileId", "id") +/// .doit(); +/// # } +/// ``` +pub struct MobileCarrierGetCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for MobileCarrierGetCall<'a, C, A> {} + +impl<'a, C, A> MobileCarrierGetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, MobileCarrier)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/mobileCarriers/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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 ["id", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> MobileCarrierGetCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Mobile carrier ID. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> MobileCarrierGetCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> MobileCarrierGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> MobileCarrierGetCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> MobileCarrierGetCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for MobileCarrierListCall<'a, C, A> {} + +impl<'a, C, A> MobileCarrierListCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/mobileCarriers".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> MobileCarrierListCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> MobileCarrierListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for FloodlightConfigurationGetCall<'a, C, A> {} + +impl<'a, C, A> FloodlightConfigurationGetCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/floodlightConfigurations/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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 ["id", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> FloodlightConfigurationGetCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Floodlight configuration ID. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> FloodlightConfigurationGetCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> FloodlightConfigurationGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::FloodlightConfiguration; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: FloodlightConfiguration, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for FloodlightConfigurationUpdateCall<'a, C, A> {} + +impl<'a, C, A> FloodlightConfigurationUpdateCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/floodlightConfigurations".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> FloodlightConfigurationUpdateCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> FloodlightConfigurationUpdateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::FloodlightConfiguration; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: '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, A> CallBuilder for FloodlightConfigurationPatchCall<'a, C, A> {} + +impl<'a, C, A> FloodlightConfigurationPatchCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/floodlightConfigurations".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> FloodlightConfigurationPatchCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Floodlight configuration ID. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> FloodlightConfigurationPatchCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> FloodlightConfigurationPatchCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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("takimata") +/// .doit(); +/// # } +/// ``` +pub struct FloodlightConfigurationListCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _ids: Vec, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for FloodlightConfigurationListCall<'a, C, A> {} + +impl<'a, C, A> FloodlightConfigurationListCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/floodlightConfigurations".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> FloodlightConfigurationListCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Set of IDs of floodlight configurations to retrieve. Required field; otherwise an empty list will be returned. + /// + /// 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. + pub fn add_ids(mut self, new_value: &str) -> FloodlightConfigurationListCall<'a, C, A> { + self._ids.push(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> FloodlightConfigurationListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for OperatingSystemListCall<'a, C, A> {} + +impl<'a, C, A> OperatingSystemListCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/operatingSystems".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> OperatingSystemListCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> OperatingSystemListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Gets one operating system by DART ID. +/// +/// A builder for the *get* method supported by a *operatingSystem* resource. +/// It is not used directly, but through a `OperatingSystemMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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().get("profileId", "dartId") +/// .doit(); +/// # } +/// ``` +pub struct OperatingSystemGetCall<'a, C, A> + where C: '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, A> CallBuilder for OperatingSystemGetCall<'a, C, A> {} + +impl<'a, C, A> OperatingSystemGetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, OperatingSystem)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/operatingSystems/{dartId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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 ["dartId", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> OperatingSystemGetCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Operating system DART ID. + /// + /// 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. + pub fn dart_id(mut self, new_value: &str) -> OperatingSystemGetCall<'a, C, A> { + self._dart_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> OperatingSystemGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> OperatingSystemGetCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> OperatingSystemGetCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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("clita") +/// .sort_field("ipsum") +/// .scope("dolor") +/// .page_token("elitr") +/// .max_results(-82) +/// .doit(); +/// # } +/// ``` +pub struct FileListCall<'a, C, A> + where C: '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, A> CallBuilder for FileListCall<'a, C, A> {} + +impl<'a, C, A> FileListCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/files".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The DFA profile ID. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> FileListCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Order of sorted results, default is 'DESCENDING'. + /// + /// Sets the *sort order* query property to the given value. + pub fn sort_order(mut self, new_value: &str) -> FileListCall<'a, C, A> { + self._sort_order = Some(new_value.to_string()); + self + } + /// The field by which to sort the list. + /// + /// Sets the *sort field* query property to the given value. + pub fn sort_field(mut self, new_value: &str) -> FileListCall<'a, C, A> { + self._sort_field = Some(new_value.to_string()); + self + } + /// The scope that defines which results are returned, default is 'MINE'. + /// + /// Sets the *scope* query property to the given value. + pub fn scope(mut self, new_value: &str) -> FileListCall<'a, C, A> { + self._scope = Some(new_value.to_string()); + self + } + /// The value of the nextToken from the previous result page. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> FileListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Maximum number of results to return. + /// + /// Sets the *max results* query property to the given value. + pub fn max_results(mut self, new_value: i32) -> FileListCall<'a, C, A> { + self._max_results = Some(new_value); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> FileListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Full`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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, A> + where C: '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, A> CallBuilder for FileGetCall<'a, C, A> {} + +impl<'a, C, A> FileGetCall<'a, C, A> where 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 Err(Error::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 >::as_ref(&value) != "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.2/reports/{reportId}/files/{fileId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_ref().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 ["fileId", "reportId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + 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 Err(Error::JsonDecodeError(json_response, err)); + } + } + } else { (res, Default::default()) }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The ID of the report. + /// + /// 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. + pub fn report_id(mut self, new_value: &str) -> FileGetCall<'a, C, A> { + self._report_id = new_value.to_string(); + self + } + /// The ID of the report file. + /// + /// 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. + pub fn file_id(mut self, new_value: &str) -> FileGetCall<'a, C, A> { + self._file_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> FileGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Full`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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("et") +/// .sort_field("sit") +/// .add_site_ids("eirmod") +/// .search_string("no") +/// .add_pricing_types("Lorem") +/// .add_placement_strategy_ids("sed") +/// .placement_group_type("tempor") +/// .page_token("clita") +/// .min_start_date("kasd") +/// .min_end_date("elitr") +/// .max_start_date("et") +/// .max_results(-76) +/// .max_end_date("sadipscing") +/// .add_ids("sed") +/// .add_directory_site_ids("vero") +/// .add_content_category_ids("nonumy") +/// .add_campaign_ids("magna") +/// .archived(false) +/// .add_advertiser_ids("sea") +/// .doit(); +/// # } +/// ``` +pub struct PlacementGroupListCall<'a, C, A> + where C: '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, + _min_start_date: Option, + _min_end_date: Option, + _max_start_date: Option, + _max_results: Option, + _max_end_date: 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, A> CallBuilder for PlacementGroupListCall<'a, C, A> {} + +impl<'a, C, A> PlacementGroupListCall<'a, C, A> where 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((22 + 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._min_start_date { + params.push(("minStartDate", value.to_string())); + } + if let Some(value) = self._min_end_date { + params.push(("minEndDate", value.to_string())); + } + if let Some(value) = self._max_start_date { + params.push(("maxStartDate", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._max_end_date { + params.push(("maxEndDate", 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", "minStartDate", "minEndDate", "maxStartDate", "maxResults", "maxEndDate", "ids", "directorySiteIds", "contentCategoryIds", "campaignIds", "archived", "advertiserIds"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/placementGroups".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> PlacementGroupListCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Order of sorted results, default is ASCENDING. + /// + /// Sets the *sort order* query property to the given value. + pub fn sort_order(mut self, new_value: &str) -> PlacementGroupListCall<'a, C, A> { + self._sort_order = Some(new_value.to_string()); + self + } + /// Field by which to sort the list. + /// + /// Sets the *sort field* query property to the given value. + pub fn sort_field(mut self, new_value: &str) -> PlacementGroupListCall<'a, C, A> { + self._sort_field = Some(new_value.to_string()); + self + } + /// Select only placement groups that are associated with these sites. + /// + /// 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. + pub fn add_site_ids(mut self, new_value: &str) -> PlacementGroupListCall<'a, C, A> { + self._site_ids.push(new_value.to_string()); + self + } + /// 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". + /// + /// Sets the *search string* query property to the given value. + pub fn search_string(mut self, new_value: &str) -> PlacementGroupListCall<'a, C, A> { + self._search_string = Some(new_value.to_string()); + self + } + /// Select only placement groups with these pricing types. + /// + /// 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. + pub fn add_pricing_types(mut self, new_value: &str) -> PlacementGroupListCall<'a, C, A> { + self._pricing_types.push(new_value.to_string()); + self + } + /// Select only placement groups that are associated with these placement strategies. + /// + /// 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. + pub fn add_placement_strategy_ids(mut self, new_value: &str) -> PlacementGroupListCall<'a, C, A> { + self._placement_strategy_ids.push(new_value.to_string()); + self + } + /// 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. + /// + /// Sets the *placement group type* query property to the given value. + pub fn placement_group_type(mut self, new_value: &str) -> PlacementGroupListCall<'a, C, A> { + self._placement_group_type = Some(new_value.to_string()); + self + } + /// Value of the nextPageToken from the previous result page. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> PlacementGroupListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Select only placements or placement groups whose start date is on or after the specified minStartDate. The date should be formatted as "yyyy-MM-dd". + /// + /// Sets the *min start date* query property to the given value. + pub fn min_start_date(mut self, new_value: &str) -> PlacementGroupListCall<'a, C, A> { + self._min_start_date = Some(new_value.to_string()); + self + } + /// Select only placements or placement groups whose end date is on or after the specified minEndDate. The date should be formatted as "yyyy-MM-dd". + /// + /// Sets the *min end date* query property to the given value. + pub fn min_end_date(mut self, new_value: &str) -> PlacementGroupListCall<'a, C, A> { + self._min_end_date = Some(new_value.to_string()); + self + } + /// Select only placements or placement groups whose start date is on or before the specified maxStartDate. The date should be formatted as "yyyy-MM-dd". + /// + /// Sets the *max start date* query property to the given value. + pub fn max_start_date(mut self, new_value: &str) -> PlacementGroupListCall<'a, C, A> { + self._max_start_date = Some(new_value.to_string()); + self + } + /// Maximum number of results to return. + /// + /// Sets the *max results* query property to the given value. + pub fn max_results(mut self, new_value: i32) -> PlacementGroupListCall<'a, C, A> { + self._max_results = Some(new_value); + self + } + /// Select only placements or placement groups whose end date is on or before the specified maxEndDate. The date should be formatted as "yyyy-MM-dd". + /// + /// Sets the *max end date* query property to the given value. + pub fn max_end_date(mut self, new_value: &str) -> PlacementGroupListCall<'a, C, A> { + self._max_end_date = Some(new_value.to_string()); + self + } + /// Select only placement groups with these IDs. + /// + /// 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. + pub fn add_ids(mut self, new_value: &str) -> PlacementGroupListCall<'a, C, A> { + self._ids.push(new_value.to_string()); + self + } + /// Select only placement groups that are associated with these directory sites. + /// + /// 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. + pub fn add_directory_site_ids(mut self, new_value: &str) -> PlacementGroupListCall<'a, C, A> { + self._directory_site_ids.push(new_value.to_string()); + self + } + /// Select only placement groups that are associated with these content categories. + /// + /// 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. + pub fn add_content_category_ids(mut self, new_value: &str) -> PlacementGroupListCall<'a, C, A> { + self._content_category_ids.push(new_value.to_string()); + self + } + /// Select only placement groups that belong to these campaigns. + /// + /// 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. + pub fn add_campaign_ids(mut self, new_value: &str) -> PlacementGroupListCall<'a, C, A> { + self._campaign_ids.push(new_value.to_string()); + self + } + /// Select only archived placements. Don't set this field to select both archived and non-archived placements. + /// + /// Sets the *archived* query property to the given value. + pub fn archived(mut self, new_value: bool) -> PlacementGroupListCall<'a, C, A> { + self._archived = Some(new_value); + self + } + /// Select only placement groups that belong to these advertisers. + /// + /// 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. + pub fn add_advertiser_ids(mut self, new_value: &str) -> PlacementGroupListCall<'a, C, A> { + self._advertiser_ids.push(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PlacementGroupListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::PlacementGroup; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: PlacementGroup, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for PlacementGroupUpdateCall<'a, C, A> {} + +impl<'a, C, A> PlacementGroupUpdateCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/placementGroups".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> PlacementGroupUpdateCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PlacementGroupUpdateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::PlacementGroup; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: PlacementGroup, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for PlacementGroupInsertCall<'a, C, A> {} + +impl<'a, C, A> PlacementGroupInsertCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/placementGroups".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> PlacementGroupInsertCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PlacementGroupInsertCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for PlacementGroupGetCall<'a, C, A> {} + +impl<'a, C, A> PlacementGroupGetCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/placementGroups/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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 ["id", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> PlacementGroupGetCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Placement group ID. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> PlacementGroupGetCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PlacementGroupGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::PlacementGroup; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: '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, A> CallBuilder for PlacementGroupPatchCall<'a, C, A> {} + +impl<'a, C, A> PlacementGroupPatchCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/placementGroups".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> PlacementGroupPatchCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Placement group ID. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> PlacementGroupPatchCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PlacementGroupPatchCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Retrieves a list of inventory items, possibly filtered. +/// +/// A builder for the *list* method supported by a *inventoryItem* resource. +/// It is not used directly, but through a `InventoryItemMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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.inventory_items().list("profileId", "projectId") +/// .sort_order("justo") +/// .sort_field("kasd") +/// .add_site_id("kasd") +/// .page_token("ipsum") +/// .add_order_id("eos") +/// .max_results(-91) +/// .in_plan(true) +/// .add_ids("voluptua.") +/// .doit(); +/// # } +/// ``` +pub struct InventoryItemListCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _project_id: String, + _sort_order: Option, + _sort_field: Option, + _site_id: Vec, + _page_token: Option, + _order_id: Vec, + _max_results: Option, + _in_plan: Option, + _ids: Vec, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for InventoryItemListCall<'a, C, A> {} + +impl<'a, C, A> InventoryItemListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, InventoryItemsListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.inventoryItems.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())); + params.push(("projectId", self._project_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_id.len() > 0 { + let mut s = String::new(); + for f in self._site_id.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("siteId", s)); + } + if let Some(value) = self._page_token { + params.push(("pageToken", value.to_string())); + } + if self._order_id.len() > 0 { + let mut s = String::new(); + for f in self._order_id.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("orderId", s)); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._in_plan { + params.push(("inPlan", 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", "projectId", "sortOrder", "sortField", "siteId", "pageToken", "orderId", "maxResults", "inPlan", "ids"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/projects/{projectId}/inventoryItems".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId"), ("{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(2); + for param_name in ["projectId", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> InventoryItemListCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Project ID for order documents. + /// + /// 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. + pub fn project_id(mut self, new_value: &str) -> InventoryItemListCall<'a, C, A> { + self._project_id = new_value.to_string(); + self + } + /// Order of sorted results, default is ASCENDING. + /// + /// Sets the *sort order* query property to the given value. + pub fn sort_order(mut self, new_value: &str) -> InventoryItemListCall<'a, C, A> { + self._sort_order = Some(new_value.to_string()); + self + } + /// Field by which to sort the list. + /// + /// Sets the *sort field* query property to the given value. + pub fn sort_field(mut self, new_value: &str) -> InventoryItemListCall<'a, C, A> { + self._sort_field = Some(new_value.to_string()); + self + } + /// Select only inventory items that are associated with these sites. + /// + /// Append the given value to the *site id* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + pub fn add_site_id(mut self, new_value: &str) -> InventoryItemListCall<'a, C, A> { + self._site_id.push(new_value.to_string()); + self + } + /// Value of the nextPageToken from the previous result page. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> InventoryItemListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Select only inventory items that belong to specified orders. + /// + /// Append the given value to the *order id* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + pub fn add_order_id(mut self, new_value: &str) -> InventoryItemListCall<'a, C, A> { + self._order_id.push(new_value.to_string()); + self + } + /// Maximum number of results to return. + /// + /// Sets the *max results* query property to the given value. + pub fn max_results(mut self, new_value: i32) -> InventoryItemListCall<'a, C, A> { + self._max_results = Some(new_value); + self + } + /// Select only inventory items that are in plan. + /// + /// Sets the *in plan* query property to the given value. + pub fn in_plan(mut self, new_value: bool) -> InventoryItemListCall<'a, C, A> { + self._in_plan = Some(new_value); + self + } + /// Select only inventory items with these IDs. + /// + /// 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. + pub fn add_ids(mut self, new_value: &str) -> InventoryItemListCall<'a, C, A> { + self._ids.push(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> InventoryItemListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> InventoryItemListCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> InventoryItemListCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Gets one inventory item by ID. +/// +/// A builder for the *get* method supported by a *inventoryItem* resource. +/// It is not used directly, but through a `InventoryItemMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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.inventory_items().get("profileId", "projectId", "id") +/// .doit(); +/// # } +/// ``` +pub struct InventoryItemGetCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _project_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for InventoryItemGetCall<'a, C, A> {} + +impl<'a, C, A> InventoryItemGetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, InventoryItem)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.inventoryItems.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(("projectId", self._project_id.to_string())); + params.push(("id", self._id.to_string())); + for &field in ["alt", "profileId", "projectId", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/projects/{projectId}/inventoryItems/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId"), ("{projectId}", "projectId"), ("{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 ["id", "projectId", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> InventoryItemGetCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Project ID for order documents. + /// + /// 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. + pub fn project_id(mut self, new_value: &str) -> InventoryItemGetCall<'a, C, A> { + self._project_id = new_value.to_string(); + self + } + /// Inventory item ID. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> InventoryItemGetCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> InventoryItemGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> InventoryItemGetCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> InventoryItemGetCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for UserRolePermissionGetCall<'a, C, A> {} + +impl<'a, C, A> UserRolePermissionGetCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/userRolePermissions/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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 ["id", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> UserRolePermissionGetCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// User role permission ID. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> UserRolePermissionGetCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserRolePermissionGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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("tempor") +/// .doit(); +/// # } +/// ``` +pub struct UserRolePermissionListCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _ids: Vec, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for UserRolePermissionListCall<'a, C, A> {} + +impl<'a, C, A> UserRolePermissionListCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/userRolePermissions".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> UserRolePermissionListCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Select only user role permissions with these IDs. + /// + /// 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. + pub fn add_ids(mut self, new_value: &str) -> UserRolePermissionListCall<'a, C, A> { + self._ids.push(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserRolePermissionListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for AccountPermissionGroupListCall<'a, C, A> {} + +impl<'a, C, A> AccountPermissionGroupListCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/accountPermissionGroups".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> AccountPermissionGroupListCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountPermissionGroupListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for AccountPermissionGroupGetCall<'a, C, A> {} + +impl<'a, C, A> AccountPermissionGroupGetCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/accountPermissionGroups/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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 ["id", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> AccountPermissionGroupGetCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Account permission group ID. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> AccountPermissionGroupGetCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountPermissionGroupGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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("clita") +/// .sort_field("et") +/// .search_string("eirmod") +/// .page_token("ea") +/// .max_results(-71) +/// .add_ids("sed") +/// .doit(); +/// # } +/// ``` +pub struct ContentCategoryListCall<'a, C, A> + where C: '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, A> CallBuilder for ContentCategoryListCall<'a, C, A> {} + +impl<'a, C, A> ContentCategoryListCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/contentCategories".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> ContentCategoryListCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Order of sorted results, default is ASCENDING. + /// + /// Sets the *sort order* query property to the given value. + pub fn sort_order(mut self, new_value: &str) -> ContentCategoryListCall<'a, C, A> { + self._sort_order = Some(new_value.to_string()); + self + } + /// Field by which to sort the list. + /// + /// Sets the *sort field* query property to the given value. + pub fn sort_field(mut self, new_value: &str) -> ContentCategoryListCall<'a, C, A> { + self._sort_field = Some(new_value.to_string()); + self + } + /// 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". + /// + /// Sets the *search string* query property to the given value. + pub fn search_string(mut self, new_value: &str) -> ContentCategoryListCall<'a, C, A> { + self._search_string = Some(new_value.to_string()); + self + } + /// Value of the nextPageToken from the previous result page. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> ContentCategoryListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Maximum number of results to return. + /// + /// Sets the *max results* query property to the given value. + pub fn max_results(mut self, new_value: i32) -> ContentCategoryListCall<'a, C, A> { + self._max_results = Some(new_value); + self + } + /// Select only content categories with these IDs. + /// + /// 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. + pub fn add_ids(mut self, new_value: &str) -> ContentCategoryListCall<'a, C, A> { + self._ids.push(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ContentCategoryListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::ContentCategory; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: ContentCategory, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ContentCategoryUpdateCall<'a, C, A> {} + +impl<'a, C, A> ContentCategoryUpdateCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/contentCategories".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> ContentCategoryUpdateCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ContentCategoryUpdateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::ContentCategory; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: ContentCategory, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ContentCategoryInsertCall<'a, C, A> {} + +impl<'a, C, A> ContentCategoryInsertCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/contentCategories".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> ContentCategoryInsertCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ContentCategoryInsertCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ContentCategoryDeleteCall<'a, C, A> {} + +impl<'a, C, A> ContentCategoryDeleteCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/dfareporting/v2.2/userprofiles/{profileId}/contentCategories/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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 ["id", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = res; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> ContentCategoryDeleteCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Content category ID. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> ContentCategoryDeleteCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ContentCategoryDeleteCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ContentCategoryGetCall<'a, C, A> {} + +impl<'a, C, A> ContentCategoryGetCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/contentCategories/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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 ["id", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> ContentCategoryGetCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Content category ID. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> ContentCategoryGetCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ContentCategoryGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::ContentCategory; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: '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, A> CallBuilder for ContentCategoryPatchCall<'a, C, A> {} + +impl<'a, C, A> ContentCategoryPatchCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/contentCategories".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> ContentCategoryPatchCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Content category ID. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> ContentCategoryPatchCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ContentCategoryPatchCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::Creative; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: Creative, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for CreativeUpdateCall<'a, C, A> {} + +impl<'a, C, A> CreativeUpdateCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/creatives".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> CreativeUpdateCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CreativeUpdateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::Creative; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: Creative, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for CreativeInsertCall<'a, C, A> {} + +impl<'a, C, A> CreativeInsertCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/creatives".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> CreativeInsertCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CreativeInsertCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for CreativeGetCall<'a, C, A> {} + +impl<'a, C, A> CreativeGetCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/creatives/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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 ["id", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> CreativeGetCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Creative ID. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> CreativeGetCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CreativeGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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("invidunt") +/// .studio_creative_id("voluptua.") +/// .sort_order("erat") +/// .sort_field("ipsum") +/// .add_size_ids("no") +/// .search_string("vero") +/// .add_rendering_ids("sed") +/// .page_token("vero") +/// .max_results(-84) +/// .add_ids("Lorem") +/// .add_creative_field_ids("invidunt") +/// .add_companion_creative_ids("duo") +/// .campaign_id("dolor") +/// .archived(false) +/// .advertiser_id("diam") +/// .active(false) +/// .doit(); +/// # } +/// ``` +pub struct CreativeListCall<'a, C, A> + where C: '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, A> CallBuilder for CreativeListCall<'a, C, A> {} + +impl<'a, C, A> CreativeListCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/creatives".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> CreativeListCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Select only creatives with these creative types. + /// + /// 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. + pub fn add_types(mut self, new_value: &str) -> CreativeListCall<'a, C, A> { + self._types.push(new_value.to_string()); + self + } + /// Select only creatives corresponding to this Studio creative ID. + /// + /// Sets the *studio creative id* query property to the given value. + pub fn studio_creative_id(mut self, new_value: &str) -> CreativeListCall<'a, C, A> { + self._studio_creative_id = Some(new_value.to_string()); + self + } + /// Order of sorted results, default is ASCENDING. + /// + /// Sets the *sort order* query property to the given value. + pub fn sort_order(mut self, new_value: &str) -> CreativeListCall<'a, C, A> { + self._sort_order = Some(new_value.to_string()); + self + } + /// Field by which to sort the list. + /// + /// Sets the *sort field* query property to the given value. + pub fn sort_field(mut self, new_value: &str) -> CreativeListCall<'a, C, A> { + self._sort_field = Some(new_value.to_string()); + self + } + /// Select only creatives with these size IDs. + /// + /// 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. + pub fn add_size_ids(mut self, new_value: &str) -> CreativeListCall<'a, C, A> { + self._size_ids.push(new_value.to_string()); + self + } + /// 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". + /// + /// Sets the *search string* query property to the given value. + pub fn search_string(mut self, new_value: &str) -> CreativeListCall<'a, C, A> { + self._search_string = Some(new_value.to_string()); + self + } + /// Select only creatives with these rendering IDs. + /// + /// 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. + pub fn add_rendering_ids(mut self, new_value: &str) -> CreativeListCall<'a, C, A> { + self._rendering_ids.push(new_value.to_string()); + self + } + /// Value of the nextPageToken from the previous result page. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> CreativeListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Maximum number of results to return. + /// + /// Sets the *max results* query property to the given value. + pub fn max_results(mut self, new_value: i32) -> CreativeListCall<'a, C, A> { + self._max_results = Some(new_value); + self + } + /// Select only creatives with these IDs. + /// + /// 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. + pub fn add_ids(mut self, new_value: &str) -> CreativeListCall<'a, C, A> { + self._ids.push(new_value.to_string()); + self + } + /// Select only creatives with these creative field IDs. + /// + /// 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. + pub fn add_creative_field_ids(mut self, new_value: &str) -> CreativeListCall<'a, C, A> { + self._creative_field_ids.push(new_value.to_string()); + self + } + /// Select only in-stream video creatives with these companion IDs. + /// + /// 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. + pub fn add_companion_creative_ids(mut self, new_value: &str) -> CreativeListCall<'a, C, A> { + self._companion_creative_ids.push(new_value.to_string()); + self + } + /// Select only creatives with this campaign ID. + /// + /// Sets the *campaign id* query property to the given value. + pub fn campaign_id(mut self, new_value: &str) -> CreativeListCall<'a, C, A> { + self._campaign_id = Some(new_value.to_string()); + self + } + /// Select only archived creatives. Leave blank to select archived and unarchived creatives. + /// + /// Sets the *archived* query property to the given value. + pub fn archived(mut self, new_value: bool) -> CreativeListCall<'a, C, A> { + self._archived = Some(new_value); + self + } + /// Select only creatives with this advertiser ID. + /// + /// Sets the *advertiser id* query property to the given value. + pub fn advertiser_id(mut self, new_value: &str) -> CreativeListCall<'a, C, A> { + self._advertiser_id = Some(new_value.to_string()); + self + } + /// Select only active creatives. Leave blank to select active and inactive creatives. + /// + /// Sets the *active* query property to the given value. + pub fn active(mut self, new_value: bool) -> CreativeListCall<'a, C, A> { + self._active = Some(new_value); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CreativeListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::Creative; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: '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, A> CallBuilder for CreativePatchCall<'a, C, A> {} + +impl<'a, C, A> CreativePatchCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/creatives".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> CreativePatchCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Creative ID. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> CreativePatchCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CreativePatchCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for CampaignGetCall<'a, C, A> {} + +impl<'a, C, A> CampaignGetCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/campaigns/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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 ["id", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> CampaignGetCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Campaign ID. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> CampaignGetCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CampaignGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::Campaign; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: '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, A> CallBuilder for CampaignInsertCall<'a, C, A> {} + +impl<'a, C, A> CampaignInsertCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/campaigns".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> CampaignInsertCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Default landing page name for this new campaign. Must be less than 256 characters long. + /// + /// 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. + pub fn default_landing_page_name(mut self, new_value: &str) -> CampaignInsertCall<'a, C, A> { + self._default_landing_page_name = new_value.to_string(); + self + } + /// Default landing page URL for this new campaign. + /// + /// 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. + pub fn default_landing_page_url(mut self, new_value: &str) -> CampaignInsertCall<'a, C, A> { + self._default_landing_page_url = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CampaignInsertCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::Campaign; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: '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, A> CallBuilder for CampaignPatchCall<'a, C, A> {} + +impl<'a, C, A> CampaignPatchCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/campaigns".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> CampaignPatchCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Campaign ID. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> CampaignPatchCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CampaignPatchCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::Campaign; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: Campaign, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for CampaignUpdateCall<'a, C, A> {} + +impl<'a, C, A> CampaignUpdateCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/campaigns".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> CampaignUpdateCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CampaignUpdateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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("duo") +/// .sort_order("ipsum") +/// .sort_field("diam") +/// .search_string("sed") +/// .page_token("et") +/// .overridden_event_tag_id("tempor") +/// .max_results(-20) +/// .add_ids("takimata") +/// .add_excluded_ids("invidunt") +/// .at_least_one_optimization_activity(true) +/// .archived(false) +/// .add_advertiser_ids("voluptua.") +/// .add_advertiser_group_ids("et") +/// .doit(); +/// # } +/// ``` +pub struct CampaignListCall<'a, C, A> + where C: '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, A> CallBuilder for CampaignListCall<'a, C, A> {} + +impl<'a, C, A> CampaignListCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/campaigns".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> CampaignListCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Select only campaigns that belong to this subaccount. + /// + /// Sets the *subaccount id* query property to the given value. + pub fn subaccount_id(mut self, new_value: &str) -> CampaignListCall<'a, C, A> { + self._subaccount_id = Some(new_value.to_string()); + self + } + /// Order of sorted results, default is ASCENDING. + /// + /// Sets the *sort order* query property to the given value. + pub fn sort_order(mut self, new_value: &str) -> CampaignListCall<'a, C, A> { + self._sort_order = Some(new_value.to_string()); + self + } + /// Field by which to sort the list. + /// + /// Sets the *sort field* query property to the given value. + pub fn sort_field(mut self, new_value: &str) -> CampaignListCall<'a, C, A> { + self._sort_field = Some(new_value.to_string()); + self + } + /// 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". + /// + /// Sets the *search string* query property to the given value. + pub fn search_string(mut self, new_value: &str) -> CampaignListCall<'a, C, A> { + self._search_string = Some(new_value.to_string()); + self + } + /// Value of the nextPageToken from the previous result page. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> CampaignListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Select only campaigns that have overridden this event tag ID. + /// + /// Sets the *overridden event tag id* query property to the given value. + pub fn overridden_event_tag_id(mut self, new_value: &str) -> CampaignListCall<'a, C, A> { + self._overridden_event_tag_id = Some(new_value.to_string()); + self + } + /// Maximum number of results to return. + /// + /// Sets the *max results* query property to the given value. + pub fn max_results(mut self, new_value: i32) -> CampaignListCall<'a, C, A> { + self._max_results = Some(new_value); + self + } + /// Select only campaigns with these IDs. + /// + /// 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. + pub fn add_ids(mut self, new_value: &str) -> CampaignListCall<'a, C, A> { + self._ids.push(new_value.to_string()); + self + } + /// Exclude campaigns with these IDs. + /// + /// 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. + pub fn add_excluded_ids(mut self, new_value: &str) -> CampaignListCall<'a, C, A> { + self._excluded_ids.push(new_value.to_string()); + self + } + /// Select only campaigns that have at least one optimization activity. + /// + /// Sets the *at least one optimization activity* query property to the given value. + pub fn at_least_one_optimization_activity(mut self, new_value: bool) -> CampaignListCall<'a, C, A> { + self._at_least_one_optimization_activity = Some(new_value); + self + } + /// Select only archived campaigns. Don't set this field to select both archived and non-archived campaigns. + /// + /// Sets the *archived* query property to the given value. + pub fn archived(mut self, new_value: bool) -> CampaignListCall<'a, C, A> { + self._archived = Some(new_value); + self + } + /// Select only campaigns that belong to these advertisers. + /// + /// 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. + pub fn add_advertiser_ids(mut self, new_value: &str) -> CampaignListCall<'a, C, A> { + self._advertiser_ids.push(new_value.to_string()); + self + } + /// Select only campaigns whose advertisers belong to these advertiser groups. + /// + /// 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. + pub fn add_advertiser_group_ids(mut self, new_value: &str) -> CampaignListCall<'a, C, A> { + self._advertiser_group_ids.push(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CampaignListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for EventTagDeleteCall<'a, C, A> {} + +impl<'a, C, A> EventTagDeleteCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/dfareporting/v2.2/userprofiles/{profileId}/eventTags/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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 ["id", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = res; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> EventTagDeleteCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Event tag ID. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> EventTagDeleteCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EventTagDeleteCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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("justo") +/// .sort_field("gubergren") +/// .search_string("ipsum") +/// .add_ids("amet.") +/// .add_event_tag_types("dolor") +/// .enabled(false) +/// .definitions_only(false) +/// .campaign_id("magna") +/// .advertiser_id("amet.") +/// .ad_id("eirmod") +/// .doit(); +/// # } +/// ``` +pub struct EventTagListCall<'a, C, A> + where C: '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, A> CallBuilder for EventTagListCall<'a, C, A> {} + +impl<'a, C, A> EventTagListCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/eventTags".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> EventTagListCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Order of sorted results, default is ASCENDING. + /// + /// Sets the *sort order* query property to the given value. + pub fn sort_order(mut self, new_value: &str) -> EventTagListCall<'a, C, A> { + self._sort_order = Some(new_value.to_string()); + self + } + /// Field by which to sort the list. + /// + /// Sets the *sort field* query property to the given value. + pub fn sort_field(mut self, new_value: &str) -> EventTagListCall<'a, C, A> { + self._sort_field = Some(new_value.to_string()); + self + } + /// 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". + /// + /// Sets the *search string* query property to the given value. + pub fn search_string(mut self, new_value: &str) -> EventTagListCall<'a, C, A> { + self._search_string = Some(new_value.to_string()); + self + } + /// Select only event tags with these IDs. + /// + /// 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. + pub fn add_ids(mut self, new_value: &str) -> EventTagListCall<'a, C, A> { + self._ids.push(new_value.to_string()); + self + } + /// 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. + /// + /// 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. + pub fn add_event_tag_types(mut self, new_value: &str) -> EventTagListCall<'a, C, A> { + self._event_tag_types.push(new_value.to_string()); + self + } + /// Select only enabled event tags. What is considered enabled or disabled depends on the definitionsOnly parameter. 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. + /// + /// Sets the *enabled* query property to the given value. + pub fn enabled(mut self, new_value: bool) -> EventTagListCall<'a, C, A> { + self._enabled = Some(new_value); + self + } + /// Examine only the specified campaign or advertiser's event tags for matching selector criteria. When set to false, the parent advertiser and parent campaign of the specified ad or campaign is examined as well. In addition, when set to false, the status field is examined as well, along with the enabledByDefault field. This parameter can not be set to true when adId is specified as ads do not define their own even tags. + /// + /// Sets the *definitions only* query property to the given value. + pub fn definitions_only(mut self, new_value: bool) -> EventTagListCall<'a, C, A> { + self._definitions_only = Some(new_value); + self + } + /// Select only event tags that belong to this campaign. + /// + /// Sets the *campaign id* query property to the given value. + pub fn campaign_id(mut self, new_value: &str) -> EventTagListCall<'a, C, A> { + self._campaign_id = Some(new_value.to_string()); + self + } + /// Select only event tags that belong to this advertiser. + /// + /// Sets the *advertiser id* query property to the given value. + pub fn advertiser_id(mut self, new_value: &str) -> EventTagListCall<'a, C, A> { + self._advertiser_id = Some(new_value.to_string()); + self + } + /// Select only event tags that belong to this ad. + /// + /// Sets the *ad id* query property to the given value. + pub fn ad_id(mut self, new_value: &str) -> EventTagListCall<'a, C, A> { + self._ad_id = Some(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EventTagListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::EventTag; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: EventTag, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for EventTagInsertCall<'a, C, A> {} + +impl<'a, C, A> EventTagInsertCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/eventTags".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> EventTagInsertCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EventTagInsertCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::EventTag; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: '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, A> CallBuilder for EventTagPatchCall<'a, C, A> {} + +impl<'a, C, A> EventTagPatchCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/eventTags".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> EventTagPatchCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Event tag ID. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> EventTagPatchCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EventTagPatchCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::EventTag; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: EventTag, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for EventTagUpdateCall<'a, C, A> {} + +impl<'a, C, A> EventTagUpdateCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/eventTags".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> EventTagUpdateCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EventTagUpdateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for EventTagGetCall<'a, C, A> {} + +impl<'a, C, A> EventTagGetCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/eventTags/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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 ["id", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> EventTagGetCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Event tag ID. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> EventTagGetCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> EventTagGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Gets one remarketing list by ID. +/// +/// A builder for the *get* method supported by a *remarketingList* resource. +/// It is not used directly, but through a `RemarketingListMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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.remarketing_lists().get("profileId", "id") +/// .doit(); +/// # } +/// ``` +pub struct RemarketingListGetCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for RemarketingListGetCall<'a, C, A> {} + +impl<'a, C, A> RemarketingListGetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, RemarketingList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.remarketingLists.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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/remarketingLists/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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 ["id", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> RemarketingListGetCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Remarketing list ID. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> RemarketingListGetCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> RemarketingListGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> RemarketingListGetCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> RemarketingListGetCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Updates an existing remarketing list. +/// +/// A builder for the *update* method supported by a *remarketingList* resource. +/// It is not used directly, but through a `RemarketingListMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::RemarketingList; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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 = RemarketingList::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.remarketing_lists().update(req, "profileId") +/// .doit(); +/// # } +/// ``` +pub struct RemarketingListUpdateCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: RemarketingList, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for RemarketingListUpdateCall<'a, C, A> {} + +impl<'a, C, A> RemarketingListUpdateCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, RemarketingList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.remarketingLists.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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/remarketingLists".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: RemarketingList) -> RemarketingListUpdateCall<'a, C, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> RemarketingListUpdateCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> RemarketingListUpdateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> RemarketingListUpdateCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> RemarketingListUpdateCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Retrieves a list of remarketing lists, possibly filtered. +/// +/// A builder for the *list* method supported by a *remarketingList* resource. +/// It is not used directly, but through a `RemarketingListMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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.remarketing_lists().list("profileId", "advertiserId") +/// .sort_order("tempor") +/// .sort_field("consetetur") +/// .page_token("eirmod") +/// .name("aliquyam") +/// .max_results(-10) +/// .floodlight_activity_id("aliquyam") +/// .active(true) +/// .doit(); +/// # } +/// ``` +pub struct RemarketingListListCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _advertiser_id: String, + _sort_order: Option, + _sort_field: Option, + _page_token: Option, + _name: Option, + _max_results: Option, + _floodlight_activity_id: Option, + _active: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for RemarketingListListCall<'a, C, A> {} + +impl<'a, C, A> RemarketingListListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, RemarketingListsListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.remarketingLists.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())); + params.push(("advertiserId", self._advertiser_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._name { + params.push(("name", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._floodlight_activity_id { + params.push(("floodlightActivityId", value.to_string())); + } + if let Some(value) = self._active { + params.push(("active", value.to_string())); + } + for &field in ["alt", "profileId", "advertiserId", "sortOrder", "sortField", "pageToken", "name", "maxResults", "floodlightActivityId", "active"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/remarketingLists".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> RemarketingListListCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Select only remarketing lists owned by this advertiser. + /// + /// 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. + pub fn advertiser_id(mut self, new_value: &str) -> RemarketingListListCall<'a, C, A> { + self._advertiser_id = new_value.to_string(); + self + } + /// Order of sorted results, default is ASCENDING. + /// + /// Sets the *sort order* query property to the given value. + pub fn sort_order(mut self, new_value: &str) -> RemarketingListListCall<'a, C, A> { + self._sort_order = Some(new_value.to_string()); + self + } + /// Field by which to sort the list. + /// + /// Sets the *sort field* query property to the given value. + pub fn sort_field(mut self, new_value: &str) -> RemarketingListListCall<'a, C, A> { + self._sort_field = Some(new_value.to_string()); + self + } + /// Value of the nextPageToken from the previous result page. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> RemarketingListListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Allows searching for objects by name or ID. Wildcards (*) are allowed. For example, "remarketing list*2015" will return objects with names like "remarketing list June 2015", "remarketing list April 2015", or simply "remarketing list 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 "remarketing list" will match objects with name "my remarketing list", "remarketing list 2015", or simply "remarketing list". + /// + /// Sets the *name* query property to the given value. + pub fn name(mut self, new_value: &str) -> RemarketingListListCall<'a, C, A> { + self._name = Some(new_value.to_string()); + self + } + /// Maximum number of results to return. + /// + /// Sets the *max results* query property to the given value. + pub fn max_results(mut self, new_value: i32) -> RemarketingListListCall<'a, C, A> { + self._max_results = Some(new_value); + self + } + /// Select only remarketing lists that have this floodlight activity ID. + /// + /// Sets the *floodlight activity id* query property to the given value. + pub fn floodlight_activity_id(mut self, new_value: &str) -> RemarketingListListCall<'a, C, A> { + self._floodlight_activity_id = Some(new_value.to_string()); + self + } + /// Select only active or only inactive remarketing lists. + /// + /// Sets the *active* query property to the given value. + pub fn active(mut self, new_value: bool) -> RemarketingListListCall<'a, C, A> { + self._active = Some(new_value); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> RemarketingListListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> RemarketingListListCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> RemarketingListListCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Updates an existing remarketing list. This method supports patch semantics. +/// +/// A builder for the *patch* method supported by a *remarketingList* resource. +/// It is not used directly, but through a `RemarketingListMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::RemarketingList; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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 = RemarketingList::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.remarketing_lists().patch(req, "profileId", "id") +/// .doit(); +/// # } +/// ``` +pub struct RemarketingListPatchCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: RemarketingList, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for RemarketingListPatchCall<'a, C, A> {} + +impl<'a, C, A> RemarketingListPatchCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, RemarketingList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.remarketingLists.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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/remarketingLists".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: RemarketingList) -> RemarketingListPatchCall<'a, C, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> RemarketingListPatchCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Remarketing list ID. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> RemarketingListPatchCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> RemarketingListPatchCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> RemarketingListPatchCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> RemarketingListPatchCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Inserts a new remarketing list. +/// +/// A builder for the *insert* method supported by a *remarketingList* resource. +/// It is not used directly, but through a `RemarketingListMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::RemarketingList; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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 = RemarketingList::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.remarketing_lists().insert(req, "profileId") +/// .doit(); +/// # } +/// ``` +pub struct RemarketingListInsertCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: RemarketingList, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for RemarketingListInsertCall<'a, C, A> {} + +impl<'a, C, A> RemarketingListInsertCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, RemarketingList)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.remarketingLists.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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/remarketingLists".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: RemarketingList) -> RemarketingListInsertCall<'a, C, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> RemarketingListInsertCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> RemarketingListInsertCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> RemarketingListInsertCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> RemarketingListInsertCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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("clita") +/// .name_prefix("est") +/// .add_dart_ids("sit") +/// .add_country_dart_ids("ipsum") +/// .doit(); +/// # } +/// ``` +pub struct CityListCall<'a, C, A> + where C: '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, A> CallBuilder for CityListCall<'a, C, A> {} + +impl<'a, C, A> CityListCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/cities".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> CityListCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Select only cities from these regions. + /// + /// 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. + pub fn add_region_dart_ids(mut self, new_value: &str) -> CityListCall<'a, C, A> { + self._region_dart_ids.push(new_value.to_string()); + self + } + /// Select only cities with names starting with this prefix. + /// + /// Sets the *name prefix* query property to the given value. + pub fn name_prefix(mut self, new_value: &str) -> CityListCall<'a, C, A> { + self._name_prefix = Some(new_value.to_string()); + self + } + /// Select only cities with these DART IDs. + /// + /// 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. + pub fn add_dart_ids(mut self, new_value: &str) -> CityListCall<'a, C, A> { + self._dart_ids.push(new_value.to_string()); + self + } + /// Select only cities from these countries. + /// + /// 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. + pub fn add_country_dart_ids(mut self, new_value: &str) -> CityListCall<'a, C, A> { + self._country_dart_ids.push(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CityListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::PlacementStrategy; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: PlacementStrategy, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for PlacementStrategyUpdateCall<'a, C, A> {} + +impl<'a, C, A> PlacementStrategyUpdateCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/placementStrategies".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> PlacementStrategyUpdateCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PlacementStrategyUpdateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for PlacementStrategyGetCall<'a, C, A> {} + +impl<'a, C, A> PlacementStrategyGetCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/placementStrategies/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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 ["id", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> PlacementStrategyGetCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Placement strategy ID. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> PlacementStrategyGetCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PlacementStrategyGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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("ea") +/// .sort_field("dolor") +/// .search_string("consetetur") +/// .page_token("sadipscing") +/// .max_results(-49) +/// .add_ids("et") +/// .doit(); +/// # } +/// ``` +pub struct PlacementStrategyListCall<'a, C, A> + where C: '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, A> CallBuilder for PlacementStrategyListCall<'a, C, A> {} + +impl<'a, C, A> PlacementStrategyListCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/placementStrategies".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> PlacementStrategyListCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Order of sorted results, default is ASCENDING. + /// + /// Sets the *sort order* query property to the given value. + pub fn sort_order(mut self, new_value: &str) -> PlacementStrategyListCall<'a, C, A> { + self._sort_order = Some(new_value.to_string()); + self + } + /// Field by which to sort the list. + /// + /// Sets the *sort field* query property to the given value. + pub fn sort_field(mut self, new_value: &str) -> PlacementStrategyListCall<'a, C, A> { + self._sort_field = Some(new_value.to_string()); + self + } + /// 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". + /// + /// Sets the *search string* query property to the given value. + pub fn search_string(mut self, new_value: &str) -> PlacementStrategyListCall<'a, C, A> { + self._search_string = Some(new_value.to_string()); + self + } + /// Value of the nextPageToken from the previous result page. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> PlacementStrategyListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Maximum number of results to return. + /// + /// Sets the *max results* query property to the given value. + pub fn max_results(mut self, new_value: i32) -> PlacementStrategyListCall<'a, C, A> { + self._max_results = Some(new_value); + self + } + /// Select only placement strategies with these IDs. + /// + /// 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. + pub fn add_ids(mut self, new_value: &str) -> PlacementStrategyListCall<'a, C, A> { + self._ids.push(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PlacementStrategyListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for PlacementStrategyDeleteCall<'a, C, A> {} + +impl<'a, C, A> PlacementStrategyDeleteCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + + let mut url = "https://www.googleapis.com/dfareporting/v2.2/userprofiles/{profileId}/placementStrategies/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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 ["id", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = res; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> PlacementStrategyDeleteCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Placement strategy ID. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> PlacementStrategyDeleteCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PlacementStrategyDeleteCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::PlacementStrategy; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: PlacementStrategy, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for PlacementStrategyInsertCall<'a, C, A> {} + +impl<'a, C, A> PlacementStrategyInsertCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/placementStrategies".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> PlacementStrategyInsertCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PlacementStrategyInsertCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::PlacementStrategy; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: '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, A> CallBuilder for PlacementStrategyPatchCall<'a, C, A> {} + +impl<'a, C, A> PlacementStrategyPatchCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/placementStrategies".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> PlacementStrategyPatchCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Placement strategy ID. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> PlacementStrategyPatchCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PlacementStrategyPatchCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Retrieves a list of projects, possibly filtered. +/// +/// A builder for the *list* method supported by a *project* resource. +/// It is not used directly, but through a `ProjectMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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.projects().list("profileId") +/// .sort_order("sit") +/// .sort_field("vero") +/// .search_string("nonumy") +/// .page_token("accusam") +/// .max_results(-6) +/// .add_ids("sit") +/// .add_advertiser_ids("erat") +/// .doit(); +/// # } +/// ``` +pub struct ProjectListCall<'a, C, A> + where C: '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, A> CallBuilder for ProjectListCall<'a, C, A> {} + +impl<'a, C, A> ProjectListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ProjectsListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.projects.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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/projects".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> ProjectListCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Order of sorted results, default is ASCENDING. + /// + /// Sets the *sort order* query property to the given value. + pub fn sort_order(mut self, new_value: &str) -> ProjectListCall<'a, C, A> { + self._sort_order = Some(new_value.to_string()); + self + } + /// Field by which to sort the list. + /// + /// Sets the *sort field* query property to the given value. + pub fn sort_field(mut self, new_value: &str) -> ProjectListCall<'a, C, A> { + self._sort_field = Some(new_value.to_string()); + self + } + /// Allows searching for projects by name or ID. Wildcards (*) are allowed. For example, "project*2015" will return projects with names like "project June 2015", "project April 2015", or simply "project 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 "project" will match projects with name "my project", "project 2015", or simply "project". + /// + /// Sets the *search string* query property to the given value. + pub fn search_string(mut self, new_value: &str) -> ProjectListCall<'a, C, A> { + self._search_string = Some(new_value.to_string()); + self + } + /// Value of the nextPageToken from the previous result page. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> ProjectListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Maximum number of results to return. + /// + /// Sets the *max results* query property to the given value. + pub fn max_results(mut self, new_value: i32) -> ProjectListCall<'a, C, A> { + self._max_results = Some(new_value); + self + } + /// Select only projects with these IDs. + /// + /// 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. + pub fn add_ids(mut self, new_value: &str) -> ProjectListCall<'a, C, A> { + self._ids.push(new_value.to_string()); + self + } + /// Select only projects with these advertiser IDs. + /// + /// 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. + pub fn add_advertiser_ids(mut self, new_value: &str) -> ProjectListCall<'a, C, A> { + self._advertiser_ids.push(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Gets one project by ID. +/// +/// A builder for the *get* method supported by a *project* resource. +/// It is not used directly, but through a `ProjectMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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.projects().get("profileId", "id") +/// .doit(); +/// # } +/// ``` +pub struct ProjectGetCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ProjectGetCall<'a, C, A> {} + +impl<'a, C, A> ProjectGetCall<'a, C, A> where 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: "dfareporting.projects.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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/projects/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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 ["id", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> ProjectGetCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Project ID. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> ProjectGetCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Inserts a new directory site. +/// +/// A builder for the *insert* method supported by a *directorySite* resource. +/// It is not used directly, but through a `DirectorySiteMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::DirectorySite; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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 = DirectorySite::default(); +/// +/// // You can configure optional parameters by calling 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().insert(req, "profileId") +/// .doit(); +/// # } +/// ``` +pub struct DirectorySiteInsertCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: DirectorySite, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for DirectorySiteInsertCall<'a, C, A> {} + +impl<'a, C, A> DirectorySiteInsertCall<'a, C, A> where 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.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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/directorySites".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: DirectorySite) -> DirectorySiteInsertCall<'a, C, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> DirectorySiteInsertCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DirectorySiteInsertCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> DirectorySiteInsertCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DirectorySiteInsertCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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("tempor") +/// .sort_field("ut") +/// .search_string("kasd") +/// .parent_id("diam") +/// .page_token("ut") +/// .max_results(-29) +/// .add_ids("eos") +/// .dfp_network_code("elitr") +/// .country_id("tempor") +/// .active(true) +/// .accepts_publisher_paid_placements(false) +/// .accepts_interstitial_placements(false) +/// .accepts_in_stream_video_placements(false) +/// .doit(); +/// # } +/// ``` +pub struct DirectorySiteListCall<'a, C, A> + where C: '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, A> CallBuilder for DirectorySiteListCall<'a, C, A> {} + +impl<'a, C, A> DirectorySiteListCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/directorySites".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> DirectorySiteListCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Order of sorted results, default is ASCENDING. + /// + /// Sets the *sort order* query property to the given value. + pub fn sort_order(mut self, new_value: &str) -> DirectorySiteListCall<'a, C, A> { + self._sort_order = Some(new_value.to_string()); + self + } + /// Field by which to sort the list. + /// + /// Sets the *sort field* query property to the given value. + pub fn sort_field(mut self, new_value: &str) -> DirectorySiteListCall<'a, C, A> { + self._sort_field = Some(new_value.to_string()); + self + } + /// 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". + /// + /// Sets the *search string* query property to the given value. + pub fn search_string(mut self, new_value: &str) -> DirectorySiteListCall<'a, C, A> { + self._search_string = Some(new_value.to_string()); + self + } + /// Select only directory sites with this parent ID. + /// + /// Sets the *parent id* query property to the given value. + pub fn parent_id(mut self, new_value: &str) -> DirectorySiteListCall<'a, C, A> { + self._parent_id = Some(new_value.to_string()); + self + } + /// Value of the nextPageToken from the previous result page. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> DirectorySiteListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Maximum number of results to return. + /// + /// Sets the *max results* query property to the given value. + pub fn max_results(mut self, new_value: i32) -> DirectorySiteListCall<'a, C, A> { + self._max_results = Some(new_value); + self + } + /// Select only directory sites with these IDs. + /// + /// 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. + pub fn add_ids(mut self, new_value: &str) -> DirectorySiteListCall<'a, C, A> { + self._ids.push(new_value.to_string()); + self + } + /// Select only directory sites with this DFP network code. + /// + /// Sets the *dfp_network_code* query property to the given value. + pub fn dfp_network_code(mut self, new_value: &str) -> DirectorySiteListCall<'a, C, A> { + self._dfp_network_code = Some(new_value.to_string()); + self + } + /// Select only directory sites with this country ID. + /// + /// Sets the *country id* query property to the given value. + pub fn country_id(mut self, new_value: &str) -> DirectorySiteListCall<'a, C, A> { + self._country_id = Some(new_value.to_string()); + self + } + /// Select only active directory sites. Leave blank to retrieve both active and inactive directory sites. + /// + /// Sets the *active* query property to the given value. + pub fn active(mut self, new_value: bool) -> DirectorySiteListCall<'a, C, A> { + self._active = Some(new_value); + self + } + /// Select only directory sites that accept publisher paid placements. This field can be left blank. + /// + /// Sets the *accepts publisher paid placements* query property to the given value. + pub fn accepts_publisher_paid_placements(mut self, new_value: bool) -> DirectorySiteListCall<'a, C, A> { + self._accepts_publisher_paid_placements = Some(new_value); + self + } + /// This search filter is no longer supported and will have no effect on the results returned. + /// + /// Sets the *accepts interstitial placements* query property to the given value. + pub fn accepts_interstitial_placements(mut self, new_value: bool) -> DirectorySiteListCall<'a, C, A> { + self._accepts_interstitial_placements = Some(new_value); + self + } + /// This search filter is no longer supported and will have no effect on the results returned. + /// + /// Sets the *accepts in stream video placements* query property to the given value. + pub fn accepts_in_stream_video_placements(mut self, new_value: bool) -> DirectorySiteListCall<'a, C, A> { + self._accepts_in_stream_video_placements = Some(new_value); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DirectorySiteListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for DirectorySiteGetCall<'a, C, A> {} + +impl<'a, C, A> DirectorySiteGetCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/directorySites/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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 ["id", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> DirectorySiteGetCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Directory site ID. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> DirectorySiteGetCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DirectorySiteGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::Size; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: Size, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for SizeInsertCall<'a, C, A> {} + +impl<'a, C, A> SizeInsertCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/sizes".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> SizeInsertCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> SizeInsertCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(-13) +/// .add_ids("eos") +/// .iab_standard(true) +/// .height(-63) +/// .doit(); +/// # } +/// ``` +pub struct SizeListCall<'a, C, A> + where C: '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, A> CallBuilder for SizeListCall<'a, C, A> {} + +impl<'a, C, A> SizeListCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/sizes".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> SizeListCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Select only sizes with this width. + /// + /// Sets the *width* query property to the given value. + pub fn width(mut self, new_value: i32) -> SizeListCall<'a, C, A> { + self._width = Some(new_value); + self + } + /// Select only sizes with these IDs. + /// + /// 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. + pub fn add_ids(mut self, new_value: &str) -> SizeListCall<'a, C, A> { + self._ids.push(new_value.to_string()); + self + } + /// Select only IAB standard sizes. + /// + /// Sets the *iab standard* query property to the given value. + pub fn iab_standard(mut self, new_value: bool) -> SizeListCall<'a, C, A> { + self._iab_standard = Some(new_value); + self + } + /// Select only sizes with this height. + /// + /// Sets the *height* query property to the given value. + pub fn height(mut self, new_value: i32) -> SizeListCall<'a, C, A> { + self._height = Some(new_value); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> SizeListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for SizeGetCall<'a, C, A> {} + +impl<'a, C, A> SizeGetCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/sizes/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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 ["id", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> SizeGetCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Size ID. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> SizeGetCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> SizeGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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, A> + where C: '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, A> CallBuilder for AccountActiveAdSummaryGetCall<'a, C, A> {} + +impl<'a, C, A> AccountActiveAdSummaryGetCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/accountActiveAdSummaries/{summaryAccountId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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 ["summaryAccountId", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> AccountActiveAdSummaryGetCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Account ID. + /// + /// 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. + pub fn summary_account_id(mut self, new_value: &str) -> AccountActiveAdSummaryGetCall<'a, C, A> { + self._summary_account_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountActiveAdSummaryGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::AccountUserProfile; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: AccountUserProfile, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for AccountUserProfileUpdateCall<'a, C, A> {} + +impl<'a, C, A> AccountUserProfileUpdateCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/accountUserProfiles".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> AccountUserProfileUpdateCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountUserProfileUpdateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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("et") +/// .subaccount_id("amet.") +/// .sort_order("rebum.") +/// .sort_field("sit") +/// .search_string("Lorem") +/// .page_token("sanctus") +/// .max_results(-73) +/// .add_ids("dolore") +/// .active(true) +/// .doit(); +/// # } +/// ``` +pub struct AccountUserProfileListCall<'a, C, A> + where C: '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, A> CallBuilder for AccountUserProfileListCall<'a, C, A> {} + +impl<'a, C, A> AccountUserProfileListCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/accountUserProfiles".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> AccountUserProfileListCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Select only user profiles with the specified user role ID. + /// + /// Sets the *user role id* query property to the given value. + pub fn user_role_id(mut self, new_value: &str) -> AccountUserProfileListCall<'a, C, A> { + self._user_role_id = Some(new_value.to_string()); + self + } + /// Select only user profiles with the specified subaccount ID. + /// + /// Sets the *subaccount id* query property to the given value. + pub fn subaccount_id(mut self, new_value: &str) -> AccountUserProfileListCall<'a, C, A> { + self._subaccount_id = Some(new_value.to_string()); + self + } + /// Order of sorted results, default is ASCENDING. + /// + /// Sets the *sort order* query property to the given value. + pub fn sort_order(mut self, new_value: &str) -> AccountUserProfileListCall<'a, C, A> { + self._sort_order = Some(new_value.to_string()); + self + } + /// Field by which to sort the list. + /// + /// Sets the *sort field* query property to the given value. + pub fn sort_field(mut self, new_value: &str) -> AccountUserProfileListCall<'a, C, A> { + self._sort_field = Some(new_value.to_string()); + self + } + /// 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". + /// + /// Sets the *search string* query property to the given value. + pub fn search_string(mut self, new_value: &str) -> AccountUserProfileListCall<'a, C, A> { + self._search_string = Some(new_value.to_string()); + self + } + /// Value of the nextPageToken from the previous result page. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> AccountUserProfileListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Maximum number of results to return. + /// + /// Sets the *max results* query property to the given value. + pub fn max_results(mut self, new_value: i32) -> AccountUserProfileListCall<'a, C, A> { + self._max_results = Some(new_value); + self + } + /// Select only user profiles with these IDs. + /// + /// 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. + pub fn add_ids(mut self, new_value: &str) -> AccountUserProfileListCall<'a, C, A> { + self._ids.push(new_value.to_string()); + self + } + /// Select only active user profiles. + /// + /// Sets the *active* query property to the given value. + pub fn active(mut self, new_value: bool) -> AccountUserProfileListCall<'a, C, A> { + self._active = Some(new_value); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountUserProfileListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Inserts a new account user profile. +/// +/// A builder for the *insert* method supported by a *accountUserProfile* resource. +/// It is not used directly, but through a `AccountUserProfileMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::AccountUserProfile; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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().insert(req, "profileId") +/// .doit(); +/// # } +/// ``` +pub struct AccountUserProfileInsertCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: AccountUserProfile, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for AccountUserProfileInsertCall<'a, C, A> {} + +impl<'a, C, A> AccountUserProfileInsertCall<'a, C, A> where 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.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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/accountUserProfiles".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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) -> AccountUserProfileInsertCall<'a, C, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> AccountUserProfileInsertCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountUserProfileInsertCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountUserProfileInsertCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountUserProfileInsertCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::AccountUserProfile; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: '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, A> CallBuilder for AccountUserProfilePatchCall<'a, C, A> {} + +impl<'a, C, A> AccountUserProfilePatchCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/accountUserProfiles".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> AccountUserProfilePatchCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// User profile ID. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> AccountUserProfilePatchCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountUserProfilePatchCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for AccountUserProfileGetCall<'a, C, A> {} + +impl<'a, C, A> AccountUserProfileGetCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/accountUserProfiles/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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 ["id", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> AccountUserProfileGetCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// User profile ID. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> AccountUserProfileGetCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountUserProfileGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for CountryListCall<'a, C, A> {} + +impl<'a, C, A> CountryListCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/countries".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> CountryListCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CountryListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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, A> + where C: '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, A> CallBuilder for CountryGetCall<'a, C, A> {} + +impl<'a, C, A> CountryGetCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/countries/{dartId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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 ["dartId", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> CountryGetCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Country DART ID. + /// + /// 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. + pub fn dart_id(mut self, new_value: &str) -> CountryGetCall<'a, C, A> { + self._dart_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CountryGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Gets one order document by ID. +/// +/// A builder for the *get* method supported by a *orderDocument* resource. +/// It is not used directly, but through a `OrderDocumentMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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.order_documents().get("profileId", "projectId", "id") +/// .doit(); +/// # } +/// ``` +pub struct OrderDocumentGetCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _project_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for OrderDocumentGetCall<'a, C, A> {} + +impl<'a, C, A> OrderDocumentGetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, OrderDocument)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.orderDocuments.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(("projectId", self._project_id.to_string())); + params.push(("id", self._id.to_string())); + for &field in ["alt", "profileId", "projectId", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/projects/{projectId}/orderDocuments/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId"), ("{projectId}", "projectId"), ("{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 ["id", "projectId", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> OrderDocumentGetCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Project ID for order documents. + /// + /// 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. + pub fn project_id(mut self, new_value: &str) -> OrderDocumentGetCall<'a, C, A> { + self._project_id = new_value.to_string(); + self + } + /// Order document ID. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> OrderDocumentGetCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> OrderDocumentGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> OrderDocumentGetCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> OrderDocumentGetCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Retrieves a list of order documents, possibly filtered. +/// +/// A builder for the *list* method supported by a *orderDocument* resource. +/// It is not used directly, but through a `OrderDocumentMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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.order_documents().list("profileId", "projectId") +/// .sort_order("et") +/// .sort_field("clita") +/// .add_site_id("consetetur") +/// .search_string("magna") +/// .page_token("invidunt") +/// .add_order_id("At") +/// .max_results(-15) +/// .add_ids("sit") +/// .approved(false) +/// .doit(); +/// # } +/// ``` +pub struct OrderDocumentListCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _project_id: String, + _sort_order: Option, + _sort_field: Option, + _site_id: Vec, + _search_string: Option, + _page_token: Option, + _order_id: Vec, + _max_results: Option, + _ids: Vec, + _approved: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for OrderDocumentListCall<'a, C, A> {} + +impl<'a, C, A> OrderDocumentListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, OrderDocumentsListResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.orderDocuments.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())); + params.push(("projectId", self._project_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_id.len() > 0 { + let mut s = String::new(); + for f in self._site_id.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("siteId", 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 self._order_id.len() > 0 { + let mut s = String::new(); + for f in self._order_id.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("orderId", s)); + } + 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._approved { + params.push(("approved", value.to_string())); + } + for &field in ["alt", "profileId", "projectId", "sortOrder", "sortField", "siteId", "searchString", "pageToken", "orderId", "maxResults", "ids", "approved"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/projects/{projectId}/orderDocuments".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId"), ("{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(2); + for param_name in ["projectId", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> OrderDocumentListCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Project ID for order documents. + /// + /// 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. + pub fn project_id(mut self, new_value: &str) -> OrderDocumentListCall<'a, C, A> { + self._project_id = new_value.to_string(); + self + } + /// Order of sorted results, default is ASCENDING. + /// + /// Sets the *sort order* query property to the given value. + pub fn sort_order(mut self, new_value: &str) -> OrderDocumentListCall<'a, C, A> { + self._sort_order = Some(new_value.to_string()); + self + } + /// Field by which to sort the list. + /// + /// Sets the *sort field* query property to the given value. + pub fn sort_field(mut self, new_value: &str) -> OrderDocumentListCall<'a, C, A> { + self._sort_field = Some(new_value.to_string()); + self + } + /// Select only order documents that are associated with these sites. + /// + /// Append the given value to the *site id* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + pub fn add_site_id(mut self, new_value: &str) -> OrderDocumentListCall<'a, C, A> { + self._site_id.push(new_value.to_string()); + self + } + /// Allows searching for order documents by name or ID. Wildcards (*) are allowed. For example, "orderdocument*2015" will return order documents with names like "orderdocument June 2015", "orderdocument April 2015", or simply "orderdocument 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 "orderdocument" will match order documents with name "my orderdocument", "orderdocument 2015", or simply "orderdocument". + /// + /// Sets the *search string* query property to the given value. + pub fn search_string(mut self, new_value: &str) -> OrderDocumentListCall<'a, C, A> { + self._search_string = Some(new_value.to_string()); + self + } + /// Value of the nextPageToken from the previous result page. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> OrderDocumentListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Select only order documents for specified orders. + /// + /// Append the given value to the *order id* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + pub fn add_order_id(mut self, new_value: &str) -> OrderDocumentListCall<'a, C, A> { + self._order_id.push(new_value.to_string()); + self + } + /// Maximum number of results to return. + /// + /// Sets the *max results* query property to the given value. + pub fn max_results(mut self, new_value: i32) -> OrderDocumentListCall<'a, C, A> { + self._max_results = Some(new_value); + self + } + /// Select only order documents with these IDs. + /// + /// 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. + pub fn add_ids(mut self, new_value: &str) -> OrderDocumentListCall<'a, C, A> { + self._ids.push(new_value.to_string()); + self + } + /// Select only order documents that have been approved by at least one user. + /// + /// Sets the *approved* query property to the given value. + pub fn approved(mut self, new_value: bool) -> OrderDocumentListCall<'a, C, A> { + self._approved = Some(new_value); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> OrderDocumentListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> OrderDocumentListCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> OrderDocumentListCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Gets one postal code by ID. +/// +/// A builder for the *get* method supported by a *postalCode* resource. +/// It is not used directly, but through a `PostalCodeMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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().get("profileId", "code") +/// .doit(); +/// # } +/// ``` +pub struct PostalCodeGetCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _code: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for PostalCodeGetCall<'a, C, A> {} + +impl<'a, C, A> PostalCodeGetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, PostalCode)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.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(("code", self._code.to_string())); + for &field in ["alt", "profileId", "code"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/postalCodes/{code}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{profileId}", "profileId"), ("{code}", "code")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["code", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> PostalCodeGetCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Postal code ID. + /// + /// Sets the *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. + pub fn code(mut self, new_value: &str) -> PostalCodeGetCall<'a, C, A> { + self._code = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PostalCodeGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> PostalCodeGetCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> PostalCodeGetCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for PostalCodeListCall<'a, C, A> {} + +impl<'a, C, A> PostalCodeListCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/postalCodes".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> PostalCodeListCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PostalCodeListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for BrowserListCall<'a, C, A> {} + +impl<'a, C, A> BrowserListCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/browsers".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> BrowserListCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> BrowserListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for AccountGetCall<'a, C, A> {} + +impl<'a, C, A> AccountGetCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/accounts/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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 ["id", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> AccountGetCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Account ID. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> AccountGetCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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("voluptua.") +/// .sort_field("At") +/// .search_string("dolor") +/// .page_token("vero") +/// .max_results(-81) +/// .add_ids("dolore") +/// .active(true) +/// .doit(); +/// # } +/// ``` +pub struct AccountListCall<'a, C, A> + where C: '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, A> CallBuilder for AccountListCall<'a, C, A> {} + +impl<'a, C, A> AccountListCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/accounts".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> AccountListCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Order of sorted results, default is ASCENDING. + /// + /// Sets the *sort order* query property to the given value. + pub fn sort_order(mut self, new_value: &str) -> AccountListCall<'a, C, A> { + self._sort_order = Some(new_value.to_string()); + self + } + /// Field by which to sort the list. + /// + /// Sets the *sort field* query property to the given value. + pub fn sort_field(mut self, new_value: &str) -> AccountListCall<'a, C, A> { + self._sort_field = Some(new_value.to_string()); + self + } + /// 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". + /// + /// Sets the *search string* query property to the given value. + pub fn search_string(mut self, new_value: &str) -> AccountListCall<'a, C, A> { + self._search_string = Some(new_value.to_string()); + self + } + /// Value of the nextPageToken from the previous result page. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> AccountListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Maximum number of results to return. + /// + /// Sets the *max results* query property to the given value. + pub fn max_results(mut self, new_value: i32) -> AccountListCall<'a, C, A> { + self._max_results = Some(new_value); + self + } + /// Select only accounts with these IDs. + /// + /// 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. + pub fn add_ids(mut self, new_value: &str) -> AccountListCall<'a, C, A> { + self._ids.push(new_value.to_string()); + self + } + /// Select only active accounts. Don't set this field to select both active and non-active accounts. + /// + /// Sets the *active* query property to the given value. + pub fn active(mut self, new_value: bool) -> AccountListCall<'a, C, A> { + self._active = Some(new_value); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::Account; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: Account, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for AccountUpdateCall<'a, C, A> {} + +impl<'a, C, A> AccountUpdateCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/accounts".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> AccountUpdateCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountUpdateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::Account; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: '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, A> CallBuilder for AccountPatchCall<'a, C, A> {} + +impl<'a, C, A> AccountPatchCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/accounts".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> AccountPatchCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Account ID. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> AccountPatchCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountPatchCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::Placement; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: '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, A> CallBuilder for PlacementPatchCall<'a, C, A> {} + +impl<'a, C, A> PlacementPatchCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/placements".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> PlacementPatchCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Placement ID. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> PlacementPatchCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PlacementPatchCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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("dolor") +/// .sort_field("ipsum") +/// .add_size_ids("et") +/// .add_site_ids("kasd") +/// .search_string("sed") +/// .add_pricing_types("tempor") +/// .add_placement_strategy_ids("diam") +/// .payment_source("takimata") +/// .page_token("Lorem") +/// .min_start_date("dolor") +/// .min_end_date("amet.") +/// .max_start_date("sed") +/// .max_results(-9) +/// .max_end_date("consetetur") +/// .add_ids("sea") +/// .add_group_ids("voluptua.") +/// .add_directory_site_ids("At") +/// .add_content_category_ids("sanctus") +/// .add_compatibilities("sit") +/// .add_campaign_ids("sit") +/// .archived(false) +/// .add_advertiser_ids("amet.") +/// .doit(); +/// # } +/// ``` +pub struct PlacementListCall<'a, C, A> + where C: '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, + _min_start_date: Option, + _min_end_date: Option, + _max_start_date: Option, + _max_results: Option, + _max_end_date: 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, A> CallBuilder for PlacementListCall<'a, C, A> {} + +impl<'a, C, A> PlacementListCall<'a, C, A> where 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((25 + 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._min_start_date { + params.push(("minStartDate", value.to_string())); + } + if let Some(value) = self._min_end_date { + params.push(("minEndDate", value.to_string())); + } + if let Some(value) = self._max_start_date { + params.push(("maxStartDate", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + if let Some(value) = self._max_end_date { + params.push(("maxEndDate", 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", "minStartDate", "minEndDate", "maxStartDate", "maxResults", "maxEndDate", "ids", "groupIds", "directorySiteIds", "contentCategoryIds", "compatibilities", "campaignIds", "archived", "advertiserIds"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/placements".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> PlacementListCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Order of sorted results, default is ASCENDING. + /// + /// Sets the *sort order* query property to the given value. + pub fn sort_order(mut self, new_value: &str) -> PlacementListCall<'a, C, A> { + self._sort_order = Some(new_value.to_string()); + self + } + /// Field by which to sort the list. + /// + /// Sets the *sort field* query property to the given value. + pub fn sort_field(mut self, new_value: &str) -> PlacementListCall<'a, C, A> { + self._sort_field = Some(new_value.to_string()); + self + } + /// Select only placements that are associated with these sizes. + /// + /// 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. + pub fn add_size_ids(mut self, new_value: &str) -> PlacementListCall<'a, C, A> { + self._size_ids.push(new_value.to_string()); + self + } + /// Select only placements that are associated with these sites. + /// + /// 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. + pub fn add_site_ids(mut self, new_value: &str) -> PlacementListCall<'a, C, A> { + self._site_ids.push(new_value.to_string()); + self + } + /// 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". + /// + /// Sets the *search string* query property to the given value. + pub fn search_string(mut self, new_value: &str) -> PlacementListCall<'a, C, A> { + self._search_string = Some(new_value.to_string()); + self + } + /// Select only placements with these pricing types. + /// + /// 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. + pub fn add_pricing_types(mut self, new_value: &str) -> PlacementListCall<'a, C, A> { + self._pricing_types.push(new_value.to_string()); + self + } + /// Select only placements that are associated with these placement strategies. + /// + /// 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. + pub fn add_placement_strategy_ids(mut self, new_value: &str) -> PlacementListCall<'a, C, A> { + self._placement_strategy_ids.push(new_value.to_string()); + self + } + /// Select only placements with this payment source. + /// + /// Sets the *payment source* query property to the given value. + pub fn payment_source(mut self, new_value: &str) -> PlacementListCall<'a, C, A> { + self._payment_source = Some(new_value.to_string()); + self + } + /// Value of the nextPageToken from the previous result page. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> PlacementListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Select only placements or placement groups whose start date is on or after the specified minStartDate. The date should be formatted as "yyyy-MM-dd". + /// + /// Sets the *min start date* query property to the given value. + pub fn min_start_date(mut self, new_value: &str) -> PlacementListCall<'a, C, A> { + self._min_start_date = Some(new_value.to_string()); + self + } + /// Select only placements or placement groups whose end date is on or after the specified minEndDate. The date should be formatted as "yyyy-MM-dd". + /// + /// Sets the *min end date* query property to the given value. + pub fn min_end_date(mut self, new_value: &str) -> PlacementListCall<'a, C, A> { + self._min_end_date = Some(new_value.to_string()); + self + } + /// Select only placements or placement groups whose start date is on or before the specified maxStartDate. The date should be formatted as "yyyy-MM-dd". + /// + /// Sets the *max start date* query property to the given value. + pub fn max_start_date(mut self, new_value: &str) -> PlacementListCall<'a, C, A> { + self._max_start_date = Some(new_value.to_string()); + self + } + /// Maximum number of results to return. + /// + /// Sets the *max results* query property to the given value. + pub fn max_results(mut self, new_value: i32) -> PlacementListCall<'a, C, A> { + self._max_results = Some(new_value); + self + } + /// Select only placements or placement groups whose end date is on or before the specified maxEndDate. The date should be formatted as "yyyy-MM-dd". + /// + /// Sets the *max end date* query property to the given value. + pub fn max_end_date(mut self, new_value: &str) -> PlacementListCall<'a, C, A> { + self._max_end_date = Some(new_value.to_string()); + self + } + /// Select only placements with these IDs. + /// + /// 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. + pub fn add_ids(mut self, new_value: &str) -> PlacementListCall<'a, C, A> { + self._ids.push(new_value.to_string()); + self + } + /// Select only placements that belong to these placement groups. + /// + /// 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. + pub fn add_group_ids(mut self, new_value: &str) -> PlacementListCall<'a, C, A> { + self._group_ids.push(new_value.to_string()); + self + } + /// Select only placements that are associated with these directory sites. + /// + /// 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. + pub fn add_directory_site_ids(mut self, new_value: &str) -> PlacementListCall<'a, C, A> { + self._directory_site_ids.push(new_value.to_string()); + self + } + /// Select only placements that are associated with these content categories. + /// + /// 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. + pub fn add_content_category_ids(mut self, new_value: &str) -> PlacementListCall<'a, C, A> { + self._content_category_ids.push(new_value.to_string()); + self + } + /// 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. + /// + /// 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. + pub fn add_compatibilities(mut self, new_value: &str) -> PlacementListCall<'a, C, A> { + self._compatibilities.push(new_value.to_string()); + self + } + /// Select only placements that belong to these campaigns. + /// + /// 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. + pub fn add_campaign_ids(mut self, new_value: &str) -> PlacementListCall<'a, C, A> { + self._campaign_ids.push(new_value.to_string()); + self + } + /// Select only archived placements. Don't set this field to select both archived and non-archived placements. + /// + /// Sets the *archived* query property to the given value. + pub fn archived(mut self, new_value: bool) -> PlacementListCall<'a, C, A> { + self._archived = Some(new_value); + self + } + /// Select only placements that belong to these advertisers. + /// + /// 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. + pub fn add_advertiser_ids(mut self, new_value: &str) -> PlacementListCall<'a, C, A> { + self._advertiser_ids.push(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PlacementListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::Placement; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: Placement, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for PlacementInsertCall<'a, C, A> {} + +impl<'a, C, A> PlacementInsertCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/placements".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> PlacementInsertCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PlacementInsertCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// use dfareporting2d2::Placement; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _request: Placement, + _profile_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for PlacementUpdateCall<'a, C, A> {} + +impl<'a, C, A> PlacementUpdateCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/placements".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> PlacementUpdateCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PlacementUpdateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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("eirmod") +/// .add_placement_ids("elitr") +/// .campaign_id("gubergren") +/// .doit(); +/// # } +/// ``` +pub struct PlacementGeneratetagCall<'a, C, A> + where C: '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, A> CallBuilder for PlacementGeneratetagCall<'a, C, A> {} + +impl<'a, C, A> PlacementGeneratetagCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/placements/generatetags".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> PlacementGeneratetagCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Tag formats to generate for these placements. + /// + /// 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. + pub fn add_tag_formats(mut self, new_value: &str) -> PlacementGeneratetagCall<'a, C, A> { + self._tag_formats.push(new_value.to_string()); + self + } + /// Generate tags for these placements. + /// + /// 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. + pub fn add_placement_ids(mut self, new_value: &str) -> PlacementGeneratetagCall<'a, C, A> { + self._placement_ids.push(new_value.to_string()); + self + } + /// Generate placements belonging to this campaign. This is a required field. + /// + /// Sets the *campaign id* query property to the given value. + pub fn campaign_id(mut self, new_value: &str) -> PlacementGeneratetagCall<'a, C, A> { + self._campaign_id = Some(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PlacementGeneratetagCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_dfareporting2d2 as dfareporting2d2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use dfareporting2d2::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, A> + where C: 'a, A: 'a { + + hub: &'a Dfareporting, + _profile_id: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for PlacementGetCall<'a, C, A> {} + +impl<'a, C, A> PlacementGetCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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.2/userprofiles/{profileId}/placements/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Dfatrafficking.as_ref().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 ["id", "profileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// User profile ID associated with this request. + /// + /// 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. + pub fn profile_id(mut self, new_value: &str) -> PlacementGetCall<'a, C, A> { + self._profile_id = new_value.to_string(); + self + } + /// Placement ID. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> PlacementGetCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> PlacementGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Dfatrafficking`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + diff --git a/gen/dns1-cli/Cargo.toml b/gen/dns1-cli/Cargo.toml index d1d7c99c8b..4507b8957f 100644 --- a/gen/dns1-cli/Cargo.toml +++ b/gen/dns1-cli/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-dns1-cli" -version = "0.3.2+20150624" +version = "0.3.2+20150729" authors = ["Sebastian Thiel "] description = "A complete library to interact with dns (protocol v1)" repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/dns1-cli" diff --git a/gen/dns1-cli/README.md b/gen/dns1-cli/README.md index 9a99fa7a44..345237b3ea 100644 --- a/gen/dns1-cli/README.md +++ b/gen/dns1-cli/README.md @@ -24,7 +24,7 @@ Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/ma # Usage -This documentation was generated from the *dns* API at revision *20150624*. The CLI is at version *0.3.2*. +This documentation was generated from the *dns* API at revision *20150729*. The CLI is at version *0.3.2*. ```bash dns1 [options] diff --git a/gen/dns1-cli/mkdocs.yml b/gen/dns1-cli/mkdocs.yml index d53161188b..276a01faef 100644 --- a/gen/dns1-cli/mkdocs.yml +++ b/gen/dns1-cli/mkdocs.yml @@ -1,4 +1,4 @@ -site_name: dns v0.3.2+20150624 +site_name: dns v0.3.2+20150729 site_url: http://byron.github.io/google-apis-rs/google-dns1-cli site_description: Write integrating applications with bcore diff --git a/gen/dns1-cli/src/main.rs b/gen/dns1-cli/src/main.rs index 4169078677..e59f725a08 100644 --- a/gen/dns1-cli/src/main.rs +++ b/gen/dns1-cli/src/main.rs @@ -1025,7 +1025,7 @@ fn main() { let mut app = App::new("dns1") .author("Sebastian Thiel ") - .version("0.3.2+20150624") + .version("0.3.2+20150729") .about("The Google Cloud DNS API provides services for configuring and serving authoritative DNS records.") .after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_dns1_cli") .arg(Arg::with_name("url") diff --git a/gen/dns1/Cargo.toml b/gen/dns1/Cargo.toml index 8f13f5defe..9a0a76b533 100644 --- a/gen/dns1/Cargo.toml +++ b/gen/dns1/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-dns1" -version = "0.1.9+20150624" +version = "0.1.9+20150729" authors = ["Sebastian Thiel "] description = "A complete library to interact with dns (protocol v1)" repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/dns1" diff --git a/gen/dns1/README.md b/gen/dns1/README.md index 2eead3eac8..018b891038 100644 --- a/gen/dns1/README.md +++ b/gen/dns1/README.md @@ -5,7 +5,7 @@ DO NOT EDIT ! --> The `google-dns1` library allows access to all features of the *Google dns* service. -This documentation was generated from *dns* crate version *0.1.9+20150624*, where *20150624* is the exact revision of the *dns:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +This documentation was generated from *dns* crate version *0.1.9+20150729*, where *20150729* is the exact revision of the *dns:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. Everything else about the *dns* *v1* API can be found at the [official documentation site](https://developers.google.com/cloud-dns). diff --git a/gen/dns1/src/lib.rs b/gen/dns1/src/lib.rs index 9b225f187c..484245d087 100644 --- a/gen/dns1/src/lib.rs +++ b/gen/dns1/src/lib.rs @@ -2,7 +2,7 @@ // This file was generated automatically from 'src/mako/api/lib.rs.mako' // DO NOT EDIT ! -//! This documentation was generated from *dns* crate version *0.1.9+20150624*, where *20150624* is the exact revision of the *dns:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +//! This documentation was generated from *dns* crate version *0.1.9+20150729*, where *20150729* is the exact revision of the *dns:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. //! //! Everything else about the *dns* *v1* API can be found at the //! [official documentation site](https://developers.google.com/cloud-dns). diff --git a/gen/dns1/src/lib.rs.in b/gen/dns1/src/lib.rs.in index 46e3b19f09..efb3d3b86e 100644 --- a/gen/dns1/src/lib.rs.in +++ b/gen/dns1/src/lib.rs.in @@ -43,6 +43,9 @@ pub enum Scope { /// View and manage your data across Google Cloud Platform services CloudPlatform, + + /// View your data across Google Cloud Platform services + CloudPlatformReadOnly, } impl AsRef for Scope { @@ -51,6 +54,7 @@ impl AsRef for Scope { 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", + Scope::CloudPlatformReadOnly => "https://www.googleapis.com/auth/cloud-platform.read-only", } } } diff --git a/gen/doubleclickbidmanager1-cli/Cargo.toml b/gen/doubleclickbidmanager1-cli/Cargo.toml index 85aef51598..65f452af71 100644 --- a/gen/doubleclickbidmanager1-cli/Cargo.toml +++ b/gen/doubleclickbidmanager1-cli/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-doubleclickbidmanager1-cli" -version = "0.3.2+20150326" +version = "0.3.2+20150925" 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-cli" diff --git a/gen/doubleclickbidmanager1-cli/README.md b/gen/doubleclickbidmanager1-cli/README.md index 731ffbbaa0..8a35b08dd3 100644 --- a/gen/doubleclickbidmanager1-cli/README.md +++ b/gen/doubleclickbidmanager1-cli/README.md @@ -24,7 +24,7 @@ Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/ma # Usage -This documentation was generated from the *DoubleClick Bid Manager* API at revision *20150326*. The CLI is at version *0.3.2*. +This documentation was generated from the *DoubleClick Bid Manager* API at revision *20150925*. The CLI is at version *0.3.2*. ```bash doubleclickbidmanager1 [options] diff --git a/gen/doubleclickbidmanager1-cli/mkdocs.yml b/gen/doubleclickbidmanager1-cli/mkdocs.yml index 822d67604c..479270220b 100644 --- a/gen/doubleclickbidmanager1-cli/mkdocs.yml +++ b/gen/doubleclickbidmanager1-cli/mkdocs.yml @@ -1,4 +1,4 @@ -site_name: DoubleClick Bid Manager v0.3.2+20150326 +site_name: DoubleClick Bid Manager v0.3.2+20150925 site_url: http://byron.github.io/google-apis-rs/google-doubleclickbidmanager1-cli site_description: Write integrating applications with bcore diff --git a/gen/doubleclickbidmanager1-cli/src/main.rs b/gen/doubleclickbidmanager1-cli/src/main.rs index 71607218f8..1059493816 100644 --- a/gen/doubleclickbidmanager1-cli/src/main.rs +++ b/gen/doubleclickbidmanager1-cli/src/main.rs @@ -68,11 +68,12 @@ impl<'n, 'a> Engine<'n, 'a> { let type_info: Option<(&'static str, JsonTypeInfo)> = match &temp_cursor.to_string()[..] { + "file-spec" => Some(("fileSpec", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "filter-type" => Some(("filterType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "filter-ids" => Some(("filterIds", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), "format" => Some(("format", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), _ => { - let suggestion = FieldCursor::did_you_mean(key, &vec!["filter-ids", "filter-type", "format"]); + let suggestion = FieldCursor::did_you_mean(key, &vec!["file-spec", "filter-ids", "filter-type", "format"]); err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); None } @@ -895,7 +896,7 @@ fn main() { let mut app = App::new("doubleclickbidmanager1") .author("Sebastian Thiel ") - .version("0.3.2+20150326") + .version("0.3.2+20150925") .about("API for viewing and managing your reports in DoubleClick Bid Manager.") .after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_doubleclickbidmanager1_cli") .arg(Arg::with_name("folder") diff --git a/gen/doubleclickbidmanager1/Cargo.toml b/gen/doubleclickbidmanager1/Cargo.toml index 990b67b679..bf3659e600 100644 --- a/gen/doubleclickbidmanager1/Cargo.toml +++ b/gen/doubleclickbidmanager1/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-doubleclickbidmanager1" -version = "0.1.9+20150326" +version = "0.1.9+20150925" 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" diff --git a/gen/doubleclickbidmanager1/README.md b/gen/doubleclickbidmanager1/README.md index 5811cc7a69..93ec475ceb 100644 --- a/gen/doubleclickbidmanager1/README.md +++ b/gen/doubleclickbidmanager1/README.md @@ -5,7 +5,7 @@ DO NOT EDIT ! --> 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.9+20150326*, where *20150326* is the exact revision of the *doubleclickbidmanager:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +This documentation was generated from *DoubleClick Bid Manager* crate version *0.1.9+20150925*, where *20150925* is the exact revision of the *doubleclickbidmanager:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. Everything else about the *DoubleClick Bid Manager* *v1* API can be found at the [official documentation site](https://developers.google.com/bid-manager/). diff --git a/gen/doubleclickbidmanager1/src/lib.rs b/gen/doubleclickbidmanager1/src/lib.rs index 2e3c35830a..765f32209b 100644 --- a/gen/doubleclickbidmanager1/src/lib.rs +++ b/gen/doubleclickbidmanager1/src/lib.rs @@ -2,7 +2,7 @@ // This file was generated automatically from 'src/mako/api/lib.rs.mako' // DO NOT EDIT ! -//! This documentation was generated from *DoubleClick Bid Manager* crate version *0.1.9+20150326*, where *20150326* is the exact revision of the *doubleclickbidmanager:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +//! This documentation was generated from *DoubleClick Bid Manager* crate version *0.1.9+20150925*, where *20150925* is the exact revision of the *doubleclickbidmanager:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. //! //! Everything else about the *DoubleClick Bid Manager* *v1* API can be found at the //! [official documentation site](https://developers.google.com/bid-manager/). diff --git a/gen/doubleclickbidmanager1/src/lib.rs.in b/gen/doubleclickbidmanager1/src/lib.rs.in index 7bbc53834e..a1fd0e7164 100644 --- a/gen/doubleclickbidmanager1/src/lib.rs.in +++ b/gen/doubleclickbidmanager1/src/lib.rs.in @@ -144,6 +144,9 @@ impl<'a, C, A> DoubleClickBidManager /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct DownloadLineItemsRequest { + /// File specification (column names, types, order) in which the line items will be returned. Default to EWF. + #[serde(rename="fileSpec")] + pub file_spec: Option, /// Filter type used to filter line items to fetch. #[serde(rename="filterType")] pub filter_type: Option, @@ -526,7 +529,7 @@ impl ResponseResult for Query {} /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct DownloadLineItemsResponse { - /// Retrieved line items in CSV format. Refer to Entity Write File Format for more information on file format. + /// Retrieved line items in CSV format. Refer to Entity Write File Format or Structured Data File Format for more information on file formats. #[serde(rename="lineItems")] pub line_items: Option, } diff --git a/gen/doubleclicksearch2-cli/Cargo.toml b/gen/doubleclicksearch2-cli/Cargo.toml index 2ed174f930..04f6ff992c 100644 --- a/gen/doubleclicksearch2-cli/Cargo.toml +++ b/gen/doubleclicksearch2-cli/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-doubleclicksearch2-cli" -version = "0.3.2+20150708" +version = "0.3.2+20151006" 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-cli" diff --git a/gen/doubleclicksearch2-cli/README.md b/gen/doubleclicksearch2-cli/README.md index 2b4d198b6a..3e2b95acfb 100644 --- a/gen/doubleclicksearch2-cli/README.md +++ b/gen/doubleclicksearch2-cli/README.md @@ -24,7 +24,7 @@ Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/ma # Usage -This documentation was generated from the *doubleclicksearch* API at revision *20150708*. The CLI is at version *0.3.2*. +This documentation was generated from the *doubleclicksearch* API at revision *20151006*. The CLI is at version *0.3.2*. ```bash doubleclicksearch2 [options] diff --git a/gen/doubleclicksearch2-cli/mkdocs.yml b/gen/doubleclicksearch2-cli/mkdocs.yml index 3db939f300..9d8cbe9b7b 100644 --- a/gen/doubleclicksearch2-cli/mkdocs.yml +++ b/gen/doubleclicksearch2-cli/mkdocs.yml @@ -1,4 +1,4 @@ -site_name: doubleclicksearch v0.3.2+20150708 +site_name: doubleclicksearch v0.3.2+20151006 site_url: http://byron.github.io/google-apis-rs/google-doubleclicksearch2-cli site_description: Write integrating applications with bcore diff --git a/gen/doubleclicksearch2-cli/src/main.rs b/gen/doubleclicksearch2-cli/src/main.rs index dcba0ed8af..d8cc91bebc 100644 --- a/gen/doubleclicksearch2-cli/src/main.rs +++ b/gen/doubleclicksearch2-cli/src/main.rs @@ -1291,7 +1291,7 @@ fn main() { let mut app = App::new("doubleclicksearch2") .author("Sebastian Thiel ") - .version("0.3.2+20150708") + .version("0.3.2+20151006") .about("Report and modify your advertising data in DoubleClick Search (for example, campaigns, ad groups, keywords, and conversions).") .after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_doubleclicksearch2_cli") .arg(Arg::with_name("url") diff --git a/gen/doubleclicksearch2/Cargo.toml b/gen/doubleclicksearch2/Cargo.toml index fdd8018c86..250d1b776b 100644 --- a/gen/doubleclicksearch2/Cargo.toml +++ b/gen/doubleclicksearch2/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-doubleclicksearch2" -version = "0.1.9+20150708" +version = "0.1.9+20151006" 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" diff --git a/gen/doubleclicksearch2/README.md b/gen/doubleclicksearch2/README.md index f4027dc475..1b164dbbdd 100644 --- a/gen/doubleclicksearch2/README.md +++ b/gen/doubleclicksearch2/README.md @@ -5,7 +5,7 @@ DO NOT EDIT ! --> The `google-doubleclicksearch2` library allows access to all features of the *Google doubleclicksearch* service. -This documentation was generated from *doubleclicksearch* crate version *0.1.9+20150708*, where *20150708* is the exact revision of the *doubleclicksearch:v2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +This documentation was generated from *doubleclicksearch* crate version *0.1.9+20151006*, where *20151006* is the exact revision of the *doubleclicksearch:v2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. Everything else about the *doubleclicksearch* *v2* API can be found at the [official documentation site](https://developers.google.com/doubleclick-search/). diff --git a/gen/doubleclicksearch2/src/lib.rs b/gen/doubleclicksearch2/src/lib.rs index 864ac687ca..4df184edbd 100644 --- a/gen/doubleclicksearch2/src/lib.rs +++ b/gen/doubleclicksearch2/src/lib.rs @@ -2,7 +2,7 @@ // This file was generated automatically from 'src/mako/api/lib.rs.mako' // DO NOT EDIT ! -//! This documentation was generated from *doubleclicksearch* crate version *0.1.9+20150708*, where *20150708* is the exact revision of the *doubleclicksearch:v2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +//! This documentation was generated from *doubleclicksearch* crate version *0.1.9+20151006*, where *20151006* is the exact revision of the *doubleclicksearch:v2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. //! //! Everything else about the *doubleclicksearch* *v2* API can be found at the //! [official documentation site](https://developers.google.com/doubleclick-search/). diff --git a/gen/doubleclicksearch2/src/lib.rs.in b/gen/doubleclicksearch2/src/lib.rs.in index 3f9d5e59e2..9ffc7dd116 100644 --- a/gen/doubleclicksearch2/src/lib.rs.in +++ b/gen/doubleclicksearch2/src/lib.rs.in @@ -399,6 +399,9 @@ pub struct ReportApiColumnSpec { /// Synchronous report only. Set to true to group by this column. Defaults to false. #[serde(rename="groupByColumn")] pub group_by_column: Option, + /// Provide different source for product items. Acceptable values are "advertised" and "sold". + #[serde(rename="productReportPerspective")] + pub product_report_perspective: Option, /// 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(rename="endDate")] pub end_date: Option, @@ -415,7 +418,7 @@ pub struct ReportApiColumnSpec { /// Name of a DoubleClick Search column to include in the report. #[serde(rename="columnName")] pub column_name: Option, - /// The platform that is used to provide data for the custom dimension. Acceptable values are "Floodlight". + /// The platform that is used to provide data for the custom dimension. Acceptable values are "floodlight". #[serde(rename="platformSource")] pub platform_source: Option, /// 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. diff --git a/gen/drive2-cli/Cargo.toml b/gen/drive2-cli/Cargo.toml index d2ebd08ccf..8f0524a3e3 100644 --- a/gen/drive2-cli/Cargo.toml +++ b/gen/drive2-cli/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-drive2-cli" -version = "0.3.2+20150709" +version = "0.3.2+20151008" 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-cli" diff --git a/gen/drive2-cli/README.md b/gen/drive2-cli/README.md index 690eececd8..0d47c5700d 100644 --- a/gen/drive2-cli/README.md +++ b/gen/drive2-cli/README.md @@ -24,7 +24,7 @@ Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/ma # Usage -This documentation was generated from the *drive* API at revision *20150709*. The CLI is at version *0.3.2*. +This documentation was generated from the *drive* API at revision *20151008*. The CLI is at version *0.3.2*. ```bash drive2 [options] @@ -55,6 +55,7 @@ drive2 [options] copy (-r )... [-p ]... [-o ] delete [-p ]... empty-trash [-p ]... + generate-ids [-p ]... [-o ] get [-p ]... [-o ] insert (-r )... (-u (simple|resumable) -f [-m ]) [-p ]... [-o ] list [-p ]... [-o ] diff --git a/gen/drive2-cli/mkdocs.yml b/gen/drive2-cli/mkdocs.yml index c2a3518fe4..ca59cb8586 100644 --- a/gen/drive2-cli/mkdocs.yml +++ b/gen/drive2-cli/mkdocs.yml @@ -1,4 +1,4 @@ -site_name: drive v0.3.2+20150709 +site_name: drive v0.3.2+20151008 site_url: http://byron.github.io/google-apis-rs/google-drive2-cli site_description: Write integrating applications with bcore @@ -29,6 +29,7 @@ pages: - ['files_copy.md', 'Files', 'Copy'] - ['files_delete.md', 'Files', 'Delete'] - ['files_empty-trash.md', 'Files', 'Empty Trash'] +- ['files_generate-ids.md', 'Files', 'Generate Ids'] - ['files_get.md', 'Files', 'Get'] - ['files_insert.md', 'Files', 'Insert'] - ['files_list.md', 'Files', 'List'] diff --git a/gen/drive2-cli/src/main.rs b/gen/drive2-cli/src/main.rs index d6d3fa510e..7b23d1248b 100644 --- a/gen/drive2-cli/src/main.rs +++ b/gen/drive2-cli/src/main.rs @@ -739,6 +739,9 @@ impl<'n, 'a> Engine<'n, 'a> { "page-token" => { call = call.page_token(value.unwrap_or("")); }, + "order-by" => { + call = call.order_by(value.unwrap_or("")); + }, "max-results" => { call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer")); }, @@ -755,7 +758,7 @@ impl<'n, 'a> Engine<'n, 'a> { err.issues.push(CLIError::UnknownParameter(key.to_string(), {let mut v = Vec::new(); v.extend(self.gp.iter().map(|v|*v)); - v.extend(["q", "page-token", "max-results"].iter().map(|v|*v)); + v.extend(["q", "page-token", "max-results", "order-by"].iter().map(|v|*v)); v } )); } } @@ -1328,8 +1331,7 @@ impl<'n, 'a> Engine<'n, 'a> { "version" => Some(("version", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "export-links" => Some(("exportLinks", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Map })), "shared" => Some(("shared", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), - "thumbnail.mime-type" => Some(("thumbnail.mimeType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), - "thumbnail.image" => Some(("thumbnail.image", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "full-file-extension" => Some(("fullFileExtension", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "open-with-links" => Some(("openWithLinks", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Map })), "image-media-metadata.exposure-bias" => Some(("imageMediaMetadata.exposureBias", JsonTypeInfo { jtype: JsonType::Float, ctype: ComplexType::Pod })), "image-media-metadata.exposure-time" => Some(("imageMediaMetadata.exposureTime", JsonTypeInfo { jtype: JsonType::Float, ctype: ComplexType::Pod })), @@ -1370,6 +1372,8 @@ impl<'n, 'a> Engine<'n, 'a> { "alternate-link" => Some(("alternateLink", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "title" => Some(("title", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "modified-by-me-date" => Some(("modifiedByMeDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "thumbnail.mime-type" => Some(("thumbnail.mimeType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "thumbnail.image" => Some(("thumbnail.image", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "download-url" => Some(("downloadUrl", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "user-permission.with-link" => Some(("userPermission.withLink", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), "user-permission.domain" => Some(("userPermission.domain", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), @@ -1393,7 +1397,7 @@ impl<'n, 'a> Engine<'n, 'a> { "self-link" => Some(("selfLink", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "modified-date" => Some(("modifiedDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), _ => { - let suggestion = FieldCursor::did_you_mean(key, &vec!["additional-roles", "alternate-link", "altitude", "aperture", "app-data-contents", "auth-key", "camera-make", "camera-model", "can-comment", "color-space", "copyable", "created-date", "date", "default-open-with-link", "description", "display-name", "domain", "download-url", "duration-millis", "editable", "email-address", "embed-link", "etag", "explicitly-trashed", "export-links", "exposure-bias", "exposure-mode", "exposure-time", "file-extension", "file-size", "flash-used", "focal-length", "folder-color-rgb", "head-revision-id", "height", "hidden", "icon-link", "id", "image", "image-media-metadata", "indexable-text", "is-authenticated-user", "iso-speed", "kind", "labels", "last-modifying-user", "last-modifying-user-name", "last-viewed-by-me-date", "latitude", "lens", "location", "longitude", "marked-viewed-by-me-date", "max-aperture-value", "md5-checksum", "metering-mode", "mime-type", "modified-by-me-date", "modified-date", "name", "open-with-links", "original-filename", "owned-by-me", "owner-names", "permission-id", "photo-link", "picture", "quota-bytes-used", "restricted", "role", "rotation", "self-link", "sensor", "shareable", "shared", "shared-with-me-date", "sharing-user", "spaces", "starred", "subject-distance", "text", "thumbnail", "thumbnail-link", "title", "trashed", "type", "url", "user-permission", "value", "version", "video-media-metadata", "viewed", "web-content-link", "web-view-link", "white-balance", "width", "with-link", "writers-can-share"]); + let suggestion = FieldCursor::did_you_mean(key, &vec!["additional-roles", "alternate-link", "altitude", "aperture", "app-data-contents", "auth-key", "camera-make", "camera-model", "can-comment", "color-space", "copyable", "created-date", "date", "default-open-with-link", "description", "display-name", "domain", "download-url", "duration-millis", "editable", "email-address", "embed-link", "etag", "explicitly-trashed", "export-links", "exposure-bias", "exposure-mode", "exposure-time", "file-extension", "file-size", "flash-used", "focal-length", "folder-color-rgb", "full-file-extension", "head-revision-id", "height", "hidden", "icon-link", "id", "image", "image-media-metadata", "indexable-text", "is-authenticated-user", "iso-speed", "kind", "labels", "last-modifying-user", "last-modifying-user-name", "last-viewed-by-me-date", "latitude", "lens", "location", "longitude", "marked-viewed-by-me-date", "max-aperture-value", "md5-checksum", "metering-mode", "mime-type", "modified-by-me-date", "modified-date", "name", "open-with-links", "original-filename", "owned-by-me", "owner-names", "permission-id", "photo-link", "picture", "quota-bytes-used", "restricted", "role", "rotation", "self-link", "sensor", "shareable", "shared", "shared-with-me-date", "sharing-user", "spaces", "starred", "subject-distance", "text", "thumbnail", "thumbnail-link", "title", "trashed", "type", "url", "user-permission", "value", "version", "video-media-metadata", "viewed", "web-content-link", "web-view-link", "white-balance", "width", "with-link", "writers-can-share"]); err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); None } @@ -1563,6 +1567,65 @@ impl<'n, 'a> Engine<'n, 'a> { } } + fn _files_generate_ids(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.files().generate_ids(); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "space" => { + call = call.space(value.unwrap_or("")); + }, + "max-results" => { + call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["max-results", "space"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + fn _files_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) -> Result<(), DoitError> { let mut download_mode = false; @@ -1699,8 +1762,7 @@ impl<'n, 'a> Engine<'n, 'a> { "version" => Some(("version", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "export-links" => Some(("exportLinks", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Map })), "shared" => Some(("shared", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), - "thumbnail.mime-type" => Some(("thumbnail.mimeType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), - "thumbnail.image" => Some(("thumbnail.image", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "full-file-extension" => Some(("fullFileExtension", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "open-with-links" => Some(("openWithLinks", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Map })), "image-media-metadata.exposure-bias" => Some(("imageMediaMetadata.exposureBias", JsonTypeInfo { jtype: JsonType::Float, ctype: ComplexType::Pod })), "image-media-metadata.exposure-time" => Some(("imageMediaMetadata.exposureTime", JsonTypeInfo { jtype: JsonType::Float, ctype: ComplexType::Pod })), @@ -1741,6 +1803,8 @@ impl<'n, 'a> Engine<'n, 'a> { "alternate-link" => Some(("alternateLink", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "title" => Some(("title", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "modified-by-me-date" => Some(("modifiedByMeDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "thumbnail.mime-type" => Some(("thumbnail.mimeType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "thumbnail.image" => Some(("thumbnail.image", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "download-url" => Some(("downloadUrl", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "user-permission.with-link" => Some(("userPermission.withLink", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), "user-permission.domain" => Some(("userPermission.domain", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), @@ -1764,7 +1828,7 @@ impl<'n, 'a> Engine<'n, 'a> { "self-link" => Some(("selfLink", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "modified-date" => Some(("modifiedDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), _ => { - let suggestion = FieldCursor::did_you_mean(key, &vec!["additional-roles", "alternate-link", "altitude", "aperture", "app-data-contents", "auth-key", "camera-make", "camera-model", "can-comment", "color-space", "copyable", "created-date", "date", "default-open-with-link", "description", "display-name", "domain", "download-url", "duration-millis", "editable", "email-address", "embed-link", "etag", "explicitly-trashed", "export-links", "exposure-bias", "exposure-mode", "exposure-time", "file-extension", "file-size", "flash-used", "focal-length", "folder-color-rgb", "head-revision-id", "height", "hidden", "icon-link", "id", "image", "image-media-metadata", "indexable-text", "is-authenticated-user", "iso-speed", "kind", "labels", "last-modifying-user", "last-modifying-user-name", "last-viewed-by-me-date", "latitude", "lens", "location", "longitude", "marked-viewed-by-me-date", "max-aperture-value", "md5-checksum", "metering-mode", "mime-type", "modified-by-me-date", "modified-date", "name", "open-with-links", "original-filename", "owned-by-me", "owner-names", "permission-id", "photo-link", "picture", "quota-bytes-used", "restricted", "role", "rotation", "self-link", "sensor", "shareable", "shared", "shared-with-me-date", "sharing-user", "spaces", "starred", "subject-distance", "text", "thumbnail", "thumbnail-link", "title", "trashed", "type", "url", "user-permission", "value", "version", "video-media-metadata", "viewed", "web-content-link", "web-view-link", "white-balance", "width", "with-link", "writers-can-share"]); + let suggestion = FieldCursor::did_you_mean(key, &vec!["additional-roles", "alternate-link", "altitude", "aperture", "app-data-contents", "auth-key", "camera-make", "camera-model", "can-comment", "color-space", "copyable", "created-date", "date", "default-open-with-link", "description", "display-name", "domain", "download-url", "duration-millis", "editable", "email-address", "embed-link", "etag", "explicitly-trashed", "export-links", "exposure-bias", "exposure-mode", "exposure-time", "file-extension", "file-size", "flash-used", "focal-length", "folder-color-rgb", "full-file-extension", "head-revision-id", "height", "hidden", "icon-link", "id", "image", "image-media-metadata", "indexable-text", "is-authenticated-user", "iso-speed", "kind", "labels", "last-modifying-user", "last-modifying-user-name", "last-viewed-by-me-date", "latitude", "lens", "location", "longitude", "marked-viewed-by-me-date", "max-aperture-value", "md5-checksum", "metering-mode", "mime-type", "modified-by-me-date", "modified-date", "name", "open-with-links", "original-filename", "owned-by-me", "owner-names", "permission-id", "photo-link", "picture", "quota-bytes-used", "restricted", "role", "rotation", "self-link", "sensor", "shareable", "shared", "shared-with-me-date", "sharing-user", "spaces", "starred", "subject-distance", "text", "thumbnail", "thumbnail-link", "title", "trashed", "type", "url", "user-permission", "value", "version", "video-media-metadata", "viewed", "web-content-link", "web-view-link", "white-balance", "width", "with-link", "writers-can-share"]); err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); None } @@ -1871,6 +1935,9 @@ impl<'n, 'a> Engine<'n, 'a> { "page-token" => { call = call.page_token(value.unwrap_or("")); }, + "order-by" => { + call = call.order_by(value.unwrap_or("")); + }, "max-results" => { call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer")); }, @@ -1890,7 +1957,7 @@ impl<'n, 'a> Engine<'n, 'a> { err.issues.push(CLIError::UnknownParameter(key.to_string(), {let mut v = Vec::new(); v.extend(self.gp.iter().map(|v|*v)); - v.extend(["projection", "max-results", "q", "page-token", "spaces", "corpus"].iter().map(|v|*v)); + v.extend(["order-by", "projection", "max-results", "q", "page-token", "spaces", "corpus"].iter().map(|v|*v)); v } )); } } @@ -1986,8 +2053,7 @@ impl<'n, 'a> Engine<'n, 'a> { "version" => Some(("version", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "export-links" => Some(("exportLinks", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Map })), "shared" => Some(("shared", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), - "thumbnail.mime-type" => Some(("thumbnail.mimeType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), - "thumbnail.image" => Some(("thumbnail.image", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "full-file-extension" => Some(("fullFileExtension", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "open-with-links" => Some(("openWithLinks", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Map })), "image-media-metadata.exposure-bias" => Some(("imageMediaMetadata.exposureBias", JsonTypeInfo { jtype: JsonType::Float, ctype: ComplexType::Pod })), "image-media-metadata.exposure-time" => Some(("imageMediaMetadata.exposureTime", JsonTypeInfo { jtype: JsonType::Float, ctype: ComplexType::Pod })), @@ -2028,6 +2094,8 @@ impl<'n, 'a> Engine<'n, 'a> { "alternate-link" => Some(("alternateLink", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "title" => Some(("title", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "modified-by-me-date" => Some(("modifiedByMeDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "thumbnail.mime-type" => Some(("thumbnail.mimeType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "thumbnail.image" => Some(("thumbnail.image", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "download-url" => Some(("downloadUrl", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "user-permission.with-link" => Some(("userPermission.withLink", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), "user-permission.domain" => Some(("userPermission.domain", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), @@ -2051,7 +2119,7 @@ impl<'n, 'a> Engine<'n, 'a> { "self-link" => Some(("selfLink", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "modified-date" => Some(("modifiedDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), _ => { - let suggestion = FieldCursor::did_you_mean(key, &vec!["additional-roles", "alternate-link", "altitude", "aperture", "app-data-contents", "auth-key", "camera-make", "camera-model", "can-comment", "color-space", "copyable", "created-date", "date", "default-open-with-link", "description", "display-name", "domain", "download-url", "duration-millis", "editable", "email-address", "embed-link", "etag", "explicitly-trashed", "export-links", "exposure-bias", "exposure-mode", "exposure-time", "file-extension", "file-size", "flash-used", "focal-length", "folder-color-rgb", "head-revision-id", "height", "hidden", "icon-link", "id", "image", "image-media-metadata", "indexable-text", "is-authenticated-user", "iso-speed", "kind", "labels", "last-modifying-user", "last-modifying-user-name", "last-viewed-by-me-date", "latitude", "lens", "location", "longitude", "marked-viewed-by-me-date", "max-aperture-value", "md5-checksum", "metering-mode", "mime-type", "modified-by-me-date", "modified-date", "name", "open-with-links", "original-filename", "owned-by-me", "owner-names", "permission-id", "photo-link", "picture", "quota-bytes-used", "restricted", "role", "rotation", "self-link", "sensor", "shareable", "shared", "shared-with-me-date", "sharing-user", "spaces", "starred", "subject-distance", "text", "thumbnail", "thumbnail-link", "title", "trashed", "type", "url", "user-permission", "value", "version", "video-media-metadata", "viewed", "web-content-link", "web-view-link", "white-balance", "width", "with-link", "writers-can-share"]); + let suggestion = FieldCursor::did_you_mean(key, &vec!["additional-roles", "alternate-link", "altitude", "aperture", "app-data-contents", "auth-key", "camera-make", "camera-model", "can-comment", "color-space", "copyable", "created-date", "date", "default-open-with-link", "description", "display-name", "domain", "download-url", "duration-millis", "editable", "email-address", "embed-link", "etag", "explicitly-trashed", "export-links", "exposure-bias", "exposure-mode", "exposure-time", "file-extension", "file-size", "flash-used", "focal-length", "folder-color-rgb", "full-file-extension", "head-revision-id", "height", "hidden", "icon-link", "id", "image", "image-media-metadata", "indexable-text", "is-authenticated-user", "iso-speed", "kind", "labels", "last-modifying-user", "last-modifying-user-name", "last-viewed-by-me-date", "latitude", "lens", "location", "longitude", "marked-viewed-by-me-date", "max-aperture-value", "md5-checksum", "metering-mode", "mime-type", "modified-by-me-date", "modified-date", "name", "open-with-links", "original-filename", "owned-by-me", "owner-names", "permission-id", "photo-link", "picture", "quota-bytes-used", "restricted", "role", "rotation", "self-link", "sensor", "shareable", "shared", "shared-with-me-date", "sharing-user", "spaces", "starred", "subject-distance", "text", "thumbnail", "thumbnail-link", "title", "trashed", "type", "url", "user-permission", "value", "version", "video-media-metadata", "viewed", "web-content-link", "web-view-link", "white-balance", "width", "with-link", "writers-can-share"]); err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); None } @@ -2369,8 +2437,7 @@ impl<'n, 'a> Engine<'n, 'a> { "version" => Some(("version", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "export-links" => Some(("exportLinks", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Map })), "shared" => Some(("shared", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), - "thumbnail.mime-type" => Some(("thumbnail.mimeType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), - "thumbnail.image" => Some(("thumbnail.image", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "full-file-extension" => Some(("fullFileExtension", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "open-with-links" => Some(("openWithLinks", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Map })), "image-media-metadata.exposure-bias" => Some(("imageMediaMetadata.exposureBias", JsonTypeInfo { jtype: JsonType::Float, ctype: ComplexType::Pod })), "image-media-metadata.exposure-time" => Some(("imageMediaMetadata.exposureTime", JsonTypeInfo { jtype: JsonType::Float, ctype: ComplexType::Pod })), @@ -2411,6 +2478,8 @@ impl<'n, 'a> Engine<'n, 'a> { "alternate-link" => Some(("alternateLink", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "title" => Some(("title", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "modified-by-me-date" => Some(("modifiedByMeDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "thumbnail.mime-type" => Some(("thumbnail.mimeType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "thumbnail.image" => Some(("thumbnail.image", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "download-url" => Some(("downloadUrl", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "user-permission.with-link" => Some(("userPermission.withLink", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), "user-permission.domain" => Some(("userPermission.domain", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), @@ -2434,7 +2503,7 @@ impl<'n, 'a> Engine<'n, 'a> { "self-link" => Some(("selfLink", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "modified-date" => Some(("modifiedDate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), _ => { - let suggestion = FieldCursor::did_you_mean(key, &vec!["additional-roles", "alternate-link", "altitude", "aperture", "app-data-contents", "auth-key", "camera-make", "camera-model", "can-comment", "color-space", "copyable", "created-date", "date", "default-open-with-link", "description", "display-name", "domain", "download-url", "duration-millis", "editable", "email-address", "embed-link", "etag", "explicitly-trashed", "export-links", "exposure-bias", "exposure-mode", "exposure-time", "file-extension", "file-size", "flash-used", "focal-length", "folder-color-rgb", "head-revision-id", "height", "hidden", "icon-link", "id", "image", "image-media-metadata", "indexable-text", "is-authenticated-user", "iso-speed", "kind", "labels", "last-modifying-user", "last-modifying-user-name", "last-viewed-by-me-date", "latitude", "lens", "location", "longitude", "marked-viewed-by-me-date", "max-aperture-value", "md5-checksum", "metering-mode", "mime-type", "modified-by-me-date", "modified-date", "name", "open-with-links", "original-filename", "owned-by-me", "owner-names", "permission-id", "photo-link", "picture", "quota-bytes-used", "restricted", "role", "rotation", "self-link", "sensor", "shareable", "shared", "shared-with-me-date", "sharing-user", "spaces", "starred", "subject-distance", "text", "thumbnail", "thumbnail-link", "title", "trashed", "type", "url", "user-permission", "value", "version", "video-media-metadata", "viewed", "web-content-link", "web-view-link", "white-balance", "width", "with-link", "writers-can-share"]); + let suggestion = FieldCursor::did_you_mean(key, &vec!["additional-roles", "alternate-link", "altitude", "aperture", "app-data-contents", "auth-key", "camera-make", "camera-model", "can-comment", "color-space", "copyable", "created-date", "date", "default-open-with-link", "description", "display-name", "domain", "download-url", "duration-millis", "editable", "email-address", "embed-link", "etag", "explicitly-trashed", "export-links", "exposure-bias", "exposure-mode", "exposure-time", "file-extension", "file-size", "flash-used", "focal-length", "folder-color-rgb", "full-file-extension", "head-revision-id", "height", "hidden", "icon-link", "id", "image", "image-media-metadata", "indexable-text", "is-authenticated-user", "iso-speed", "kind", "labels", "last-modifying-user", "last-modifying-user-name", "last-viewed-by-me-date", "latitude", "lens", "location", "longitude", "marked-viewed-by-me-date", "max-aperture-value", "md5-checksum", "metering-mode", "mime-type", "modified-by-me-date", "modified-date", "name", "open-with-links", "original-filename", "owned-by-me", "owner-names", "permission-id", "photo-link", "picture", "quota-bytes-used", "restricted", "role", "rotation", "self-link", "sensor", "shareable", "shared", "shared-with-me-date", "sharing-user", "spaces", "starred", "subject-distance", "text", "thumbnail", "thumbnail-link", "title", "trashed", "type", "url", "user-permission", "value", "version", "video-media-metadata", "viewed", "web-content-link", "web-view-link", "white-balance", "width", "with-link", "writers-can-share"]); err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); None } @@ -4880,6 +4949,9 @@ impl<'n, 'a> Engine<'n, 'a> { ("empty-trash", Some(opt)) => { call_result = self._files_empty_trash(opt, dry_run, &mut err); }, + ("generate-ids", Some(opt)) => { + call_result = self._files_generate_ids(opt, dry_run, &mut err); + }, ("get", Some(opt)) => { call_result = self._files_get(opt, dry_run, &mut err); }, @@ -5550,7 +5622,7 @@ fn main() { ]), ]), - ("files", "methods: 'copy', 'delete', 'empty-trash', 'get', 'insert', 'list', 'patch', 'touch', 'trash', 'untrash', 'update' and 'watch'", vec![ + ("files", "methods: 'copy', 'delete', 'empty-trash', 'generate-ids', 'get', 'insert', 'list', 'patch', 'touch', 'trash', 'untrash', 'update' and 'watch'", vec![ ("copy", Some(r##"Creates a copy of the specified file."##), "Details at http://byron.github.io/google-apis-rs/google_drive2_cli/files_copy", @@ -5605,6 +5677,22 @@ fn main() { Some(false), Some(true)), ]), + ("generate-ids", + Some(r##"Generates a set of file IDs which can be provided in insert requests."##), + "Details at http://byron.github.io/google-apis-rs/google_drive2_cli/files_generate-ids", + vec![ + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), ("get", Some(r##"Gets a file's metadata by ID."##), "Details at http://byron.github.io/google-apis-rs/google_drive2_cli/files_get", @@ -5722,7 +5810,7 @@ fn main() { Some(false)), ]), ("trash", - Some(r##"Moves a file to the trash."##), + Some(r##"Moves a file to the trash. The currently authenticated user must own the file."##), "Details at http://byron.github.io/google-apis-rs/google_drive2_cli/files_trash", vec![ (Some(r##"file-id"##), @@ -6056,7 +6144,7 @@ fn main() { Some(false)), ]), ("patch", - Some(r##"Updates a permission. This method supports patch semantics."##), + Some(r##"Updates a permission using patch semantics."##), "Details at http://byron.github.io/google-apis-rs/google_drive2_cli/permissions_patch", vec![ (Some(r##"file-id"##), @@ -6697,7 +6785,7 @@ fn main() { let mut app = App::new("drive2") .author("Sebastian Thiel ") - .version("0.3.2+20150709") + .version("0.3.2+20151008") .about("The API to interact with Drive.") .after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_drive2_cli") .arg(Arg::with_name("url") diff --git a/gen/drive2/Cargo.toml b/gen/drive2/Cargo.toml index 989f6a444d..303547ce10 100644 --- a/gen/drive2/Cargo.toml +++ b/gen/drive2/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-drive2" -version = "0.1.9+20150709" +version = "0.1.9+20151008" 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" diff --git a/gen/drive2/README.md b/gen/drive2/README.md index 33c75ada88..609138b89b 100644 --- a/gen/drive2/README.md +++ b/gen/drive2/README.md @@ -5,7 +5,7 @@ DO NOT EDIT ! --> The `google-drive2` library allows access to all features of the *Google drive* service. -This documentation was generated from *drive* crate version *0.1.9+20150709*, where *20150709* is the exact revision of the *drive:v2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +This documentation was generated from *drive* crate version *0.1.9+20151008*, where *20151008* is the exact revision of the *drive:v2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. Everything else about the *drive* *v2* API can be found at the [official documentation site](https://developers.google.com/drive/). @@ -26,7 +26,7 @@ Handle the following *Resources* with ease from the central [hub](http://byron.g * [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) + * [*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), [*generate ids*](http://byron.github.io/google-apis-rs/google_drive2/struct.FileGenerateIdCall.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) @@ -50,16 +50,16 @@ Upload supported by ... 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) +* [*get files*](http://byron.github.io/google-apis-rs/google_drive2/struct.FileGetCall.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) +* [*get files*](http://byron.github.io/google-apis-rs/google_drive2/struct.FileGetCall.html) @@ -93,6 +93,7 @@ Or specifically ... ```ignore let r = hub.files().watch(...).doit() let r = hub.files().empty_trash(...).doit() +let r = hub.files().generate_ids(...).doit() let r = hub.files().copy(...).doit() let r = hub.files().list(...).doit() let r = hub.files().delete(...).doit() diff --git a/gen/drive2/src/lib.rs b/gen/drive2/src/lib.rs index e29006e1bc..72a565fce3 100644 --- a/gen/drive2/src/lib.rs +++ b/gen/drive2/src/lib.rs @@ -2,7 +2,7 @@ // This file was generated automatically from 'src/mako/api/lib.rs.mako' // DO NOT EDIT ! -//! This documentation was generated from *drive* crate version *0.1.9+20150709*, where *20150709* is the exact revision of the *drive:v2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +//! This documentation was generated from *drive* crate version *0.1.9+20151008*, where *20151008* is the exact revision of the *drive:v2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. //! //! Everything else about the *drive* *v2* API can be found at the //! [official documentation site](https://developers.google.com/drive/). @@ -24,7 +24,7 @@ //! * [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) +//! * [*copy*](struct.FileCopyCall.html), [*delete*](struct.FileDeleteCall.html), [*empty trash*](struct.FileEmptyTrashCall.html), [*generate ids*](struct.FileGenerateIdCall.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) @@ -48,16 +48,16 @@ //! Download supported by ... //! //! * [*watch files*](struct.FileWatchCall.html) -//! * [*get files*](struct.FileGetCall.html) //! * [*get realtime*](struct.RealtimeGetCall.html) +//! * [*get files*](struct.FileGetCall.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) +//! * [*get files*](struct.FileGetCall.html) //! //! //! @@ -93,6 +93,7 @@ //! ```ignore //! let r = hub.files().watch(...).doit() //! let r = hub.files().empty_trash(...).doit() +//! let r = hub.files().generate_ids(...).doit() //! let r = hub.files().copy(...).doit() //! let r = hub.files().list(...).doit() //! let r = hub.files().delete(...).doit() @@ -156,18 +157,18 @@ //! // 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("aliquyam") -//! .timed_text_language("elitr") -//! .set_modified_date(true) -//! .remove_parents("et") -//! .pinned(false) -//! .ocr_language("sed") +//! .update_viewed_date(true) +//! .timed_text_track_name("Stet") +//! .timed_text_language("sed") +//! .set_modified_date(false) +//! .remove_parents("sanctus") +//! .pinned(true) +//! .ocr_language("Lorem") //! .ocr(false) //! .new_revision(true) -//! .modified_date_behavior("dolore") +//! .modified_date_behavior("eirmod") //! .convert(true) -//! .add_parents("consetetur") +//! .add_parents("gubergren") //! .doit(); //! //! match result { diff --git a/gen/drive2/src/lib.rs.in b/gen/drive2/src/lib.rs.in index 074f492185..d58be700cb 100644 --- a/gen/drive2/src/lib.rs.in +++ b/gen/drive2/src/lib.rs.in @@ -41,6 +41,9 @@ pub enum Scope { /// View your Google Drive apps AppReadonly, + /// View the photos, videos and albums in your Google Photos + PhotoReadonly, + /// View and manage metadata of files in your Google Drive Metadata, @@ -65,6 +68,7 @@ impl AsRef for Scope { match *self { Scope::Full => "https://www.googleapis.com/auth/drive", Scope::AppReadonly => "https://www.googleapis.com/auth/drive.apps.readonly", + Scope::PhotoReadonly => "https://www.googleapis.com/auth/drive.photos.readonly", Scope::Metadata => "https://www.googleapis.com/auth/drive.metadata", Scope::MetadataReadonly => "https://www.googleapis.com/auth/drive.metadata.readonly", Scope::File => "https://www.googleapis.com/auth/drive.file", @@ -397,10 +401,10 @@ pub struct About { #[serde(rename="exportFormats")] pub export_formats: Option>, /// The domain sharing policy for the current user. Possible values are: - /// - ALLOWED - /// - ALLOWED_WITH_WARNING - /// - INCOMING_ONLY - /// - DISALLOWED + /// - allowed + /// - allowedWithWarning + /// - incomingOnly + /// - disallowed #[serde(rename="domainSharingPolicy")] pub domain_sharing_policy: Option, /// A link back to this item. @@ -440,6 +444,7 @@ impl Part for FileThumbnail {} /// /// * [watch files](struct.FileWatchCall.html) (none) /// * [empty trash files](struct.FileEmptyTrashCall.html) (none) +/// * [generate ids files](struct.FileGenerateIdCall.html) (none) /// * [copy files](struct.FileCopyCall.html) (request|response) /// * [list files](struct.FileListCall.html) (none) /// * [delete files](struct.FileDeleteCall.html) (none) @@ -524,8 +529,9 @@ pub struct File { /// A link to the file's icon. #[serde(rename="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, + /// The full file extension; extracted from the title. May contain multiple concatenated extensions, such as "tar.gz". Removing an extension from the title does not clear this field; however, changing the extension on the title does update this field. This field is only populated for files with content stored in Drive; it is not populated for Google Docs or shortcut files. + #[serde(rename="fullFileExtension")] + pub full_file_extension: 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(rename="openWithLinks")] pub open_with_links: Option>, @@ -539,7 +545,7 @@ pub struct File { pub web_content_link: Option, /// Whether the file can be edited by the current user. pub editable: Option, - /// Time this file was explicitly marked viewed by the user (formatted RFC 3339 timestamp). + /// Deprecated. #[serde(rename="markedViewedByMeDate")] pub marked_viewed_by_me_date: Option, /// A link for embedding the file. @@ -548,7 +554,7 @@ pub struct File { /// Whether the current user can comment on the file. #[serde(rename="canComment")] pub can_comment: 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. + /// The final component of fullFileExtension with trailing text that does not appear to be part of the extension removed. This field is only populated for files with content stored in Drive; it is not populated for Google Docs or shortcut files. #[serde(rename="fileExtension")] pub file_extension: 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. @@ -559,7 +565,7 @@ pub struct File { 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. + /// An MD5 checksum for the content of this file. This field is only populated for files with content stored in Drive; it is not populated for Google Docs or shortcut files. #[serde(rename="md5Checksum")] pub md5_checksum: Option, /// The list of permissions for users with access to this file. @@ -577,29 +583,31 @@ pub struct File { /// 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(rename="modifiedByMeDate")] pub modified_by_me_date: Option, + /// Thumbnail for the file. Only accepted on upload and for files that are not already thumbnailed by Google. + pub thumbnail: Option, /// no description provided #[serde(rename="downloadUrl")] pub download_url: Option, /// The permissions for the authenticated user on this file. #[serde(rename="userPermission")] pub user_permission: Option, - /// The list of spaces which contain the file. Supported values are 'drive' and 'appDataFolder'. + /// The list of spaces which contain the file. Supported values are 'drive', 'appDataFolder' and 'photos'. pub spaces: Option>, /// Whether the file's sharing settings can be modified by the current user. pub shareable: 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. + /// 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 field is only populated for files with content stored in Drive; it is not populated for Google Docs or shortcut files. #[serde(rename="originalFilename")] pub original_filename: Option, /// The number of quota bytes used by this file. #[serde(rename="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. + /// The ID of the file's head revision. This field is only populated for files with content stored in Drive; it is not populated for Google Docs or shortcut files. #[serde(rename="headRevisionId")] pub head_revision_id: Option, /// A link back to this file. #[serde(rename="selfLink")] pub self_link: Option, - /// The size of the file in bytes. This is only populated for files with content stored in Drive. + /// The size of the file in bytes. This field is only populated for files with content stored in Drive; it is not populated for Google Docs or shortcut files. #[serde(rename="fileSize")] pub file_size: Option, } @@ -706,6 +714,31 @@ pub struct PermissionId { impl ResponseResult for PermissionId {} +/// 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, Serialize, Deserialize)] +pub struct PermissionList { + /// The actual list of permissions. + pub items: Option>, + /// This is always drive#permissionList. + pub kind: Option, + /// The ETag of the list. + pub etag: Option, + /// A link back to this list. + #[serde(rename="selfLink")] + pub self_link: Option, +} + +impl ResponseResult for PermissionList {} + + /// 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. @@ -831,7 +864,7 @@ impl Part for AboutMaxUploadSizes {} /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct FileLabels { - /// Whether viewers are prevented from downloading this file. + /// Whether viewers and commenters are prevented from downloading, printing, and copying this file. pub restricted: Option, /// Deprecated. pub hidden: Option, @@ -847,42 +880,26 @@ impl NestedType for FileLabels {} impl Part for FileLabels {} -/// A key-value pair attached to a file that is either public or private to an application. -/// The following limits apply to file properties: -/// - Maximum of 100 properties total per file -/// - Maximum of 30 private properties per app -/// - Maximum of 30 public properties -/// - Maximum of 124 bytes size limit on (key + value) string in UTF-8 encoding for a single property. +/// A list of generated IDs which can be provided in insert 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*). /// -/// * [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) +/// * [generate ids files](struct.FileGenerateIdCall.html) (response) /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] -pub struct Property { - /// The link back to this property. - #[serde(rename="selfLink")] - pub self_link: Option, - /// This is always drive#property. +pub struct GeneratedIds { + /// This is always drive#generatedIds 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, + /// The IDs generated for the requesting user in the specified space. + pub ids: Option>, + /// The type of file that can be created with these IDs. + pub space: Option, } -impl RequestValue for Property {} -impl ResponseResult for Property {} +impl ResponseResult for GeneratedIds {} /// An notification channel used to watch for resource changes. @@ -928,75 +945,32 @@ impl Resource for Channel {} impl ResponseResult for Channel {} -/// A revision of a file. +/// 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*). /// -/// * [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) +/// * [insert children](struct.ChildrenInsertCall.html) (request|response) +/// * [get children](struct.ChildrenGetCall.html) (response) /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] -pub struct Revision { - /// The MIME type of the revision. - #[serde(rename="mimeType")] - pub mime_type: Option, - /// A link to the published revision. - #[serde(rename="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(rename="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(rename="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(rename="fileSize")] - pub file_size: Option, - /// Name of the last user to modify this revision. - #[serde(rename="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(rename="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(rename="downloadUrl")] - pub download_url: Option, - /// This is always drive#revision. +pub struct ChildReference { + /// This is always drive#childReference. pub kind: Option, - /// The last user to modify this revision. - #[serde(rename="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(rename="originalFilename")] - pub original_filename: Option, - /// Links for exporting Google Docs to specific formats. - #[serde(rename="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. + /// A link to the child. + #[serde(rename="childLink")] + pub child_link: Option, + /// The ID of the child. + pub id: Option, + /// A link back to this reference. #[serde(rename="selfLink")] pub self_link: Option, - /// Last time this revision was modified (formatted RFC 3339 timestamp). - #[serde(rename="modifiedDate")] - pub modified_date: Option, } -impl RequestValue for Revision {} -impl Resource for Revision {} -impl ResponseResult for Revision {} +impl RequestValue for ChildReference {} +impl ResponseResult for ChildReference {} /// A JSON representation of a list of comments on a file in Google Drive. @@ -1053,29 +1027,42 @@ pub struct ParentList { impl ResponseResult for ParentList {} -/// A list of permissions associated with a file. +/// A key-value pair attached to a file that is either public or private to an application. +/// The following limits apply to file properties: +/// - Maximum of 100 properties total per file +/// - Maximum of 30 private properties per app +/// - Maximum of 30 public properties +/// - Maximum of 124 bytes size limit on (key + value) string in UTF-8 encoding for a single 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*). /// -/// * [list permissions](struct.PermissionListCall.html) (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 PermissionList { - /// The actual list of permissions. - pub items: Option>, - /// This is always drive#permissionList. - pub kind: Option, - /// The ETag of the list. - pub etag: Option, - /// A link back to this list. +pub struct Property { + /// The link back to this property. #[serde(rename="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 ResponseResult for PermissionList {} +impl RequestValue for Property {} +impl ResponseResult for Property {} /// The amount of storage quota used by different Google services. @@ -1563,32 +1550,75 @@ impl NestedType for CommentContext {} impl Part for CommentContext {} -/// A reference to a folder's child. +/// 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*). /// -/// * [insert children](struct.ChildrenInsertCall.html) (request|response) -/// * [get children](struct.ChildrenGetCall.html) (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 ChildReference { - /// This is always drive#childReference. - pub kind: Option, - /// A link to the child. - #[serde(rename="childLink")] - pub child_link: Option, - /// The ID of the child. +pub struct Revision { + /// The MIME type of the revision. + #[serde(rename="mimeType")] + pub mime_type: Option, + /// A link to the published revision. + #[serde(rename="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(rename="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(rename="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(rename="fileSize")] + pub file_size: Option, + /// Name of the last user to modify this revision. + #[serde(rename="lastModifyingUserName")] + pub last_modifying_user_name: Option, + /// The ID of the revision. pub id: Option, - /// A link back to this reference. + /// An MD5 checksum for the content of this revision. This will only be populated on files with content stored in Drive. + #[serde(rename="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(rename="downloadUrl")] + pub download_url: Option, + /// This is always drive#revision. + pub kind: Option, + /// The last user to modify this revision. + #[serde(rename="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(rename="originalFilename")] + pub original_filename: Option, + /// Links for exporting Google Docs to specific formats. + #[serde(rename="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(rename="selfLink")] pub self_link: Option, + /// Last time this revision was modified (formatted RFC 3339 timestamp). + #[serde(rename="modifiedDate")] + pub modified_date: Option, } -impl RequestValue for ChildReference {} -impl ResponseResult for ChildReference {} +impl RequestValue for Revision {} +impl Resource for Revision {} +impl ResponseResult for Revision {} /// Metadata about video media. This will only be present for video types. @@ -1690,7 +1720,7 @@ impl ResponseResult for Change {} /// ::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(...)` +/// // like `copy(...)`, `delete(...)`, `empty_trash(...)`, `generate_ids(...)`, `get(...)`, `insert(...)`, `list(...)`, `patch(...)`, `touch(...)`, `trash(...)`, `untrash(...)`, `update(...)` and `watch(...)` /// // to build up your call. /// let rb = hub.files(); /// # } @@ -1798,7 +1828,7 @@ impl<'a, C, A> FileMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Moves a file to the trash. + /// Moves a file to the trash. The currently authenticated user must own the file. /// /// # Arguments /// @@ -1835,6 +1865,7 @@ impl<'a, C, A> FileMethods<'a, C, A> { _q: Default::default(), _projection: Default::default(), _page_token: Default::default(), + _order_by: Default::default(), _max_results: Default::default(), _corpus: Default::default(), _delegate: Default::default(), @@ -1860,6 +1891,20 @@ impl<'a, C, A> FileMethods<'a, C, A> { } } + /// Create a builder to help you perform the following task: + /// + /// Generates a set of file IDs which can be provided in insert requests. + pub fn generate_ids(&self) -> FileGenerateIdCall<'a, C, A> { + FileGenerateIdCall { + hub: self.hub, + _space: 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 file metadata and/or content. @@ -2384,6 +2429,7 @@ impl<'a, C, A> ChildrenMethods<'a, C, A> { _folder_id: folder_id.to_string(), _q: Default::default(), _page_token: Default::default(), + _order_by: Default::default(), _max_results: Default::default(), _delegate: Default::default(), _scopes: Default::default(), @@ -2899,7 +2945,7 @@ impl<'a, C, A> PermissionMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Updates a permission. This method supports patch semantics. + /// Updates a permission using patch semantics. /// /// # Arguments /// @@ -3292,6 +3338,27 @@ impl<'a, C, A> RevisionMethods<'a, C, A> { } } + /// Create a builder to help you perform the following task: + /// + /// Updates a revision. This method supports patch semantics. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `fileId` - The ID for the file. + /// * `revisionId` - The ID for the revision. + pub fn patch(&self, request: Revision, file_id: &str, revision_id: &str) -> RevisionPatchCall<'a, C, A> { + RevisionPatchCall { + hub: self.hub, + _request: request, + _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. @@ -3348,27 +3415,6 @@ impl<'a, C, A> RevisionMethods<'a, C, A> { _additional_params: Default::default(), } } - - /// Create a builder to help you perform the following task: - /// - /// Updates a revision. This method supports patch semantics. - /// - /// # Arguments - /// - /// * `request` - No description provided. - /// * `fileId` - The ID for the file. - /// * `revisionId` - The ID for the revision. - pub fn patch(&self, request: Revision, file_id: &str, revision_id: &str) -> RevisionPatchCall<'a, C, A> { - RevisionPatchCall { - hub: self.hub, - _request: request, - _file_id: file_id.to_string(), - _revision_id: revision_id.to_string(), - _delegate: Default::default(), - _scopes: Default::default(), - _additional_params: Default::default(), - } - } } @@ -3635,7 +3681,7 @@ impl<'a, C, A> FileWatchCall<'a, C, A> where C: BorrowMut, A: oau self._file_id = new_value.to_string(); self } - /// Whether to update the view date after successfully retrieving the file. + /// Deprecated: Use files.update with modifiedDateBehavior=noChange, updateViewedDate=true and an empty request body. /// /// Sets the *update viewed date* query property to the given value. pub fn update_viewed_date(mut self, new_value: bool) -> FileWatchCall<'a, C, A> { @@ -4026,10 +4072,10 @@ impl<'a, C, A> FileInsertCall<'a, C, A> where C: BorrowMut, A: oa self.doit(stream, mime_type, "simple") } /// Upload media in a resumable fashion. - /// Even if the upload fails or is interrupted, it can be resumed for a + /// Even if the upload fails or is interrupted, it can be resumed for a /// certain amount of time as the server maintains state temporarily. /// - /// The delegate will be asked for an `upload_url()`, and if not provided, will be asked to store an upload URL + /// The delegate will be asked for an `upload_url()`, and if not provided, will be asked to store an upload URL /// that was provided by the server, using `store_upload_url(...)`. The upload will be done in chunks, the delegate /// may specify the `chunk_size()` and may cancel the operation before each chunk is uploaded, using /// `cancel_chunk_upload(...)`. @@ -4746,7 +4792,7 @@ impl<'a, C, A> FileCopyCall<'a, C, A> where C: BorrowMut, A: oaut } -/// Moves a file to the trash. +/// Moves a file to the trash. The currently authenticated user must own the file. /// /// A builder for the *trash* method supported by a *file* resource. /// It is not used directly, but through a `FileMethods` instance. @@ -5205,8 +5251,9 @@ impl<'a, C, A> FileEmptyTrashCall<'a, C, A> where C: BorrowMut, A /// .q("eirmod") /// .projection("sanctus") /// .page_token("et") -/// .max_results(-46) -/// .corpus("et") +/// .order_by("amet") +/// .max_results(-23) +/// .corpus("consetetur") /// .doit(); /// # } /// ``` @@ -5218,6 +5265,7 @@ pub struct FileListCall<'a, C, A> _q: Option, _projection: Option, _page_token: Option, + _order_by: Option, _max_results: Option, _corpus: Option, _delegate: Option<&'a mut Delegate>, @@ -5241,7 +5289,7 @@ impl<'a, C, A> FileListCall<'a, C, A> where C: BorrowMut, A: oaut }; dlg.begin(MethodInfo { id: "drive.files.list", http_method: hyper::method::Method::Get }); - let mut params: Vec<(&str, String)> = Vec::with_capacity((8 + self._additional_params.len())); + let mut params: Vec<(&str, String)> = Vec::with_capacity((9 + self._additional_params.len())); if let Some(value) = self._spaces { params.push(("spaces", value.to_string())); } @@ -5254,13 +5302,16 @@ impl<'a, C, A> FileListCall<'a, C, A> where C: BorrowMut, A: oaut 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._corpus { params.push(("corpus", value.to_string())); } - for &field in ["alt", "spaces", "q", "projection", "pageToken", "maxResults", "corpus"].iter() { + for &field in ["alt", "spaces", "q", "projection", "pageToken", "orderBy", "maxResults", "corpus"].iter() { if self._additional_params.contains_key(field) { dlg.finished(false); return Err(Error::FieldClash(field)); @@ -5355,7 +5406,7 @@ impl<'a, C, A> FileListCall<'a, C, A> where C: BorrowMut, A: oaut } - /// A comma-separated list of spaces to query. Supported values are 'drive' and 'appDataFolder'. + /// A comma-separated list of spaces to query. Supported values are 'drive', 'appDataFolder' and 'photos'. /// /// Sets the *spaces* query property to the given value. pub fn spaces(mut self, new_value: &str) -> FileListCall<'a, C, A> { @@ -5383,6 +5434,13 @@ impl<'a, C, A> FileListCall<'a, C, A> where C: BorrowMut, A: oaut self._page_token = Some(new_value.to_string()); self } + /// A comma-separated list of sort keys. Valid keys are 'createdDate', 'folder', 'lastViewedByMeDate', 'modifiedByMeDate', 'modifiedDate', 'quotaBytesUsed', 'recency', 'sharedWithMeDate', 'starred', and 'title'. Each key sorts ascending by default, but may be reversed with the 'desc' modifier. Example usage: ?orderBy=folder,modifiedDate desc,title. Please note that there is a current limitation for users with approximately one million files in which the requested sort order is ignored. + /// + /// Sets the *order by* query property to the given value. + pub fn order_by(mut self, new_value: &str) -> FileListCall<'a, C, A> { + self._order_by = Some(new_value.to_string()); + self + } /// Maximum number of files to return. /// /// Sets the *max results* query property to the given value. @@ -5685,6 +5743,233 @@ impl<'a, C, A> FileTouchCall<'a, C, A> where C: BorrowMut, A: oau } +/// Generates a set of file IDs which can be provided in insert requests. +/// +/// A builder for the *generateIds* method supported by a *file* resource. +/// It is not used directly, but through a `FileMethods` instance. +/// +/// # 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().generate_ids() +/// .space("ea") +/// .max_results(-80) +/// .doit(); +/// # } +/// ``` +pub struct FileGenerateIdCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Drive, + _space: Option, + _max_results: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for FileGenerateIdCall<'a, C, A> {} + +impl<'a, C, A> FileGenerateIdCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, GeneratedIds)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, 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.generateIds", + 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._space { + params.push(("space", value.to_string())); + } + if let Some(value) = self._max_results { + params.push(("maxResults", value.to_string())); + } + for &field in ["alt", "space", "maxResults"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, 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/generateIds".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Full.as_ref().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The space in which the IDs can be used to create new files. Supported values are 'drive' and 'appDataFolder'. + /// + /// Sets the *space* query property to the given value. + pub fn space(mut self, new_value: &str) -> FileGenerateIdCall<'a, C, A> { + self._space = Some(new_value.to_string()); + self + } + /// Maximum number of IDs to return. + /// + /// Sets the *max results* query property to the given value. + pub fn max_results(mut self, new_value: i32) -> FileGenerateIdCall<'a, C, A> { + self._max_results = Some(new_value); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> FileGenerateIdCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> FileGenerateIdCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Full`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> FileGenerateIdCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + /// Updates file metadata and/or content. /// /// A builder for the *update* method supported by a *file* resource. @@ -5720,18 +6005,18 @@ impl<'a, C, A> FileTouchCall<'a, C, A> where C: BorrowMut, A: oau /// // Values shown here are possibly random and not representative ! /// let result = hub.files().update(req, "fileId") /// .use_content_as_indexable_text(true) -/// .update_viewed_date(false) -/// .timed_text_track_name("dolor") -/// .timed_text_language("dolor") -/// .set_modified_date(true) -/// .remove_parents("et") +/// .update_viewed_date(true) +/// .timed_text_track_name("et") +/// .timed_text_language("consetetur") +/// .set_modified_date(false) +/// .remove_parents("voluptua.") /// .pinned(false) -/// .ocr_language("amet.") +/// .ocr_language("gubergren") /// .ocr(true) /// .new_revision(false) -/// .modified_date_behavior("gubergren") +/// .modified_date_behavior("vero") /// .convert(true) -/// .add_parents("sit") +/// .add_parents("rebum.") /// .upload_resumable(fs::File::open("file.ext").unwrap(), "application/octet-stream".parse().unwrap()); /// # } /// ``` @@ -6044,10 +6329,10 @@ impl<'a, C, A> FileUpdateCall<'a, C, A> where C: BorrowMut, A: oa self.doit(stream, mime_type, "simple") } /// Upload media in a resumable fashion. - /// Even if the upload fails or is interrupted, it can be resumed for a + /// Even if the upload fails or is interrupted, it can be resumed for a /// certain amount of time as the server maintains state temporarily. /// - /// The delegate will be asked for an `upload_url()`, and if not provided, will be asked to store an upload URL + /// The delegate will be asked for an `upload_url()`, and if not provided, will be asked to store an upload URL /// that was provided by the server, using `store_upload_url(...)`. The upload will be done in chunks, the delegate /// may specify the `chunk_size()` and may cancel the operation before each chunk is uploaded, using /// `cancel_chunk_upload(...)`. @@ -6142,21 +6427,21 @@ impl<'a, C, A> FileUpdateCall<'a, C, A> where C: BorrowMut, A: oa self._ocr = Some(new_value); self } - /// 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 unpinned revisions are preserved for a short period of time. Pinned revisions are stored indefinitely, using additional storage quota, up to a maximum of 200 revisions. + /// 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 unpinned revisions are preserved for a short period of time. Pinned revisions are stored indefinitely, using additional storage quota, up to a maximum of 200 revisions. For details on how revisions are retained, see the Drive Help Center. /// /// Sets the *new revision* query property to the given value. pub fn new_revision(mut self, new_value: bool) -> FileUpdateCall<'a, C, A> { self._new_revision = Some(new_value); self } - /// How the modifiedDate field should be updated. This overrides setModifiedDate. + /// Determines the behavior in which modifiedDate is updated. This overrides setModifiedDate. /// /// Sets the *modified date behavior* query property to the given value. pub fn modified_date_behavior(mut self, new_value: &str) -> FileUpdateCall<'a, C, A> { self._modified_date_behavior = Some(new_value.to_string()); self } - /// Whether to convert this file to the corresponding Google Docs format. + /// This parameter is deprecated and has no function. /// /// Sets the *convert* query property to the given value. pub fn convert(mut self, new_value: bool) -> FileUpdateCall<'a, C, A> { @@ -6481,18 +6766,18 @@ impl<'a, C, A> FileDeleteCall<'a, C, A> where C: BorrowMut, A: oa /// // 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("sadipscing") -/// .timed_text_language("vero") +/// .update_viewed_date(false) +/// .timed_text_track_name("invidunt") +/// .timed_text_language("consetetur") /// .set_modified_date(false) -/// .remove_parents("invidunt") +/// .remove_parents("duo") /// .pinned(false) -/// .ocr_language("dolore") +/// .ocr_language("Lorem") /// .ocr(true) -/// .new_revision(false) -/// .modified_date_behavior("Lorem") -/// .convert(true) -/// .add_parents("clita") +/// .new_revision(true) +/// .modified_date_behavior("consetetur") +/// .convert(false) +/// .add_parents("nonumy") /// .doit(); /// # } /// ``` @@ -6790,21 +7075,21 @@ impl<'a, C, A> FilePatchCall<'a, C, A> where C: BorrowMut, A: oau self._ocr = Some(new_value); self } - /// 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 unpinned revisions are preserved for a short period of time. Pinned revisions are stored indefinitely, using additional storage quota, up to a maximum of 200 revisions. + /// 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 unpinned revisions are preserved for a short period of time. Pinned revisions are stored indefinitely, using additional storage quota, up to a maximum of 200 revisions. For details on how revisions are retained, see the Drive Help Center. /// /// Sets the *new revision* query property to the given value. pub fn new_revision(mut self, new_value: bool) -> FilePatchCall<'a, C, A> { self._new_revision = Some(new_value); self } - /// How the modifiedDate field should be updated. This overrides setModifiedDate. + /// Determines the behavior in which modifiedDate is updated. This overrides setModifiedDate. /// /// Sets the *modified date behavior* query property to the given value. pub fn modified_date_behavior(mut self, new_value: &str) -> FilePatchCall<'a, C, A> { self._modified_date_behavior = Some(new_value.to_string()); self } - /// Whether to convert this file to the corresponding Google Docs format. + /// This parameter is deprecated and has no function. /// /// Sets the *convert* query property to the given value. pub fn convert(mut self, new_value: bool) -> FilePatchCall<'a, C, A> { @@ -6902,10 +7187,10 @@ impl<'a, C, A> FilePatchCall<'a, C, A> where C: BorrowMut, A: oau /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.files().get("fileId") -/// .update_viewed_date(false) -/// .revision_id("nonumy") -/// .projection("kasd") -/// .acknowledge_abuse(true) +/// .update_viewed_date(true) +/// .revision_id("takimata") +/// .projection("At") +/// .acknowledge_abuse(false) /// .doit(); /// # } /// ``` @@ -7095,7 +7380,7 @@ impl<'a, C, A> FileGetCall<'a, C, A> where C: BorrowMut, A: oauth self._file_id = new_value.to_string(); self } - /// Whether to update the view date after successfully retrieving the file. + /// Deprecated: Use files.update with modifiedDateBehavior=noChange, updateViewedDate=true and an empty request body. /// /// Sets the *update viewed date* query property to the given value. pub fn update_viewed_date(mut self, new_value: bool) -> FileGetCall<'a, C, A> { @@ -7202,8 +7487,8 @@ impl<'a, C, A> FileGetCall<'a, C, A> where C: BorrowMut, A: oauth /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.about().get() -/// .start_change_id("takimata") -/// .max_change_id_count(-27) +/// .start_change_id("invidunt") +/// .max_change_id_count(-66) /// .include_subscribed(false) /// .doit(); /// # } @@ -7442,7 +7727,7 @@ impl<'a, C, A> AboutGetCall<'a, C, A> where C: BorrowMut, A: oaut /// // execute the final call using `upload(...)`. /// // Values shown here are possibly random and not representative ! /// let result = hub.realtime().update("fileId") -/// .base_revision("ea") +/// .base_revision("dolore") /// .upload(fs::File::open("file.ext").unwrap(), "application/octet-stream".parse().unwrap()); /// # } /// ``` @@ -7675,10 +7960,10 @@ impl<'a, C, A> RealtimeUpdateCall<'a, C, A> where C: BorrowMut, A self.doit(stream, mime_type, "simple") } /// Upload media in a resumable fashion. - /// Even if the upload fails or is interrupted, it can be resumed for a + /// Even if the upload fails or is interrupted, it can be resumed for a /// certain amount of time as the server maintains state temporarily. /// - /// The delegate will be asked for an `upload_url()`, and if not provided, will be asked to store an upload URL + /// The delegate will be asked for an `upload_url()`, and if not provided, will be asked to store an upload URL /// that was provided by the server, using `store_upload_url(...)`. The upload will be done in chunks, the delegate /// may specify the `chunk_size()` and may cancel the operation before each chunk is uploaded, using /// `cancel_chunk_upload(...)`. @@ -7790,7 +8075,7 @@ impl<'a, C, A> RealtimeUpdateCall<'a, C, A> where C: BorrowMut, A /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.realtime().get("fileId") -/// .revision(-66) +/// .revision(-29) /// .doit(); /// # } /// ``` @@ -8263,9 +8548,9 @@ impl<'a, C, A> AppGetCall<'a, C, A> where C: BorrowMut, A: oauth2 /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.apps().list() -/// .language_code("nonumy") -/// .app_filter_mime_types("sed") -/// .app_filter_extensions("aliquyam") +/// .language_code("sit") +/// .app_filter_mime_types("eirmod") +/// .app_filter_extensions("consetetur") /// .doit(); /// # } /// ``` @@ -8739,7 +9024,7 @@ impl<'a, C, A> CommentDeleteCall<'a, C, A> where C: BorrowMut, A: /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.comments().get("fileId", "commentId") -/// .include_deleted(true) +/// .include_deleted(false) /// .doit(); /// # } /// ``` @@ -9824,10 +10109,10 @@ impl<'a, C, A> CommentUpdateCall<'a, C, A> where C: BorrowMut, A: /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.comments().list("fileId") -/// .updated_min("labore") -/// .page_token("ipsum") -/// .max_results(-31) -/// .include_deleted(false) +/// .updated_min("dolores") +/// .page_token("sit") +/// .max_results(-41) +/// .include_deleted(true) /// .doit(); /// # } /// ``` @@ -10108,9 +10393,10 @@ impl<'a, C, A> CommentListCall<'a, C, A> where C: BorrowMut, A: o /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.children().list("folderId") -/// .q("diam") -/// .page_token("ut") -/// .max_results(-70) +/// .q("est") +/// .page_token("amet") +/// .order_by("accusam") +/// .max_results(-13) /// .doit(); /// # } /// ``` @@ -10121,6 +10407,7 @@ pub struct ChildrenListCall<'a, C, A> _folder_id: String, _q: Option, _page_token: Option, + _order_by: Option, _max_results: Option, _delegate: Option<&'a mut Delegate>, _additional_params: HashMap, @@ -10143,7 +10430,7 @@ impl<'a, C, A> ChildrenListCall<'a, C, A> where C: BorrowMut, A: }; 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())); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); params.push(("folderId", self._folder_id.to_string())); if let Some(value) = self._q { params.push(("q", value.to_string())); @@ -10151,10 +10438,13 @@ impl<'a, C, A> ChildrenListCall<'a, C, A> where C: BorrowMut, A: 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", "folderId", "q", "pageToken", "maxResults"].iter() { + for &field in ["alt", "folderId", "q", "pageToken", "orderBy", "maxResults"].iter() { if self._additional_params.contains_key(field) { dlg.finished(false); return Err(Error::FieldClash(field)); @@ -10294,6 +10584,13 @@ impl<'a, C, A> ChildrenListCall<'a, C, A> where C: BorrowMut, A: self._page_token = Some(new_value.to_string()); self } + /// A comma-separated list of sort keys. Valid keys are 'createdDate', 'folder', 'lastViewedByMeDate', 'modifiedByMeDate', 'modifiedDate', 'quotaBytesUsed', 'recency', 'sharedWithMeDate', 'starred', and 'title'. Each key sorts ascending by default, but may be reversed with the 'desc' modifier. Example usage: ?orderBy=folder,modifiedDate desc,title. Please note that there is a current limitation for users with approximately one million files in which the requested sort order is ignored. + /// + /// Sets the *order by* query property to the given value. + pub fn order_by(mut self, new_value: &str) -> ChildrenListCall<'a, C, A> { + self._order_by = Some(new_value.to_string()); + self + } /// Maximum number of children to return. /// /// Sets the *max results* query property to the given value. @@ -12634,8 +12931,8 @@ impl<'a, C, A> ReplyPatchCall<'a, C, A> where C: BorrowMut, A: oa /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.replies().list("fileId", "commentId") -/// .page_token("ea") -/// .max_results(-17) +/// .page_token("diam") +/// .max_results(-62) /// .include_deleted(false) /// .doit(); /// # } @@ -12918,7 +13215,7 @@ impl<'a, C, A> ReplyListCall<'a, C, A> where C: BorrowMut, A: oau /// // 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) +/// .include_deleted(true) /// .doit(); /// # } /// ``` @@ -14253,7 +14550,7 @@ impl<'a, C, A> PermissionDeleteCall<'a, C, A> where C: BorrowMut, /// // Values shown here are possibly random and not representative ! /// let result = hub.permissions().insert(req, "fileId") /// .send_notification_emails(true) -/// .email_message("nonumy") +/// .email_message("diam") /// .doit(); /// # } /// ``` @@ -14543,7 +14840,7 @@ impl<'a, C, A> PermissionInsertCall<'a, C, A> where C: BorrowMut, /// // 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(true) +/// .transfer_ownership(false) /// .doit(); /// # } /// ``` @@ -14801,7 +15098,7 @@ impl<'a, C, A> PermissionUpdateCall<'a, C, A> where C: BorrowMut, } -/// Updates a permission. This method supports patch semantics. +/// Updates a permission using patch semantics. /// /// A builder for the *patch* method supported by a *permission* resource. /// It is not used directly, but through a `PermissionMethods` instance. @@ -15845,12 +16142,12 @@ impl<'a, C, A> PermissionGetIdForEmailCall<'a, C, A> where C: BorrowMut ChangeWatchCall<'a, C, A> where C: BorrowMut, A: o self._start_change_id = Some(new_value.to_string()); self } - /// A comma-separated list of spaces to query. Supported values are 'drive' and 'appDataFolder'. + /// A comma-separated list of spaces to query. Supported values are 'drive', 'appDataFolder' and 'photos'. /// /// Sets the *spaces* query property to the given value. pub fn spaces(mut self, new_value: &str) -> ChangeWatchCall<'a, C, A> { @@ -16145,10 +16442,10 @@ impl<'a, C, A> ChangeWatchCall<'a, C, A> where C: BorrowMut, A: o /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.changes().list() -/// .start_change_id("et") +/// .start_change_id("sed") /// .spaces("et") -/// .page_token("vero") -/// .max_results(-36) +/// .page_token("ipsum") +/// .max_results(-20) /// .include_subscribed(true) /// .include_deleted(true) /// .doit(); @@ -16306,7 +16603,7 @@ impl<'a, C, A> ChangeListCall<'a, C, A> where C: BorrowMut, A: oa self._start_change_id = Some(new_value.to_string()); self } - /// A comma-separated list of spaces to query. Supported values are 'drive' and 'appDataFolder'. + /// A comma-separated list of spaces to query. Supported values are 'drive', 'appDataFolder' and 'photos'. /// /// Sets the *spaces* query property to the given value. pub fn spaces(mut self, new_value: &str) -> ChangeListCall<'a, C, A> { @@ -16662,7 +16959,7 @@ impl<'a, C, A> ChangeGetCall<'a, C, A> where C: BorrowMut, A: oau /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.properties().patch(req, "fileId", "propertyKey") -/// .visibility("vero") +/// .visibility("nonumy") /// .doit(); /// # } /// ``` @@ -16947,7 +17244,7 @@ impl<'a, C, A> PropertyPatchCall<'a, C, A> where C: BorrowMut, A: /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.properties().delete("fileId", "propertyKey") -/// .visibility("et") +/// .visibility("no") /// .doit(); /// # } /// ``` @@ -17705,7 +18002,7 @@ impl<'a, C, A> PropertyListCall<'a, C, A> where C: BorrowMut, A: /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.properties().update(req, "fileId", "propertyKey") -/// .visibility("invidunt") +/// .visibility("elitr") /// .doit(); /// # } /// ``` @@ -17990,7 +18287,7 @@ impl<'a, C, A> PropertyUpdateCall<'a, C, A> where C: BorrowMut, A /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.properties().get("fileId", "propertyKey") -/// .visibility("aliquyam") +/// .visibility("elitr") /// .doit(); /// # } /// ``` @@ -18471,6 +18768,285 @@ impl<'a, C, A> RevisionGetCall<'a, C, A> where C: BorrowMut, A: o } +/// 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` instance. +/// +/// # 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(); +/// +/// // You can configure optional parameters by calling 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, A> + where C: '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, A> CallBuilder for RevisionPatchCall<'a, C, A> {} + +impl<'a, C, A> RevisionPatchCall<'a, C, A> where 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 Err(Error::FieldClash(field)); + } + } + for (name, 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_ref().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 ["revisionId", "fileId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// The ID for the file. + /// + /// 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. + pub fn file_id(mut self, new_value: &str) -> RevisionPatchCall<'a, C, A> { + self._file_id = new_value.to_string(); + self + } + /// The ID for the revision. + /// + /// 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. + pub fn revision_id(mut self, new_value: &str) -> RevisionPatchCall<'a, C, A> { + self._revision_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> RevisionPatchCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Full`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + /// Removes a revision. /// /// A builder for the *delete* method supported by a *revision* resource. @@ -19223,282 +19799,3 @@ impl<'a, C, A> RevisionListCall<'a, C, A> where C: BorrowMut, A: } -/// 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` instance. -/// -/// # 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(); -/// -/// // You can configure optional parameters by calling 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, A> - where C: '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, A> CallBuilder for RevisionPatchCall<'a, C, A> {} - -impl<'a, C, A> RevisionPatchCall<'a, C, A> where 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 Err(Error::FieldClash(field)); - } - } - for (name, 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_ref().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 ["revisionId", "fileId"].iter() { - if let Some(index) = params.iter().position(|t| &t.0 == param_name) { - indices_for_removal.push(index); - } - } - for &index in indices_for_removal.iter() { - params.remove(index); - } - } - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); - let mut request_value_reader = - { - let mut value = json::value::to_value(&self._request); - remove_json_null_values(&mut value); - let mut dst = io::Cursor::new(Vec::with_capacity(128)); - json::to_writer(&mut dst, &value).unwrap(); - dst - }; - let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); - request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_token }); - request_value_reader.seek(io::SeekFrom::Start(0)).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) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()) - .header(ContentType(json_mime_type.clone())) - .header(ContentLength(request_size as u64)) - .body(&mut request_value_reader); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = { - let mut json_response = String::new(); - res.read_to_string(&mut json_response).unwrap(); - match json::from_str(&json_response) { - Ok(decoded) => (res, decoded), - Err(err) => { - dlg.response_json_decode_error(&json_response, &err); - return Err(Error::JsonDecodeError(json_response, err)); - } - } - }; - - dlg.finished(true); - return Ok(result_value) - } - } - } - } - - - /// - /// Sets the *request* property to the given value. - /// - /// Even though 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, A> { - self._request = new_value; - self - } - /// The ID for the file. - /// - /// 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. - pub fn file_id(mut self, new_value: &str) -> RevisionPatchCall<'a, C, A> { - self._file_id = new_value.to_string(); - self - } - /// The ID for the revision. - /// - /// 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. - pub fn revision_id(mut self, new_value: &str) -> RevisionPatchCall<'a, C, A> { - self._revision_id = new_value.to_string(); - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> RevisionPatchCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. - /// * *fields* (query-string) - Selector specifying which 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, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::Full`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing 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, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().to_string(), ()); - self - } -} - - diff --git a/gen/freebase1-cli/Cargo.toml b/gen/freebase1-cli/Cargo.toml index 6c75cd4f0d..48fef02672 100644 --- a/gen/freebase1-cli/Cargo.toml +++ b/gen/freebase1-cli/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-freebase1-cli" -version = "0.3.2+20150715" +version = "0.3.2+20150728" 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-cli" diff --git a/gen/freebase1-cli/README.md b/gen/freebase1-cli/README.md index 81cb7dcf52..4bf6278dba 100644 --- a/gen/freebase1-cli/README.md +++ b/gen/freebase1-cli/README.md @@ -24,7 +24,7 @@ Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/ma # Usage -This documentation was generated from the *freebase* API at revision *20150715*. The CLI is at version *0.3.2*. +This documentation was generated from the *freebase* API at revision *20150728*. The CLI is at version *0.3.2*. ```bash freebase1 [options] diff --git a/gen/freebase1-cli/mkdocs.yml b/gen/freebase1-cli/mkdocs.yml index e605e20f82..5ae85b022e 100644 --- a/gen/freebase1-cli/mkdocs.yml +++ b/gen/freebase1-cli/mkdocs.yml @@ -1,4 +1,4 @@ -site_name: freebase v0.3.2+20150715 +site_name: freebase v0.3.2+20150728 site_url: http://byron.github.io/google-apis-rs/google-freebase1-cli site_description: Write integrating applications with bcore diff --git a/gen/freebase1-cli/src/main.rs b/gen/freebase1-cli/src/main.rs index 480a5ffeff..39d938dbb6 100644 --- a/gen/freebase1-cli/src/main.rs +++ b/gen/freebase1-cli/src/main.rs @@ -377,7 +377,7 @@ fn main() { let mut app = App::new("freebase1") .author("Sebastian Thiel ") - .version("0.3.2+20150715") + .version("0.3.2+20150728") .about("Find Freebase entities using textual queries and other constraints.") .after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_freebase1_cli") .arg(Arg::with_name("folder") diff --git a/gen/freebase1/Cargo.toml b/gen/freebase1/Cargo.toml index 3e9bb02909..e366584378 100644 --- a/gen/freebase1/Cargo.toml +++ b/gen/freebase1/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-freebase1" -version = "0.1.9+20150715" +version = "0.1.9+20150728" 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" diff --git a/gen/freebase1/README.md b/gen/freebase1/README.md index 9b10fb01fd..235a78a25e 100644 --- a/gen/freebase1/README.md +++ b/gen/freebase1/README.md @@ -5,7 +5,7 @@ DO NOT EDIT ! --> The `google-freebase1` library allows access to all features of the *Google freebase* service. -This documentation was generated from *freebase* crate version *0.1.9+20150715*, where *20150715* is the exact revision of the *freebase:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +This documentation was generated from *freebase* crate version *0.1.9+20150728*, where *20150728* is the exact revision of the *freebase:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. Everything else about the *freebase* *v1* API can be found at the [official documentation site](https://developers.google.com/freebase/). diff --git a/gen/freebase1/src/lib.rs b/gen/freebase1/src/lib.rs index 06c23be498..9329c8e2e9 100644 --- a/gen/freebase1/src/lib.rs +++ b/gen/freebase1/src/lib.rs @@ -2,7 +2,7 @@ // This file was generated automatically from 'src/mako/api/lib.rs.mako' // DO NOT EDIT ! -//! This documentation was generated from *freebase* crate version *0.1.9+20150715*, where *20150715* is the exact revision of the *freebase:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +//! This documentation was generated from *freebase* crate version *0.1.9+20150728*, where *20150728* is the exact revision of the *freebase:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. //! //! Everything else about the *freebase* *v1* API can be found at the //! [official documentation site](https://developers.google.com/freebase/). diff --git a/gen/fusiontables2/src/lib.rs.in b/gen/fusiontables2/src/lib.rs.in index 32da8acde4..cf2702fe4b 100644 --- a/gen/fusiontables2/src/lib.rs.in +++ b/gen/fusiontables2/src/lib.rs.in @@ -8220,10 +8220,10 @@ impl<'a, C, A> TableReplaceRowCall<'a, C, A> where C: BorrowMut, self.doit(stream, mime_type, "simple") } /// Upload media in a resumable fashion. - /// Even if the upload fails or is interrupted, it can be resumed for a + /// Even if the upload fails or is interrupted, it can be resumed for a /// certain amount of time as the server maintains state temporarily. /// - /// The delegate will be asked for an `upload_url()`, and if not provided, will be asked to store an upload URL + /// The delegate will be asked for an `upload_url()`, and if not provided, will be asked to store an upload URL /// that was provided by the server, using `store_upload_url(...)`. The upload will be done in chunks, the delegate /// may specify the `chunk_size()` and may cancel the operation before each chunk is uploaded, using /// `cancel_chunk_upload(...)`. @@ -9826,10 +9826,10 @@ impl<'a, C, A> TableImportRowCall<'a, C, A> where C: BorrowMut, A self.doit(stream, mime_type, "simple") } /// Upload media in a resumable fashion. - /// Even if the upload fails or is interrupted, it can be resumed for a + /// Even if the upload fails or is interrupted, it can be resumed for a /// certain amount of time as the server maintains state temporarily. /// - /// The delegate will be asked for an `upload_url()`, and if not provided, will be asked to store an upload URL + /// The delegate will be asked for an `upload_url()`, and if not provided, will be asked to store an upload URL /// that was provided by the server, using `store_upload_url(...)`. The upload will be done in chunks, the delegate /// may specify the `chunk_size()` and may cancel the operation before each chunk is uploaded, using /// `cancel_chunk_upload(...)`. @@ -10195,10 +10195,10 @@ impl<'a, C, A> TableImportTableCall<'a, C, A> where C: BorrowMut, self.doit(stream, mime_type, "simple") } /// Upload media in a resumable fashion. - /// Even if the upload fails or is interrupted, it can be resumed for a + /// Even if the upload fails or is interrupted, it can be resumed for a /// certain amount of time as the server maintains state temporarily. /// - /// The delegate will be asked for an `upload_url()`, and if not provided, will be asked to store an upload URL + /// The delegate will be asked for an `upload_url()`, and if not provided, will be asked to store an upload URL /// that was provided by the server, using `store_upload_url(...)`. The upload will be done in chunks, the delegate /// may specify the `chunk_size()` and may cancel the operation before each chunk is uploaded, using /// `cancel_chunk_upload(...)`. diff --git a/gen/games1-cli/Cargo.toml b/gen/games1-cli/Cargo.toml index 688cb5bf38..1d912dbad7 100644 --- a/gen/games1-cli/Cargo.toml +++ b/gen/games1-cli/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-games1-cli" -version = "0.3.2+20150717" +version = "0.3.2+20151012" authors = ["Sebastian Thiel "] description = "A complete library to interact with Games (protocol v1)" repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/games1-cli" diff --git a/gen/games1-cli/README.md b/gen/games1-cli/README.md index 1127201c4e..d777401b75 100644 --- a/gen/games1-cli/README.md +++ b/gen/games1-cli/README.md @@ -24,7 +24,7 @@ Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/ma # Usage -This documentation was generated from the *Games* API at revision *20150717*. The CLI is at version *0.3.2*. +This documentation was generated from the *Games* API at revision *20151012*. The CLI is at version *0.3.2*. ```bash games1 [options] diff --git a/gen/games1-cli/mkdocs.yml b/gen/games1-cli/mkdocs.yml index cd5fe0f0b4..d6f2d1e138 100644 --- a/gen/games1-cli/mkdocs.yml +++ b/gen/games1-cli/mkdocs.yml @@ -1,4 +1,4 @@ -site_name: Games v0.3.2+20150717 +site_name: Games v0.3.2+20151012 site_url: http://byron.github.io/google-apis-rs/google-games1-cli site_description: Write integrating applications with bcore diff --git a/gen/games1-cli/src/main.rs b/gen/games1-cli/src/main.rs index a5d49f1e53..dff3e718ec 100644 --- a/gen/games1-cli/src/main.rs +++ b/gen/games1-cli/src/main.rs @@ -5009,7 +5009,7 @@ fn main() { let mut app = App::new("games1") .author("Sebastian Thiel ") - .version("0.3.2+20150717") + .version("0.3.2+20151012") .about("The API for Google Play Game Services.") .after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_games1_cli") .arg(Arg::with_name("url") diff --git a/gen/games1/Cargo.toml b/gen/games1/Cargo.toml index 5ac61529fe..abbfdba333 100644 --- a/gen/games1/Cargo.toml +++ b/gen/games1/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-games1" -version = "0.1.9+20150717" +version = "0.1.9+20151012" authors = ["Sebastian Thiel "] description = "A complete library to interact with Games (protocol v1)" repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/games1" diff --git a/gen/games1/README.md b/gen/games1/README.md index 92ecdbf91c..44b737992a 100644 --- a/gen/games1/README.md +++ b/gen/games1/README.md @@ -5,7 +5,7 @@ DO NOT EDIT ! --> The `google-games1` library allows access to all features of the *Google Games* service. -This documentation was generated from *Games* crate version *0.1.9+20150717*, where *20150717* is the exact revision of the *games:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +This documentation was generated from *Games* crate version *0.1.9+20151012*, where *20151012* is the exact revision of the *games:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. Everything else about the *Games* *v1* API can be found at the [official documentation site](https://developers.google.com/games/services/). diff --git a/gen/games1/src/lib.rs b/gen/games1/src/lib.rs index 3342304edd..c428508de0 100644 --- a/gen/games1/src/lib.rs +++ b/gen/games1/src/lib.rs @@ -2,7 +2,7 @@ // This file was generated automatically from 'src/mako/api/lib.rs.mako' // DO NOT EDIT ! -//! This documentation was generated from *Games* crate version *0.1.9+20150717*, where *20150717* is the exact revision of the *games:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +//! This documentation was generated from *Games* crate version *0.1.9+20151012*, where *20151012* is the exact revision of the *games:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. //! //! Everything else about the *Games* *v1* API can be found at the //! [official documentation site](https://developers.google.com/games/services/). diff --git a/gen/gamesconfiguration1_configuration-cli/Cargo.toml b/gen/gamesconfiguration1_configuration-cli/Cargo.toml index f66b418a4a..331c8ec855 100644 --- a/gen/gamesconfiguration1_configuration-cli/Cargo.toml +++ b/gen/gamesconfiguration1_configuration-cli/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-gamesconfiguration1_configuration-cli" -version = "0.3.2+20150717" +version = "0.3.2+20151012" authors = ["Sebastian Thiel "] description = "A complete library to interact with Games Configuration (protocol v1configuration)" repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/gamesconfiguration1_configuration-cli" diff --git a/gen/gamesconfiguration1_configuration-cli/README.md b/gen/gamesconfiguration1_configuration-cli/README.md index 51cf19984d..f4402ca212 100644 --- a/gen/gamesconfiguration1_configuration-cli/README.md +++ b/gen/gamesconfiguration1_configuration-cli/README.md @@ -24,7 +24,7 @@ Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/ma # Usage -This documentation was generated from the *Games Configuration* API at revision *20150717*. The CLI is at version *0.3.2*. +This documentation was generated from the *Games Configuration* API at revision *20151012*. The CLI is at version *0.3.2*. ```bash gamesconfiguration1-configuration [options] diff --git a/gen/gamesconfiguration1_configuration-cli/mkdocs.yml b/gen/gamesconfiguration1_configuration-cli/mkdocs.yml index e3ec10881b..f6bf35c744 100644 --- a/gen/gamesconfiguration1_configuration-cli/mkdocs.yml +++ b/gen/gamesconfiguration1_configuration-cli/mkdocs.yml @@ -1,4 +1,4 @@ -site_name: Games Configuration v0.3.2+20150717 +site_name: Games Configuration v0.3.2+20151012 site_url: http://byron.github.io/google-apis-rs/google-gamesconfiguration1_configuration-cli site_description: Write integrating applications with bcore diff --git a/gen/gamesconfiguration1_configuration-cli/src/main.rs b/gen/gamesconfiguration1_configuration-cli/src/main.rs index 7bc45ee4a5..e322133388 100644 --- a/gen/gamesconfiguration1_configuration-cli/src/main.rs +++ b/gen/gamesconfiguration1_configuration-cli/src/main.rs @@ -1551,7 +1551,7 @@ fn main() { let mut app = App::new("gamesconfiguration1-configuration") .author("Sebastian Thiel ") - .version("0.3.2+20150717") + .version("0.3.2+20151012") .about("The Publishing API for Google Play Game Services.") .after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_gamesconfiguration1_configuration_cli") .arg(Arg::with_name("url") diff --git a/gen/gamesconfiguration1_configuration/Cargo.toml b/gen/gamesconfiguration1_configuration/Cargo.toml index 7a7808bb67..1f16428569 100644 --- a/gen/gamesconfiguration1_configuration/Cargo.toml +++ b/gen/gamesconfiguration1_configuration/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-gamesconfiguration1_configuration" -version = "0.1.9+20150717" +version = "0.1.9+20151012" authors = ["Sebastian Thiel "] description = "A complete library to interact with Games Configuration (protocol v1configuration)" repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/gamesconfiguration1_configuration" diff --git a/gen/gamesconfiguration1_configuration/README.md b/gen/gamesconfiguration1_configuration/README.md index 2017bfb4cf..0004f6cd2a 100644 --- a/gen/gamesconfiguration1_configuration/README.md +++ b/gen/gamesconfiguration1_configuration/README.md @@ -5,7 +5,7 @@ DO NOT EDIT ! --> The `google-gamesconfiguration1_configuration` library allows access to all features of the *Google Games Configuration* service. -This documentation was generated from *Games Configuration* crate version *0.1.9+20150717*, where *20150717* is the exact revision of the *gamesConfiguration:v1configuration* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +This documentation was generated from *Games Configuration* crate version *0.1.9+20151012*, where *20151012* is the exact revision of the *gamesConfiguration:v1configuration* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. Everything else about the *Games Configuration* *v1_configuration* API can be found at the [official documentation site](https://developers.google.com/games/services). diff --git a/gen/gamesconfiguration1_configuration/src/lib.rs b/gen/gamesconfiguration1_configuration/src/lib.rs index b11caf5c94..37cae36264 100644 --- a/gen/gamesconfiguration1_configuration/src/lib.rs +++ b/gen/gamesconfiguration1_configuration/src/lib.rs @@ -2,7 +2,7 @@ // This file was generated automatically from 'src/mako/api/lib.rs.mako' // DO NOT EDIT ! -//! This documentation was generated from *Games Configuration* crate version *0.1.9+20150717*, where *20150717* is the exact revision of the *gamesConfiguration:v1configuration* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +//! This documentation was generated from *Games Configuration* crate version *0.1.9+20151012*, where *20151012* is the exact revision of the *gamesConfiguration:v1configuration* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. //! //! Everything else about the *Games Configuration* *v1_configuration* API can be found at the //! [official documentation site](https://developers.google.com/games/services). diff --git a/gen/gamesconfiguration1_configuration/src/lib.rs.in b/gen/gamesconfiguration1_configuration/src/lib.rs.in index 5ff6c6f25d..0ae8647cf8 100644 --- a/gen/gamesconfiguration1_configuration/src/lib.rs.in +++ b/gen/gamesconfiguration1_configuration/src/lib.rs.in @@ -1097,10 +1097,10 @@ impl<'a, C, A> ImageConfigurationUploadCall<'a, C, A> where C: BorrowMut"] description = "A complete library to interact with Games Management (protocol v1management)" repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/gamesmanagement1_management-cli" diff --git a/gen/gamesmanagement1_management-cli/README.md b/gen/gamesmanagement1_management-cli/README.md index 25f5df3d87..534c138ea1 100644 --- a/gen/gamesmanagement1_management-cli/README.md +++ b/gen/gamesmanagement1_management-cli/README.md @@ -24,7 +24,7 @@ Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/ma # Usage -This documentation was generated from the *Games Management* API at revision *20150717*. The CLI is at version *0.3.2*. +This documentation was generated from the *Games Management* API at revision *20151012*. The CLI is at version *0.3.2*. ```bash gamesmanagement1-management [options] diff --git a/gen/gamesmanagement1_management-cli/mkdocs.yml b/gen/gamesmanagement1_management-cli/mkdocs.yml index 4aed280f25..c0c0e34596 100644 --- a/gen/gamesmanagement1_management-cli/mkdocs.yml +++ b/gen/gamesmanagement1_management-cli/mkdocs.yml @@ -1,4 +1,4 @@ -site_name: Games Management v0.3.2+20150717 +site_name: Games Management v0.3.2+20151012 site_url: http://byron.github.io/google-apis-rs/google-gamesmanagement1_management-cli site_description: Write integrating applications with bcore diff --git a/gen/gamesmanagement1_management-cli/src/main.rs b/gen/gamesmanagement1_management-cli/src/main.rs index 9182e7f0c9..0073bdf07e 100644 --- a/gen/gamesmanagement1_management-cli/src/main.rs +++ b/gen/gamesmanagement1_management-cli/src/main.rs @@ -2078,7 +2078,7 @@ fn main() { let mut app = App::new("gamesmanagement1-management") .author("Sebastian Thiel ") - .version("0.3.2+20150717") + .version("0.3.2+20151012") .about("The Management API for Google Play Game Services.") .after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_gamesmanagement1_management_cli") .arg(Arg::with_name("url") diff --git a/gen/gamesmanagement1_management/Cargo.toml b/gen/gamesmanagement1_management/Cargo.toml index 8d803dcc72..1e4dc21e6a 100644 --- a/gen/gamesmanagement1_management/Cargo.toml +++ b/gen/gamesmanagement1_management/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-gamesmanagement1_management" -version = "0.1.9+20150717" +version = "0.1.9+20151012" authors = ["Sebastian Thiel "] description = "A complete library to interact with Games Management (protocol v1management)" repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/gamesmanagement1_management" diff --git a/gen/gamesmanagement1_management/README.md b/gen/gamesmanagement1_management/README.md index 03d42b4bdf..cff8a0f492 100644 --- a/gen/gamesmanagement1_management/README.md +++ b/gen/gamesmanagement1_management/README.md @@ -5,7 +5,7 @@ DO NOT EDIT ! --> The `google-gamesmanagement1_management` library allows access to all features of the *Google Games Management* service. -This documentation was generated from *Games Management* crate version *0.1.9+20150717*, where *20150717* is the exact revision of the *gamesManagement:v1management* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +This documentation was generated from *Games Management* crate version *0.1.9+20151012*, where *20151012* is the exact revision of the *gamesManagement:v1management* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. Everything else about the *Games Management* *v1_management* API can be found at the [official documentation site](https://developers.google.com/games/services). diff --git a/gen/gamesmanagement1_management/src/lib.rs b/gen/gamesmanagement1_management/src/lib.rs index 7151b8b795..08a140abb6 100644 --- a/gen/gamesmanagement1_management/src/lib.rs +++ b/gen/gamesmanagement1_management/src/lib.rs @@ -2,7 +2,7 @@ // This file was generated automatically from 'src/mako/api/lib.rs.mako' // DO NOT EDIT ! -//! This documentation was generated from *Games Management* crate version *0.1.9+20150717*, where *20150717* is the exact revision of the *gamesManagement:v1management* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +//! This documentation was generated from *Games Management* crate version *0.1.9+20151012*, where *20151012* is the exact revision of the *gamesManagement:v1management* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. //! //! Everything else about the *Games Management* *v1_management* API can be found at the //! [official documentation site](https://developers.google.com/games/services). diff --git a/gen/genomics1-cli/Cargo.toml b/gen/genomics1-cli/Cargo.toml index 1320a9da86..7695a26add 100644 --- a/gen/genomics1-cli/Cargo.toml +++ b/gen/genomics1-cli/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-genomics1-cli" -version = "0.3.2+20150716" +version = "0.3.2+20151014" authors = ["Sebastian Thiel "] description = "A complete library to interact with genomics (protocol v1)" repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/genomics1-cli" diff --git a/gen/genomics1-cli/README.md b/gen/genomics1-cli/README.md index 1b10b0395e..553a7e3581 100644 --- a/gen/genomics1-cli/README.md +++ b/gen/genomics1-cli/README.md @@ -21,7 +21,7 @@ Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/ma # Usage -This documentation was generated from the *genomics* API at revision *20150716*. The CLI is at version *0.3.2*. +This documentation was generated from the *genomics* API at revision *20151014*. The CLI is at version *0.3.2*. ```bash genomics1 [options] @@ -35,8 +35,11 @@ genomics1 [options] create (-r )... [-p ]... [-o ] delete [-p ]... [-o ] get [-p ]... [-o ] + get-iam-policy (-r )... [-p ]... [-o ] list [-p ]... [-o ] patch (-r )... [-p ]... [-o ] + set-iam-policy (-r )... [-p ]... [-o ] + test-iam-permissions (-r )... [-p ]... [-o ] undelete (-r )... [-p ]... [-o ] operations cancel (-r )... [-p ]... [-o ] @@ -65,7 +68,6 @@ genomics1 [options] delete [-p ]... [-o ] get [-p ]... [-o ] import (-r )... [-p ]... [-o ] - merge (-r )... [-p ]... [-o ] patch (-r )... [-p ]... [-o ] search (-r )... [-p ]... [-o ] variantsets diff --git a/gen/genomics1-cli/mkdocs.yml b/gen/genomics1-cli/mkdocs.yml index 4e14268a30..fbe033a251 100644 --- a/gen/genomics1-cli/mkdocs.yml +++ b/gen/genomics1-cli/mkdocs.yml @@ -1,4 +1,4 @@ -site_name: genomics v0.3.2+20150716 +site_name: genomics v0.3.2+20151014 site_url: http://byron.github.io/google-apis-rs/google-genomics1-cli site_description: Write integrating applications with bcore @@ -17,8 +17,11 @@ pages: - ['datasets_create.md', 'Datasets', 'Create'] - ['datasets_delete.md', 'Datasets', 'Delete'] - ['datasets_get.md', 'Datasets', 'Get'] +- ['datasets_get-iam-policy.md', 'Datasets', 'Get Iam Policy'] - ['datasets_list.md', 'Datasets', 'List'] - ['datasets_patch.md', 'Datasets', 'Patch'] +- ['datasets_set-iam-policy.md', 'Datasets', 'Set Iam Policy'] +- ['datasets_test-iam-permissions.md', 'Datasets', 'Test Iam Permissions'] - ['datasets_undelete.md', 'Datasets', 'Undelete'] - ['operations_cancel.md', 'Operations', 'Cancel'] - ['operations_delete.md', 'Operations', 'Delete'] @@ -41,7 +44,6 @@ pages: - ['variants_delete.md', 'Variants', 'Delete'] - ['variants_get.md', 'Variants', 'Get'] - ['variants_import.md', 'Variants', 'Import'] -- ['variants_merge.md', 'Variants', 'Merge'] - ['variants_patch.md', 'Variants', 'Patch'] - ['variants_search.md', 'Variants', 'Search'] - ['variantsets_create.md', 'Variantsets', 'Create'] diff --git a/gen/genomics1-cli/src/main.rs b/gen/genomics1-cli/src/main.rs index fe2f3d313b..5512bcb42c 100644 --- a/gen/genomics1-cli/src/main.rs +++ b/gen/genomics1-cli/src/main.rs @@ -611,6 +611,90 @@ impl<'n, 'a> Engine<'n, 'a> { } } + fn _datasets_get_iam_policy(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec![]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::GetIamPolicyRequest = json::value::from_value(object).unwrap(); + let mut call = self.hub.datasets().get_iam_policy(request, opt.value_of("resource").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + fn _datasets_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) -> Result<(), DoitError> { let mut call = self.hub.datasets().list(); @@ -765,6 +849,177 @@ impl<'n, 'a> Engine<'n, 'a> { } } + fn _datasets_set_iam_policy(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "policy.version" => Some(("policy.version", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "policy.etag" => Some(("policy.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["etag", "policy", "version"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::SetIamPolicyRequest = json::value::from_value(object).unwrap(); + let mut call = self.hub.datasets().set_iam_policy(request, opt.value_of("resource").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _datasets_test_iam_permissions(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "permissions" => Some(("permissions", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["permissions"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::TestIamPermissionsRequest = json::value::from_value(object).unwrap(); + let mut call = self.hub.datasets().test_iam_permissions(request, opt.value_of("resource").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + fn _datasets_undelete(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) -> Result<(), DoitError> { @@ -2355,91 +2610,6 @@ impl<'n, 'a> Engine<'n, 'a> { } } - fn _variants_merge(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) - -> Result<(), DoitError> { - - let mut field_cursor = FieldCursor::default(); - let mut object = json::value::Value::Object(Default::default()); - - for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { - let last_errc = err.issues.len(); - let (key, value) = parse_kv_arg(&*kvarg, err, false); - let mut temp_cursor = field_cursor.clone(); - if let Err(field_err) = temp_cursor.set(&*key) { - err.issues.push(field_err); - } - if value.is_none() { - field_cursor = temp_cursor.clone(); - if err.issues.len() > last_errc { - err.issues.remove(last_errc); - } - continue; - } - - let type_info: Option<(&'static str, JsonTypeInfo)> = - match &temp_cursor.to_string()[..] { - "variant-set-id" => Some(("variantSetId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), - _ => { - let suggestion = FieldCursor::did_you_mean(key, &vec!["variant-set-id"]); - err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); - None - } - }; - if let Some((field_cursor_str, type_info)) = type_info { - FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); - } - } - let mut request: api::MergeVariantsRequest = json::value::from_value(object).unwrap(); - let mut call = self.hub.variants().merge(request); - for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { - let (key, value) = parse_kv_arg(&*parg, err, false); - match key { - _ => { - let mut found = false; - for param in &self.gp { - if key == *param { - found = true; - call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); - break; - } - } - if !found { - err.issues.push(CLIError::UnknownParameter(key.to_string(), - {let mut v = Vec::new(); - v.extend(self.gp.iter().map(|v|*v)); - v } )); - } - } - } - } - let protocol = CallType::Standard; - if dry_run { - Ok(()) - } else { - assert!(err.issues.len() == 0); - for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { - call = call.add_scope(scope); - } - let mut ostream = match writer_from_opts(opt.value_of("out")) { - Ok(mut f) => f, - Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), - }; - match match protocol { - CallType::Standard => call.doit(), - _ => unreachable!() - } { - Err(api_err) => Err(DoitError::ApiError(api_err)), - Ok((mut response, output_schema)) => { - let mut value = json::value::to_value(&output_schema); - remove_json_null_values(&mut value); - json::to_writer_pretty(&mut ostream, &value).unwrap(); - ostream.flush().unwrap(); - Ok(()) - } - } - } - } - fn _variants_patch(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) -> Result<(), DoitError> { @@ -3127,12 +3297,21 @@ impl<'n, 'a> Engine<'n, 'a> { ("get", Some(opt)) => { call_result = self._datasets_get(opt, dry_run, &mut err); }, + ("get-iam-policy", Some(opt)) => { + call_result = self._datasets_get_iam_policy(opt, dry_run, &mut err); + }, ("list", Some(opt)) => { call_result = self._datasets_list(opt, dry_run, &mut err); }, ("patch", Some(opt)) => { call_result = self._datasets_patch(opt, dry_run, &mut err); }, + ("set-iam-policy", Some(opt)) => { + call_result = self._datasets_set_iam_policy(opt, dry_run, &mut err); + }, + ("test-iam-permissions", Some(opt)) => { + call_result = self._datasets_test_iam_permissions(opt, dry_run, &mut err); + }, ("undelete", Some(opt)) => { call_result = self._datasets_undelete(opt, dry_run, &mut err); }, @@ -3247,9 +3426,6 @@ impl<'n, 'a> Engine<'n, 'a> { ("import", Some(opt)) => { call_result = self._variants_import(opt, dry_run, &mut err); }, - ("merge", Some(opt)) => { - call_result = self._variants_merge(opt, dry_run, &mut err); - }, ("patch", Some(opt)) => { call_result = self._variants_patch(opt, dry_run, &mut err); }, @@ -3493,7 +3669,7 @@ fn main() { ]), ]), - ("datasets", "methods: 'create', 'delete', 'get', 'list', 'patch' and 'undelete'", vec![ + ("datasets", "methods: 'create', 'delete', 'get', 'get-iam-policy', 'list', 'patch', 'set-iam-policy', 'test-iam-permissions' and 'undelete'", vec![ ("create", Some(r##"Creates a new dataset."##), "Details at http://byron.github.io/google-apis-rs/google_genomics1_cli/datasets_create", @@ -3554,6 +3730,34 @@ fn main() { Some(false), Some(true)), + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("get-iam-policy", + Some(r##"Gets the access control policy for the dataset. Is empty if the policy or the resource does not exist. See Getting a Policy for more information."##), + "Details at http://byron.github.io/google-apis-rs/google_genomics1_cli/datasets_get-iam-policy", + vec![ + (Some(r##"resource"##), + None, + Some(r##"REQUIRED: The resource for which policy is being specified. Format is `datasets/`."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + (Some(r##"out"##), Some(r##"o"##), Some(r##"Specify the file into which to write the program's output"##), @@ -3598,6 +3802,62 @@ fn main() { Some(false), Some(true)), + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("set-iam-policy", + Some(r##"Sets the access control policy on the specified dataset. Replaces any existing policy. See Setting a Policy for more information."##), + "Details at http://byron.github.io/google-apis-rs/google_genomics1_cli/datasets_set-iam-policy", + vec![ + (Some(r##"resource"##), + None, + Some(r##"REQUIRED: The resource for which policy is being specified. Format is `datasets/`."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("test-iam-permissions", + Some(r##"Returns permissions that a caller has on the specified resource. See Testing Permissions for more information."##), + "Details at http://byron.github.io/google-apis-rs/google_genomics1_cli/datasets_test-iam-permissions", + vec![ + (Some(r##"resource"##), + None, + Some(r##"REQUIRED: The resource for which policy is being specified. Format is `datasets/`."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + (Some(r##"out"##), Some(r##"o"##), Some(r##"Specify the file into which to write the program's output"##), @@ -3636,7 +3896,7 @@ fn main() { ("operations", "methods: 'cancel', 'delete', 'get' and 'list'", vec![ ("cancel", - Some(r##"Starts asynchronous cancellation on a long-running operation. The server makes a best effort to cancel the operation, but success is not guaranteed. Clients may use [Operations.GetOperation][google.longrunning.Operations.GetOperation] or [Operations.ListOperations][google.longrunning.Operations.ListOperations] to check whether the cancellation succeeded or the operation completed despite cancellation."##), + Some(r##"Starts asynchronous cancellation on a long-running operation. The server makes a best effort to cancel the operation, but success is not guaranteed. Clients may use Operations.GetOperation or Operations.ListOperations to check whether the cancellation succeeded or the operation completed despite cancellation."##), "Details at http://byron.github.io/google-apis-rs/google_genomics1_cli/operations_cancel", vec![ (Some(r##"name"##), @@ -3664,7 +3924,7 @@ fn main() { Some(false)), ]), ("delete", - Some(r##"This method is not implemented. To cancel an operation, please use [Operations.CancelOperation][google.longrunning.Operations.CancelOperation]."##), + Some(r##"This method is not implemented. To cancel an operation, please use Operations.CancelOperation."##), "Details at http://byron.github.io/google-apis-rs/google_genomics1_cli/operations_delete", vec![ (Some(r##"name"##), @@ -3777,7 +4037,7 @@ fn main() { Some(false)), ]), ("export", - Some(r##"Exports a read group set to a BAM file in Google Cloud Storage. Note that currently there may be some differences between exported BAM files and the original BAM file at the time of import. In particular, comments in the input file header will not be preserved, some custom tags will be converted to strings, and original reference sequence order is not necessarily preserved."##), + Some(r##"Exports a read group set to a BAM file in Google Cloud Storage. Note that currently there may be some differences between exported BAM files and the original BAM file at the time of import. See [ImportReadGroupSets](google.genomics.v1.ReadServiceV1.ImportReadGroupSets) for caveats."##), "Details at http://byron.github.io/google-apis-rs/google_genomics1_cli/readgroupsets_export", vec![ (Some(r##"read-group-set-id"##), @@ -3827,7 +4087,7 @@ fn main() { Some(false)), ]), ("import", - Some(r##"Creates read group sets by asynchronously importing the provided information. Note that currently comments in the input file header are **not** imported and some custom tags will be converted to strings, rather than preserving tag types. The caller must have WRITE permissions to the dataset."##), + Some(r##"Creates read group sets by asynchronously importing the provided information. The caller must have WRITE permissions to the dataset. ## Notes on [BAM](https://samtools.github.io/hts-specs/SAMv1.pdf) import - Tags will be converted to strings - tag types are not preserved - Comments (`@CO`) in the input file header will not be preserved - Original header order of references (`@SQ`) will not be preserved - Any reverse stranded unmapped reads will be reverse complemented, and their qualities (and "BQ" tag, if any) will be reversed - Unmapped reads will be stripped of positional information (reference name and position)"##), "Details at http://byron.github.io/google-apis-rs/google_genomics1_cli/readgroupsets_import", vec![ (Some(r##"kv"##), @@ -4041,7 +4301,7 @@ fn main() { ]), ]), - ("variants", "methods: 'create', 'delete', 'get', 'import', 'merge', 'patch' and 'search'", vec![ + ("variants", "methods: 'create', 'delete', 'get', 'import', 'patch' and 'search'", vec![ ("create", Some(r##"Creates a new variant."##), "Details at http://byron.github.io/google-apis-rs/google_genomics1_cli/variants_create", @@ -4109,7 +4369,7 @@ fn main() { Some(false)), ]), ("import", - Some(r##"Creates variant data by asynchronously importing the provided information. The variants for import will be merged with any existing data and each other according to the behavior of mergeVariants. In particular, this means for merged VCF variants that have conflicting INFO fields, some data will be arbitrarily discarded. As a special case, for single-sample VCF files, QUAL and FILTER fields will be moved to the call level; these are sometimes interpreted in a call-specific context. Imported VCF headers are appended to the metadata already in a variant set."##), + Some(r##"Creates variant data by asynchronously importing the provided information. The variants for import will be merged with any existing variant that matches its reference sequence, start, end, reference bases, and alternative bases. If no such variant exists, a new one will be created. When variants are merged, the call information from the new variant is added to the existing variant, and other fields (such as key/value pairs) are discarded. In particular, this means for merged VCF variants that have conflicting INFO fields, some data will be arbitrarily discarded. As a special case, for single-sample VCF files, QUAL and FILTER fields will be moved to the call level; these are sometimes interpreted in a call-specific context. Imported VCF headers are appended to the metadata already in a variant set."##), "Details at http://byron.github.io/google-apis-rs/google_genomics1_cli/variants_import", vec![ (Some(r##"kv"##), @@ -4124,28 +4384,6 @@ fn main() { Some(false), Some(true)), - (Some(r##"out"##), - Some(r##"o"##), - Some(r##"Specify the file into which to write the program's output"##), - Some(false), - Some(false)), - ]), - ("merge", - Some(r##"Merges the given variants with existing variants. Each variant will be merged with an existing variant that matches its reference sequence, start, end, reference bases, and alternative bases. If no such variant exists, a new one will be created. When variants are merged, the call information from the new variant is added to the existing variant, and other fields (such as key/value pairs) are discarded."##), - "Details at http://byron.github.io/google-apis-rs/google_genomics1_cli/variants_merge", - vec![ - (Some(r##"kv"##), - Some(r##"r"##), - Some(r##"Set various fields of the request structure, matching the key=value form"##), - Some(true), - Some(true)), - - (Some(r##"v"##), - Some(r##"p"##), - Some(r##"Set various optional parameters, matching the key=value form"##), - Some(false), - Some(true)), - (Some(r##"out"##), Some(r##"o"##), Some(r##"Specify the file into which to write the program's output"##), @@ -4206,7 +4444,7 @@ fn main() { ("variantsets", "methods: 'create', 'delete', 'export', 'get', 'patch' and 'search'", vec![ ("create", - Some(r##"Creates a new variant set."##), + Some(r##"Creates a new variant set. The provided variant set must have a valid `datasetId` set - all other fields are optional. Note that the `id` field will be ignored, as this is assigned by the server."##), "Details at http://byron.github.io/google-apis-rs/google_genomics1_cli/variantsets_create", vec![ (Some(r##"kv"##), @@ -4355,7 +4593,7 @@ fn main() { let mut app = App::new("genomics1") .author("Sebastian Thiel ") - .version("0.3.2+20150716") + .version("0.3.2+20151014") .about("An API to store, process, explore, and share DNA sequence reads, reference-based alignments, and variant calls.") .after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_genomics1_cli") .arg(Arg::with_name("url") diff --git a/gen/genomics1/Cargo.toml b/gen/genomics1/Cargo.toml index 1d81a77b70..d0a375cef5 100644 --- a/gen/genomics1/Cargo.toml +++ b/gen/genomics1/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-genomics1" -version = "0.1.9+20150716" +version = "0.1.9+20151014" authors = ["Sebastian Thiel "] description = "A complete library to interact with genomics (protocol v1)" repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/genomics1" diff --git a/gen/genomics1/README.md b/gen/genomics1/README.md index 04779dc270..1c40c3c1dc 100644 --- a/gen/genomics1/README.md +++ b/gen/genomics1/README.md @@ -5,7 +5,7 @@ DO NOT EDIT ! --> The `google-genomics1` library allows access to all features of the *Google genomics* service. -This documentation was generated from *genomics* crate version *0.1.9+20150716*, where *20150716* is the exact revision of the *genomics:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +This documentation was generated from *genomics* crate version *0.1.9+20151014*, where *20151014* is the exact revision of the *genomics:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. # Features Handle the following *Resources* with ease from the central [hub](http://byron.github.io/google-apis-rs/google_genomics1/struct.Genomics.html) ... @@ -13,7 +13,7 @@ Handle the following *Resources* with ease from the central [hub](http://byron.g * callsets * [*create*](http://byron.github.io/google-apis-rs/google_genomics1/struct.CallsetCreateCall.html), [*delete*](http://byron.github.io/google-apis-rs/google_genomics1/struct.CallsetDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google_genomics1/struct.CallsetGetCall.html), [*patch*](http://byron.github.io/google-apis-rs/google_genomics1/struct.CallsetPatchCall.html) and [*search*](http://byron.github.io/google-apis-rs/google_genomics1/struct.CallsetSearchCall.html) * [datasets](http://byron.github.io/google-apis-rs/google_genomics1/struct.Dataset.html) - * [*create*](http://byron.github.io/google-apis-rs/google_genomics1/struct.DatasetCreateCall.html), [*delete*](http://byron.github.io/google-apis-rs/google_genomics1/struct.DatasetDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google_genomics1/struct.DatasetGetCall.html), [*list*](http://byron.github.io/google-apis-rs/google_genomics1/struct.DatasetListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google_genomics1/struct.DatasetPatchCall.html) and [*undelete*](http://byron.github.io/google-apis-rs/google_genomics1/struct.DatasetUndeleteCall.html) + * [*create*](http://byron.github.io/google-apis-rs/google_genomics1/struct.DatasetCreateCall.html), [*delete*](http://byron.github.io/google-apis-rs/google_genomics1/struct.DatasetDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google_genomics1/struct.DatasetGetCall.html), [*get iam policy*](http://byron.github.io/google-apis-rs/google_genomics1/struct.DatasetGetIamPolicyCall.html), [*list*](http://byron.github.io/google-apis-rs/google_genomics1/struct.DatasetListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google_genomics1/struct.DatasetPatchCall.html), [*set iam policy*](http://byron.github.io/google-apis-rs/google_genomics1/struct.DatasetSetIamPolicyCall.html), [*test iam permissions*](http://byron.github.io/google-apis-rs/google_genomics1/struct.DatasetTestIamPermissionCall.html) and [*undelete*](http://byron.github.io/google-apis-rs/google_genomics1/struct.DatasetUndeleteCall.html) * [operations](http://byron.github.io/google-apis-rs/google_genomics1/struct.Operation.html) * [*cancel*](http://byron.github.io/google-apis-rs/google_genomics1/struct.OperationCancelCall.html), [*delete*](http://byron.github.io/google-apis-rs/google_genomics1/struct.OperationDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google_genomics1/struct.OperationGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google_genomics1/struct.OperationListCall.html) * readgroupsets @@ -25,7 +25,7 @@ Handle the following *Resources* with ease from the central [hub](http://byron.g * referencesets * [*get*](http://byron.github.io/google-apis-rs/google_genomics1/struct.ReferencesetGetCall.html) and [*search*](http://byron.github.io/google-apis-rs/google_genomics1/struct.ReferencesetSearchCall.html) * [variants](http://byron.github.io/google-apis-rs/google_genomics1/struct.Variant.html) - * [*create*](http://byron.github.io/google-apis-rs/google_genomics1/struct.VariantCreateCall.html), [*delete*](http://byron.github.io/google-apis-rs/google_genomics1/struct.VariantDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google_genomics1/struct.VariantGetCall.html), [*import*](http://byron.github.io/google-apis-rs/google_genomics1/struct.VariantImportCall.html), [*merge*](http://byron.github.io/google-apis-rs/google_genomics1/struct.VariantMergeCall.html), [*patch*](http://byron.github.io/google-apis-rs/google_genomics1/struct.VariantPatchCall.html) and [*search*](http://byron.github.io/google-apis-rs/google_genomics1/struct.VariantSearchCall.html) + * [*create*](http://byron.github.io/google-apis-rs/google_genomics1/struct.VariantCreateCall.html), [*delete*](http://byron.github.io/google-apis-rs/google_genomics1/struct.VariantDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google_genomics1/struct.VariantGetCall.html), [*import*](http://byron.github.io/google-apis-rs/google_genomics1/struct.VariantImportCall.html), [*patch*](http://byron.github.io/google-apis-rs/google_genomics1/struct.VariantPatchCall.html) and [*search*](http://byron.github.io/google-apis-rs/google_genomics1/struct.VariantSearchCall.html) * variantsets * [*create*](http://byron.github.io/google-apis-rs/google_genomics1/struct.VariantsetCreateCall.html), [*delete*](http://byron.github.io/google-apis-rs/google_genomics1/struct.VariantsetDeleteCall.html), [*export*](http://byron.github.io/google-apis-rs/google_genomics1/struct.VariantsetExportCall.html), [*get*](http://byron.github.io/google-apis-rs/google_genomics1/struct.VariantsetGetCall.html), [*patch*](http://byron.github.io/google-apis-rs/google_genomics1/struct.VariantsetPatchCall.html) and [*search*](http://byron.github.io/google-apis-rs/google_genomics1/struct.VariantsetSearchCall.html) @@ -60,14 +60,15 @@ let r = hub.resource().activity(...).doit() Or specifically ... ```ignore -let r = hub.operations().delete(...).doit() -let r = hub.operations().cancel(...).doit() -let r = hub.variantsets().export(...).doit() -let r = hub.readgroupsets().export(...).doit() -let r = hub.variants().import(...).doit() -let r = hub.readgroupsets().import(...).doit() -let r = hub.operations().get(...).doit() -let r = hub.operations().list(...).doit() +let r = hub.datasets().set_iam_policy(...).doit() +let r = hub.datasets().delete(...).doit() +let r = hub.datasets().get_iam_policy(...).doit() +let r = hub.datasets().test_iam_permissions(...).doit() +let r = hub.datasets().get(...).doit() +let r = hub.datasets().undelete(...).doit() +let r = hub.datasets().create(...).doit() +let r = hub.datasets().patch(...).doit() +let r = hub.datasets().list(...).doit() ``` The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` @@ -92,6 +93,7 @@ google-genomics1 = "*" extern crate hyper; extern crate yup_oauth2 as oauth2; extern crate google_genomics1 as genomics1; +use genomics1::Dataset; use genomics1::{Result, Error}; use std::default::Default; use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; @@ -109,13 +111,16 @@ let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, hyper::Client::new(), ::default(), None); let mut hub = Genomics::new(hyper::Client::new(), auth); +// As the method needs a request, you would usually fill it with the desired information +// into the 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(); + // You can configure optional parameters by calling 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("name") - .page_token("sit") - .page_size(-65) - .filter("sed") +let result = hub.datasets().patch(req, "datasetId") + .update_mask("sit") .doit(); match result { diff --git a/gen/genomics1/src/lib.rs b/gen/genomics1/src/lib.rs index a65175bc14..7d11638eac 100644 --- a/gen/genomics1/src/lib.rs +++ b/gen/genomics1/src/lib.rs @@ -2,7 +2,7 @@ // This file was generated automatically from 'src/mako/api/lib.rs.mako' // DO NOT EDIT ! -//! This documentation was generated from *genomics* crate version *0.1.9+20150716*, where *20150716* is the exact revision of the *genomics:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +//! This documentation was generated from *genomics* crate version *0.1.9+20151014*, where *20151014* is the exact revision of the *genomics:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. //! The original source code is [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/genomics1). //! # Features //! @@ -11,7 +11,7 @@ //! * callsets //! * [*create*](struct.CallsetCreateCall.html), [*delete*](struct.CallsetDeleteCall.html), [*get*](struct.CallsetGetCall.html), [*patch*](struct.CallsetPatchCall.html) and [*search*](struct.CallsetSearchCall.html) //! * [datasets](struct.Dataset.html) -//! * [*create*](struct.DatasetCreateCall.html), [*delete*](struct.DatasetDeleteCall.html), [*get*](struct.DatasetGetCall.html), [*list*](struct.DatasetListCall.html), [*patch*](struct.DatasetPatchCall.html) and [*undelete*](struct.DatasetUndeleteCall.html) +//! * [*create*](struct.DatasetCreateCall.html), [*delete*](struct.DatasetDeleteCall.html), [*get*](struct.DatasetGetCall.html), [*get iam policy*](struct.DatasetGetIamPolicyCall.html), [*list*](struct.DatasetListCall.html), [*patch*](struct.DatasetPatchCall.html), [*set iam policy*](struct.DatasetSetIamPolicyCall.html), [*test iam permissions*](struct.DatasetTestIamPermissionCall.html) and [*undelete*](struct.DatasetUndeleteCall.html) //! * [operations](struct.Operation.html) //! * [*cancel*](struct.OperationCancelCall.html), [*delete*](struct.OperationDeleteCall.html), [*get*](struct.OperationGetCall.html) and [*list*](struct.OperationListCall.html) //! * readgroupsets @@ -23,7 +23,7 @@ //! * referencesets //! * [*get*](struct.ReferencesetGetCall.html) and [*search*](struct.ReferencesetSearchCall.html) //! * [variants](struct.Variant.html) -//! * [*create*](struct.VariantCreateCall.html), [*delete*](struct.VariantDeleteCall.html), [*get*](struct.VariantGetCall.html), [*import*](struct.VariantImportCall.html), [*merge*](struct.VariantMergeCall.html), [*patch*](struct.VariantPatchCall.html) and [*search*](struct.VariantSearchCall.html) +//! * [*create*](struct.VariantCreateCall.html), [*delete*](struct.VariantDeleteCall.html), [*get*](struct.VariantGetCall.html), [*import*](struct.VariantImportCall.html), [*patch*](struct.VariantPatchCall.html) and [*search*](struct.VariantSearchCall.html) //! * variantsets //! * [*create*](struct.VariantsetCreateCall.html), [*delete*](struct.VariantsetDeleteCall.html), [*export*](struct.VariantsetExportCall.html), [*get*](struct.VariantsetGetCall.html), [*patch*](struct.VariantsetPatchCall.html) and [*search*](struct.VariantsetSearchCall.html) //! @@ -60,14 +60,15 @@ //! Or specifically ... //! //! ```ignore -//! let r = hub.operations().delete(...).doit() -//! let r = hub.operations().cancel(...).doit() -//! let r = hub.variantsets().export(...).doit() -//! let r = hub.readgroupsets().export(...).doit() -//! let r = hub.variants().import(...).doit() -//! let r = hub.readgroupsets().import(...).doit() -//! let r = hub.operations().get(...).doit() -//! let r = hub.operations().list(...).doit() +//! let r = hub.datasets().set_iam_policy(...).doit() +//! let r = hub.datasets().delete(...).doit() +//! let r = hub.datasets().get_iam_policy(...).doit() +//! let r = hub.datasets().test_iam_permissions(...).doit() +//! let r = hub.datasets().get(...).doit() +//! let r = hub.datasets().undelete(...).doit() +//! let r = hub.datasets().create(...).doit() +//! let r = hub.datasets().patch(...).doit() +//! let r = hub.datasets().list(...).doit() //! ``` //! //! The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` @@ -92,6 +93,7 @@ //! extern crate hyper; //! extern crate yup_oauth2 as oauth2; //! extern crate google_genomics1 as genomics1; +//! use genomics1::Dataset; //! use genomics1::{Result, Error}; //! # #[test] fn egal() { //! use std::default::Default; @@ -110,13 +112,16 @@ //! hyper::Client::new(), //! ::default(), None); //! let mut hub = Genomics::new(hyper::Client::new(), auth); +//! // As the method needs a request, you would usually fill it with the desired information +//! // into the 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(); +//! //! // You can configure optional parameters by calling 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("name") -//! .page_token("et") -//! .page_size(-45) -//! .filter("ut") +//! let result = hub.datasets().patch(req, "datasetId") +//! .update_mask("amet") //! .doit(); //! //! match result { diff --git a/gen/genomics1/src/lib.rs.in b/gen/genomics1/src/lib.rs.in index e01d46dc9f..567683055b 100644 --- a/gen/genomics1/src/lib.rs.in +++ b/gen/genomics1/src/lib.rs.in @@ -85,6 +85,7 @@ impl Default for Scope { /// extern crate hyper; /// extern crate yup_oauth2 as oauth2; /// extern crate google_genomics1 as genomics1; +/// use genomics1::Dataset; /// use genomics1::{Result, Error}; /// # #[test] fn egal() { /// use std::default::Default; @@ -103,13 +104,16 @@ impl Default for Scope { /// hyper::Client::new(), /// ::default(), None); /// let mut hub = Genomics::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the 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(); +/// /// // You can configure optional parameters by calling 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("name") -/// .page_token("dolores") -/// .page_size(-63) -/// .filter("accusam") +/// let result = hub.datasets().patch(req, "datasetId") +/// .update_mask("sed") /// .doit(); /// /// match result { @@ -219,6 +223,73 @@ pub struct SearchReadGroupSetsRequest { impl RequestValue for SearchReadGroupSetsRequest {} +/// This resource represents a long-running operation that is the result of a network API call. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where 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 operations](struct.OperationDeleteCall.html) (none) +/// * [cancel operations](struct.OperationCancelCall.html) (none) +/// * [export variantsets](struct.VariantsetExportCall.html) (response) +/// * [export readgroupsets](struct.ReadgroupsetExportCall.html) (response) +/// * [import variants](struct.VariantImportCall.html) (response) +/// * [import readgroupsets](struct.ReadgroupsetImportCall.html) (response) +/// * [get operations](struct.OperationGetCall.html) (response) +/// * [list operations](struct.OperationListCall.html) (none) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Operation { + /// An OperationMetadata object. This will always be returned with the Operation. + pub metadata: Option>, + /// If the value is `false`, it means the operation is still in progress. If true, the operation is completed, and either `error` or `response` is available. + pub done: Option, + /// If importing ReadGroupSets, an ImportReadGroupSetsResponse is returned. If importing Variants, an ImportVariantsResponse is returned. For exports, an empty response is returned. + pub response: Option>, + /// The server-assigned name, which is only unique within the same service that originally returns it. For example: `operations/CJHU7Oi_ChDrveSpBRjfuL-qzoWAgEw` + pub name: Option, + /// The error result of the operation in case of failure. + pub error: Option, +} + +impl Resource for Operation {} +impl ResponseResult for Operation {} + + +/// Request message for `SetIamPolicy` 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*). +/// +/// * [set iam policy datasets](struct.DatasetSetIamPolicyCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct SetIamPolicyRequest { + /// REQUIRED: The complete policy to be applied to the `resource`. The size of the policy is limited to a few 10s of KB. An empty policy is a valid policy but certain Cloud Platform services (such as Projects) might reject them. + pub policy: Option, +} + +impl RequestValue for SetIamPolicyRequest {} + + +/// Associates `members` with a `role`. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Binding { + /// Role that is assigned to `members`. For example, `roles/viewer`, `roles/editor`, or `roles/owner`. Required + pub role: Option, + /// Specifies the identities requesting access for a Cloud Platform resource. `members` can have the following formats: * `allUsers`: A special identifier that represents anyone who is on the internet; with or without a Google account. * `allAuthenticatedUsers`: A special identifier that represents anyone who is authenticated with a Google account or a service account. * `user:{emailid}`: An email address that represents a specific Google account. For example, `alice@gmail.com` or `joe@example.com`. * `serviceAccount:{emailid}`: An email address that represents a service account. For example, `my-other-app@appspot.gserviceaccount.com`. * `group:{emailid}`: An email address that represents a Google group. For example, `admins@example.com`. * `domain:{domain}`: A Google Apps domain name that represents all the users of that domain. For example, `google.com` or `example.com`. + pub members: Option>, +} + +impl Part for Binding {} + + /// The search variant sets request. /// /// # Activities @@ -314,63 +385,45 @@ impl RequestValue for ExportReadGroupSetRequest {} /// This type is not used in any activity, and only used as *part* of another schema. /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] -pub struct Experiment { - /// The sequencing center used as part of this experiment. - #[serde(rename="sequencingCenter")] - pub sequencing_center: Option, - /// The library used as part of this experiment. Note: This is not an actual ID within this repository, but rather an identifier for a library which may be meaningful to some external system. - #[serde(rename="libraryId")] - pub library_id: Option, - /// The instrument model used as part of this experiment. This maps to sequencing technology in BAM. - #[serde(rename="instrumentModel")] - pub instrument_model: Option, - /// The platform unit used as part of this experiment e.g. flowcell-barcode.lane for Illumina or slide for SOLiD. Corresponds to the @RG PU field in the SAM spec. - #[serde(rename="platformUnit")] - pub platform_unit: Option, +pub struct Program { + /// The command line used to run this program. + #[serde(rename="commandLine")] + pub command_line: Option, + /// The version of the program run. + pub version: Option, + /// The user specified locally unique ID of the program. Used along with `prevProgramId` to define an ordering between programs. + pub id: Option, + /// The name of the program. + pub name: Option, + /// The ID of the program run before this one. + #[serde(rename="prevProgramId")] + pub prev_program_id: Option, } -impl Part for Experiment {} +impl Part for Program {} -/// The variant search request. +/// Defines an Identity and Access Management (IAM) policy. It is used to specify access control policies for Cloud Platform resources. A `Policy` consists of a list of `bindings`. A `Binding` binds a list of `members` to a `role`, where the members can be user accounts, Google groups, Google domains, and service accounts. A `role` is a named list of permissions defined by IAM. **Example** { "bindings": [ { "role": "roles/owner", "members": [ "user:mike@example.com", "group:admins@example.com", "domain:google.com", "serviceAccount:my-other-app@appspot.gserviceaccount.com"] }, { "role": "roles/viewer", "members": ["user:sean@example.com"] } ] } For a description of IAM and its features, see the [IAM developer's guide](https://cloud.google.com/iam). /// /// # Activities /// /// This type is used in activities, which are methods you may call on this type or where this type is involved in. /// The list links the activity name, along with information about where it is used (one of *request* and *response*). /// -/// * [search variants](struct.VariantSearchCall.html) (request) +/// * [set iam policy datasets](struct.DatasetSetIamPolicyCall.html) (response) +/// * [get iam policy datasets](struct.DatasetGetIamPolicyCall.html) (response) /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] -pub struct SearchVariantsRequest { - /// The end of the window, 0-based exclusive. If unspecified or 0, defaults to the length of the reference. - pub end: Option, - /// The maximum number of variants to return. If unspecified, defaults to 5000. - #[serde(rename="pageSize")] - pub page_size: Option, - /// 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. - #[serde(rename="pageToken")] - pub page_token: Option, - /// The maximum number of calls to return. However, at least one variant will always be returned, even if it has more calls than this limit. If unspecified, defaults to 5000. - #[serde(rename="maxCalls")] - pub max_calls: Option, - /// The beginning of the window (0-based, inclusive) for which overlapping variants should be returned. If unspecified, defaults to 0. - pub start: Option, - /// Only return variant calls which belong to call sets with these ids. Leaving this blank returns all variant calls. If a variant has no calls belonging to any of these call sets, it won't be returned at all. Currently, variants with no calls from any call set will never be returned. - #[serde(rename="callSetIds")] - pub call_set_ids: Option>, - /// Only return variants which have exactly this name. - #[serde(rename="variantName")] - pub variant_name: Option, - /// Required. Only return variants in this reference sequence. - #[serde(rename="referenceName")] - pub reference_name: Option, - /// At most one variant set ID must be provided. Only variants from this variant set will be returned. If omitted, a call set id must be included in the request. - #[serde(rename="variantSetIds")] - pub variant_set_ids: Option>, +pub struct Policy { + /// Associates a list of `members` to a `role`. Multiple `bindings` must not be specified for the same `role`. `bindings` with no members will result in an error. + pub bindings: Option>, + /// Version of the `Policy`. The default version is 0. + pub version: Option, + /// Can be used to perform a read-modify-write. + pub etag: Option, } -impl RequestValue for SearchVariantsRequest {} +impl ResponseResult for Policy {} /// The variant data import request. @@ -414,7 +467,6 @@ impl RequestValue for ImportVariantsRequest {} /// * [delete callsets](struct.CallsetDeleteCall.html) (response) /// * [delete variantsets](struct.VariantsetDeleteCall.html) (response) /// * [delete variants](struct.VariantDeleteCall.html) (response) -/// * [merge variants](struct.VariantMergeCall.html) (response) /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct Empty; @@ -422,53 +474,15 @@ pub struct Empty; impl ResponseResult for Empty {} -/// A reference set is a set of references which typically comprise a reference assembly for a species, such as `GRCh38` which is representative of the human genome. A reference set defines a common coordinate space for comparing reference-aligned experimental data. A reference set contains 1 or more references. -/// -/// # Activities -/// -/// This type is used in activities, which are methods you may call on this type or where 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 referencesets](struct.ReferencesetGetCall.html) (response) -/// -#[derive(Default, Clone, Debug, Serialize, Deserialize)] -pub struct ReferenceSet { - /// Free text description of this reference set. - pub description: Option, - /// The URI from which the references were obtained. - #[serde(rename="sourceUri")] - pub source_uri: Option, - /// The IDs of the reference objects that are part of this set. `Reference.md5checksum` must be unique within this set. - #[serde(rename="referenceIds")] - pub reference_ids: Option>, - /// Public id of this reference set, such as `GRCh37`. - #[serde(rename="assemblyId")] - pub assembly_id: Option, - /// All known corresponding accession IDs in INSDC (GenBank/ENA/DDBJ) ideally with a version number, for example `NC_000001.11`. - #[serde(rename="sourceAccessions")] - pub source_accessions: Option>, - /// ID from http://www.ncbi.nlm.nih.gov/taxonomy (e.g. 9606->human) indicating the species which this assembly is intended to model. Note that contained references may specify a different `ncbiTaxonId`, as assemblies may contain reference sequences which do not belong to the modeled species, e.g. EBV in a human reference genome. - #[serde(rename="ncbiTaxonId")] - pub ncbi_taxon_id: Option, - /// The server-generated reference set ID, unique across all reference sets. - pub id: Option, - /// Order-independent MD5 checksum which identifies this reference set. The checksum is computed by sorting all lower case hexidecimal string `reference.md5checksum` (for all reference in this set) in ascending lexicographic order, concatenating, and taking the MD5 of that value. The resulting value is represented in lower case hexadecimal format. - pub md5checksum: Option, -} - -impl Resource for ReferenceSet {} -impl ResponseResult for ReferenceSet {} - - -/// The `Status` defines a logical error model that is suitable for different programming environments, including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). The error model is designed to be: - Simple to use and understand for most users. - Flexible enough to meet unexpected needs. # Overview The `Status` message contains 3 pieces of data: error code, error message, and error details. The error code should be an enum value of [google.rpc.Code][google.rpc.Code], but it may accept additional error codes if needed. The error message should be a developer-facing English message that helps developers *understand* and *resolve* the error. If a localized user-facing error message is needed, it can be sent in the error details or localized by the client. The optional error details may contain arbitrary information about the error. There is a predefined set of error detail types in the package `google.rpc` which can be used for common error conditions. # Language mapping The `Status` message is the logical representation of the error model, but it is not necessarily the actual wire format. When the `Status` message is exposed in different client libraries and different wire protocols, it can be mapped differently. For example, it will likely be mapped to some exceptions in Java, but more likely mapped to some error codes in C. # Other uses The error model and the `Status` message can be used in a variety of environments - either with or without APIs - to provide consistent developer experience across different environments. Example uses of this error model include: - Partial errors. If a service needs to return partial errors to the client, it may embed the `Status` in the normal response to indicate the partial errors. - Workflow errors. A typical workflow has multiple steps. Each step may have a `Status` message for error reporting purpose. - Batch operations. If a client uses batch request and batch response, the `Status` message should be used directly inside batch response, one for each error sub-response. - Asynchronous operations. If an API call embeds asynchronous operation results in its response, the status of those operations should be represented directly using the `Status` message. - Logging. If some API errors are stored in logs, the message `Status` could be used directly after any stripping needed for security/privacy reasons. +/// The `Status` type defines a logical error model that is suitable for different programming environments, including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). The error model is designed to be: - Simple to use and understand for most users - Flexible enough to meet unexpected needs # Overview The `Status` message contains three pieces of data: error code, error message, and error details. The error code should be an enum value of google.rpc.Code, but it may accept additional error codes if needed. The error message should be a developer-facing English message that helps developers *understand* and *resolve* the error. If a localized user-facing error message is needed, put the localized message in the error details or localize it in the client. The optional error details may contain arbitrary information about the error. There is a predefined set of error detail types in the package `google.rpc` which can be used for common error conditions. # Language mapping The `Status` message is the logical representation of the error model, but it is not necessarily the actual wire format. When the `Status` message is exposed in different client libraries and different wire protocols, it can be mapped differently. For example, it will likely be mapped to some exceptions in Java, but more likely mapped to some error codes in C. # Other uses The error model and the `Status` message can be used in a variety of environments, either with or without APIs, to provide a consistent developer experience across different environments. Example uses of this error model include: - Partial errors. If a service needs to return partial errors to the client, it may embed the `Status` in the normal response to indicate the partial errors. - Workflow errors. A typical workflow has multiple steps. Each step may have a `Status` message for error reporting purpose. - Batch operations. If a client uses batch request and batch response, the `Status` message should be used directly inside batch response, one for each error sub-response. - Asynchronous operations. If an API call embeds asynchronous operation results in its response, the status of those operations should be represented directly using the `Status` message. - Logging. If some API errors are stored in logs, the message `Status` could be used directly after any stripping needed for security/privacy 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 Status { - /// A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the [google.rpc.Status.details][google.rpc.Status.details] field, or localized by the client. + /// A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the google.rpc.Status.details field, or localized by the client. pub message: Option, - /// The status code, which should be an enum value of [google.rpc.Code][google.rpc.Code]. + /// The status code, which should be an enum value of google.rpc.Code. pub code: Option, /// A list of messages that carry the error details. There will be a common set of message types for APIs to use. pub details: Option>>, @@ -502,7 +516,25 @@ pub struct ListCoverageBucketsResponse { impl ResponseResult for ListCoverageBucketsResponse {} -/// A read alignment describes a linear alignment of a string of DNA to a [reference sequence][google.genomics.v1.Reference], in addition to metadata about the fragment (the molecule of DNA sequenced) and the read (the bases which were read by the sequencer). A read is equivalent to a line in a SAM file. A read belongs to exactly one read group and exactly one [read group set][google.genomics.v1.ReadGroupSet]. ### Generating a reference-aligned sequence string When interacting with mapped reads, it's often useful to produce a string representing the local alignment of the read to reference. The following pseudocode demonstrates one way of doing this: out = "" offset = 0 for c in read.alignment.cigar { switch c.operation { case "ALIGNMENT_MATCH", "SEQUENCE_MATCH", "SEQUENCE_MISMATCH": out += read.alignedSequence[offset:offset+c.operationLength] offset += c.operationLength break case "CLIP_SOFT", "INSERT": offset += c.operationLength break case "PAD": out += repeat("*", c.operationLength) break case "DELETE": out += repeat("-", c.operationLength) break case "SKIP": out += repeat(" ", c.operationLength) break case "CLIP_HARD": break } } return out ### Converting to SAM's CIGAR string The following pseudocode generates a SAM CIGAR string from the `cigar` field. Note that this is a lossy conversion (`cigar.referenceSequence` is lost). cigarMap = { "ALIGNMENT_MATCH": "M", "INSERT": "I", "DELETE": "D", "SKIP": "N", "CLIP_SOFT": "S", "CLIP_HARD": "H", "PAD": "P", "SEQUENCE_MATCH": "=", "SEQUENCE_MISMATCH": "X", } cigarStr = "" for c in read.alignment.cigar { cigarStr += c.operationLength + cigarMap[c.operation] } return cigarStr +/// Response message for `TestIamPermissions` 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*). +/// +/// * [test iam permissions datasets](struct.DatasetTestIamPermissionCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct TestIamPermissionsResponse { + /// A subset of `TestPermissionsRequest.permissions` that the caller is allowed. + pub permissions: Option>, +} + +impl ResponseResult for TestIamPermissionsResponse {} + + +/// A read alignment describes a linear alignment of a string of DNA to a reference sequence, in addition to metadata about the fragment (the molecule of DNA sequenced) and the read (the bases which were read by the sequencer). A read is equivalent to a line in a SAM file. A read belongs to exactly one read group and exactly one read group set. ### Generating a reference-aligned sequence string When interacting with mapped reads, it's often useful to produce a string representing the local alignment of the read to reference. The following pseudocode demonstrates one way of doing this: out = "" offset = 0 for c in read.alignment.cigar { switch c.operation { case "ALIGNMENT_MATCH", "SEQUENCE_MATCH", "SEQUENCE_MISMATCH": out += read.alignedSequence[offset:offset+c.operationLength] offset += c.operationLength break case "CLIP_SOFT", "INSERT": offset += c.operationLength break case "PAD": out += repeat("*", c.operationLength) break case "DELETE": out += repeat("-", c.operationLength) break case "SKIP": out += repeat(" ", c.operationLength) break case "CLIP_HARD": break } } return out ### Converting to SAM's CIGAR string The following pseudocode generates a SAM CIGAR string from the `cigar` field. Note that this is a lossy conversion (`cigar.referenceSequence` is lost). cigarMap = { "ALIGNMENT_MATCH": "M", "INSERT": "I", "DELETE": "D", "SKIP": "N", "CLIP_SOFT": "S", "CLIP_HARD": "H", "PAD": "P", "SEQUENCE_MATCH": "=", "SEQUENCE_MISMATCH": "X", } cigarStr = "" for c in read.alignment.cigar { cigarStr += c.operationLength + cigarMap[c.operation] } return cigarStr /// /// # Activities /// @@ -573,12 +605,11 @@ impl Resource for Read {} /// This type is used in activities, which are methods you may call on this type or where 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 variants](struct.VariantImportCall.html) (none) +/// * [patch variants](struct.VariantPatchCall.html) (request|response) /// * [delete variants](struct.VariantDeleteCall.html) (none) /// * [create variants](struct.VariantCreateCall.html) (request|response) /// * [get variants](struct.VariantGetCall.html) (response) -/// * [patch variants](struct.VariantPatchCall.html) (request|response) -/// * [merge variants](struct.VariantMergeCall.html) (none) +/// * [import variants](struct.VariantImportCall.html) (none) /// * [search variants](struct.VariantSearchCall.html) (none) /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] @@ -620,25 +651,34 @@ impl Resource for Variant {} impl ResponseResult for Variant {} -/// The variant search response. +/// The variant data export 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*). /// -/// * [search variants](struct.VariantSearchCall.html) (response) +/// * [export variantsets](struct.VariantsetExportCall.html) (request) /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] -pub struct SearchVariantsResponse { - /// 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. This field will be empty if there aren't any additional results. - #[serde(rename="nextPageToken")] - pub next_page_token: Option, - /// The list of matching Variants. - pub variants: Option>, +pub struct ExportVariantSetRequest { + /// Required. The Google Cloud project ID that owns the destination BigQuery dataset. The caller must have WRITE access to this project. This project will also own the resulting export job. + #[serde(rename="projectId")] + pub project_id: Option, + /// The format for the exported data. + pub format: Option, + /// Required. The BigQuery dataset to export data to. This dataset must already exist. Note that this is distinct from the Genomics concept of "dataset". + #[serde(rename="bigqueryDataset")] + pub bigquery_dataset: Option, + /// If provided, only variant call information from the specified call sets will be exported. By default all variant calls are exported. + #[serde(rename="callSetIds")] + pub call_set_ids: Option>, + /// Required. The BigQuery table to export data to. If the table doesn't exist, it will be created. If it already exists, it will be overwritten. + #[serde(rename="bigqueryTable")] + pub bigquery_table: Option, } -impl ResponseResult for SearchVariantsResponse {} +impl RequestValue for ExportVariantSetRequest {} /// There is no detailed description. @@ -663,6 +703,59 @@ pub struct SearchReferenceSetsResponse { impl ResponseResult for SearchReferenceSetsResponse {} +/// Request message for `GetIamPolicy` 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*). +/// +/// * [get iam policy datasets](struct.DatasetGetIamPolicyCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct GetIamPolicyRequest; + +impl RequestValue for GetIamPolicyRequest {} + + +/// A reference set is a set of references which typically comprise a reference assembly for a species, such as `GRCh38` which is representative of the human genome. A reference set defines a common coordinate space for comparing reference-aligned experimental data. A reference set contains 1 or more references. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where 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 referencesets](struct.ReferencesetGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ReferenceSet { + /// Free text description of this reference set. + pub description: Option, + /// The URI from which the references were obtained. + #[serde(rename="sourceUri")] + pub source_uri: Option, + /// The IDs of the reference objects that are part of this set. `Reference.md5checksum` must be unique within this set. + #[serde(rename="referenceIds")] + pub reference_ids: Option>, + /// Public id of this reference set, such as `GRCh37`. + #[serde(rename="assemblyId")] + pub assembly_id: Option, + /// All known corresponding accession IDs in INSDC (GenBank/ENA/DDBJ) ideally with a version number, for example `NC_000001.11`. + #[serde(rename="sourceAccessions")] + pub source_accessions: Option>, + /// ID from http://www.ncbi.nlm.nih.gov/taxonomy (e.g. 9606->human) indicating the species which this assembly is intended to model. Note that contained references may specify a different `ncbiTaxonId`, as assemblies may contain reference sequences which do not belong to the modeled species, e.g. EBV in a human reference genome. + #[serde(rename="ncbiTaxonId")] + pub ncbi_taxon_id: Option, + /// The server-generated reference set ID, unique across all reference sets. + pub id: Option, + /// Order-independent MD5 checksum which identifies this reference set. The checksum is computed by sorting all lower case hexidecimal string `reference.md5checksum` (for all reference in this set) in ascending lexicographic order, concatenating, and taking the MD5 of that value. The resulting value is represented in lower case hexadecimal format. + pub md5checksum: Option, +} + +impl Resource for ReferenceSet {} +impl ResponseResult for ReferenceSet {} + + /// A variant set is a collection of call sets and variants. It contains summary statistics of those contents. A variant set belongs to a dataset. /// /// # Activities @@ -693,25 +786,44 @@ impl Resource for VariantSet {} impl ResponseResult for VariantSet {} -/// There is no detailed description. +/// The variant search 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*). /// -/// * [merge variants](struct.VariantMergeCall.html) (request) +/// * [search variants](struct.VariantSearchCall.html) (response) /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] -pub struct MergeVariantsRequest { - /// The destination variant set. - #[serde(rename="variantSetId")] - pub variant_set_id: Option, - /// The variants to be merged with existing variants. +pub struct SearchVariantsResponse { + /// 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. This field will be empty if there aren't any additional results. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// The list of matching Variants. pub variants: Option>, } -impl RequestValue for MergeVariantsRequest {} +impl ResponseResult for SearchVariantsResponse {} + + +/// A single CIGAR operation. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct CigarUnit { + /// `referenceSequence` is only used at mismatches (`SEQUENCE_MISMATCH`) and deletions (`DELETE`). Filling this field replaces SAM's MD tag. If the relevant information is not available, this field is unset. + #[serde(rename="referenceSequence")] + pub reference_sequence: Option, + /// no description provided + pub operation: Option, + /// The number of genomic bases that the operation runs for. Required. + #[serde(rename="operationLength")] + pub operation_length: Option, +} + +impl Part for CigarUnit {} /// Metadata describes a single piece of variant call metadata. These data include a top level key and either a single value string (value) or a list of key-value pairs (info.) Value and info are mutually exclusive. @@ -730,7 +842,7 @@ pub struct VariantSetMetadata { #[serde(rename="type")] pub type_: Option, /// The number of values that can be included in a field described by this metadata. - pub number: Option, + pub number: Option, /// The value field for simple metadata pub value: Option, /// User-provided ID field, not enforced by this API. Two or more pieces of structured metadata with identical id and key fields are considered equivalent. @@ -740,57 +852,44 @@ pub struct VariantSetMetadata { impl Part for VariantSetMetadata {} -/// The read search request. +/// The read group set search 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*). /// -/// * [search reads](struct.ReadSearchCall.html) (request) +/// * [search readgroupsets](struct.ReadgroupsetSearchCall.html) (response) /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] -pub struct SearchReadsRequest { - /// The start position of the range on the reference, 0-based inclusive. If specified, `referenceName` must also be specified. - pub start: Option, - /// The IDs of the read groups sets within which to search for reads. All specified read group sets must be aligned against a common set of reference sequences; this defines the genomic coordinates for the query. Must specify one of `readGroupSetIds` or `readGroupIds`. - #[serde(rename="readGroupSetIds")] - pub read_group_set_ids: Option>, - /// The IDs of the read groups within which to search for reads. All specified read groups must belong to the same read group sets. Must specify one of `readGroupSetIds` or `readGroupIds`. - #[serde(rename="readGroupIds")] - pub read_group_ids: Option>, - /// Specifies number of results to return in a single page. If unspecified, it will default to 256. The maximum value is 2048. - #[serde(rename="pageSize")] - pub page_size: Option, - /// 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. - #[serde(rename="pageToken")] - pub page_token: Option, - /// The end position of the range on the reference, 0-based exclusive. If specified, `referenceName` must also be specified. - pub end: Option, - /// The reference sequence name, for example `chr1`, `1`, or `chrX`. If set to *, only unmapped reads are returned. - #[serde(rename="referenceName")] - pub reference_name: Option, +pub struct SearchReadGroupSetsResponse { + /// 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. This field will be empty if there aren't any additional results. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// The list of matching read group sets. + #[serde(rename="readGroupSets")] + pub read_group_sets: Option>, } -impl RequestValue for SearchReadsRequest {} +impl ResponseResult for SearchReadGroupSetsResponse {} -/// A 0-based half-open genomic coordinate range for search requests. +/// Request message for `TestIamPermissions` method. /// -/// This type is not used in any activity, and only used as *part* of another schema. +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [test iam permissions datasets](struct.DatasetTestIamPermissionCall.html) (request) /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] -pub struct Range { - /// The start position of the range on the reference, 0-based inclusive. - pub start: Option, - /// The end position of the range on the reference, 0-based exclusive. - pub end: Option, - /// The reference sequence name, for example `chr1`, `1`, or `chrX`. - #[serde(rename="referenceName")] - pub reference_name: Option, +pub struct TestIamPermissionsRequest { + /// REQUIRED: The set of permissions to check for the 'resource'. Permissions with wildcards (such as '*' or 'storage.*') are not allowed. Allowed permissions are: * `genomics.datasets.create` * `genomics.datasets.delete` * `genomics.datasets.get` * `genomics.datasets.list` * `genomics.datasets.update` * `genomics.datasets.getIamPolicy` * `genomics.datasets.setIamPolicy` + pub permissions: Option>, } -impl Part for Range {} +impl RequestValue for TestIamPermissionsRequest {} /// The search variant sets response. @@ -845,7 +944,7 @@ impl RequestValue for UndeleteDatasetRequest {} pub struct CallSet { /// A map of additional call set information. This must be of the form map (string key mapping to a list of string values). pub info: Option>>, - /// The IDs of the variant sets this call set belongs to. + /// The IDs of the variant sets this call set belongs to. This field must have exactly length one, as a call set belongs to a single variant set. This field is repeated for compatibility with the [GA4GH 0.5.1 API](https://github.com/ga4gh/schemas/blob/v0.5.1/src/main/resources/avro/variants.avdl#L76). #[serde(rename="variantSetIds")] pub variant_set_ids: Option>, /// The call set name. @@ -931,38 +1030,20 @@ pub struct SearchCallSetsRequest { impl RequestValue for SearchCallSetsRequest {} -/// This resource represents a long-running operation that is the result of a network API call. +/// A bucket over which read coverage has been precomputed. A bucket corresponds to a specific range of the reference sequence. /// -/// # Activities -/// -/// This type is used in activities, which are methods you may call on this type or where 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 operations](struct.OperationDeleteCall.html) (none) -/// * [cancel operations](struct.OperationCancelCall.html) (none) -/// * [export variantsets](struct.VariantsetExportCall.html) (response) -/// * [export readgroupsets](struct.ReadgroupsetExportCall.html) (response) -/// * [import variants](struct.VariantImportCall.html) (response) -/// * [import readgroupsets](struct.ReadgroupsetImportCall.html) (response) -/// * [get operations](struct.OperationGetCall.html) (response) -/// * [list operations](struct.OperationListCall.html) (none) +/// This type is not used in any activity, and only used as *part* of another schema. /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] -pub struct Operation { - /// An [OperationMetadata][google.genomics.v1.OperationMetadata] object. This will always be returned with the [Operation][google.longrunning.Operation]. - pub metadata: Option>, - /// If the value is `false`, it means the operation is still in progress. If true, the operation is completed and the `result` is available. - pub done: Option, - /// If importing [ReadGroupSets][google.genomics.v1.ReadGroupSet], an [ImportReadGroupSetsResponse][google.genomics.v1.ImportReadGroupSetsResponse] is returned. If importing [Variants][google.genomics.v1.Variant], an [ImportVariantsResponse][google.genomics.v1.ImportVariantsResponse] is returned. For exports, an empty response is returned. - pub response: Option>, - /// The server-assigned name, which is only unique within the same service that originally returns it. For example: `operations/CJHU7Oi_ChDrveSpBRjfuL-qzoWAgEw` - pub name: Option, - /// The error result of the operation in case of failure. - pub error: Option, +pub struct CoverageBucket { + /// The average number of reads which are aligned to each individual reference base in this bucket. + #[serde(rename="meanCoverage")] + pub mean_coverage: Option, + /// The genomic coordinate range spanned by this bucket. + pub range: Option, } -impl Resource for Operation {} -impl ResponseResult for Operation {} +impl Part for CoverageBucket {} /// The dataset list response. @@ -1036,7 +1117,7 @@ pub struct ImportReadGroupSetsRequest { /// The reference set to which the imported read group sets are aligned to, if any. The reference names of this reference set must be a superset of those found in the imported file headers. If no reference set id is provided, a best effort is made to associate with a matching reference set. #[serde(rename="referenceSetId")] pub reference_set_id: Option, - /// A list of URIs pointing at BAM files in Google Cloud Storage. + /// A list of URIs pointing at [BAM files](https://samtools.github.io/hts-specs/SAMv1.pdf) in Google Cloud Storage. #[serde(rename="sourceUris")] pub source_uris: Option>, /// The partition strategy describes how read groups are partitioned into read group sets. @@ -1050,7 +1131,7 @@ pub struct ImportReadGroupSetsRequest { impl RequestValue for ImportReadGroupSetsRequest {} -/// The response message for [Operations.ListOperations][google.longrunning.Operations.ListOperations]. +/// The response message for Operations.ListOperations. /// /// # Activities /// @@ -1125,36 +1206,6 @@ pub struct LinearAlignment { impl Part for LinearAlignment {} -/// The variant data export 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*). -/// -/// * [export variantsets](struct.VariantsetExportCall.html) (request) -/// -#[derive(Default, Clone, Debug, Serialize, Deserialize)] -pub struct ExportVariantSetRequest { - /// Required. The Google Cloud project ID that owns the destination BigQuery dataset. The caller must have WRITE access to this project. This project will also own the resulting export job. - #[serde(rename="projectId")] - pub project_id: Option, - /// The format for the exported data. - pub format: Option, - /// Required. The BigQuery dataset to export data to. This dataset must already exist. Note that this is distinct from the Genomics concept of "dataset". - #[serde(rename="bigqueryDataset")] - pub bigquery_dataset: Option, - /// If provided, only variant call information from the specified call sets will be exported. By default all variant calls are exported. - #[serde(rename="callSetIds")] - pub call_set_ids: Option>, - /// Required. The BigQuery table to export data to. If the table doesn't exist, it will be created. If it already exists, it will be overwritten. - #[serde(rename="bigqueryTable")] - pub bigquery_table: Option, -} - -impl RequestValue for ExportVariantSetRequest {} - - /// A call represents the determination of genotype with respect to a particular variant. It may include associated information such as quality and phasing. For example, a call might assign a probability of 0.32 to the occurrence of a SNP named rs1234 in a call set with the name NA12345. /// /// This type is not used in any activity, and only used as *part* of another schema. @@ -1181,23 +1232,22 @@ pub struct VariantCall { impl Part for VariantCall {} -/// A single CIGAR operation. +/// A 0-based half-open genomic coordinate range for search 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 CigarUnit { - /// `referenceSequence` is only used at mismatches (`SEQUENCE_MISMATCH`) and deletions (`DELETE`). Filling this field replaces SAM's MD tag. If the relevant information is not available, this field is unset. - #[serde(rename="referenceSequence")] - pub reference_sequence: Option, - /// no description provided - pub operation: Option, - /// The number of genomic bases that the operation runs for. Required. - #[serde(rename="operationLength")] - pub operation_length: Option, +pub struct Range { + /// The start position of the range on the reference, 0-based inclusive. + pub start: Option, + /// The end position of the range on the reference, 0-based exclusive. + pub end: Option, + /// The reference sequence name, for example `chr1`, `1`, or `chrX`. + #[serde(rename="referenceName")] + pub reference_name: Option, } -impl Part for CigarUnit {} +impl Part for Range {} /// There is no detailed description. @@ -1236,7 +1286,10 @@ impl RequestValue for SearchReferencesRequest {} /// This type is used in activities, which are methods you may call on this type or where 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 iam policy datasets](struct.DatasetSetIamPolicyCall.html) (none) /// * [delete datasets](struct.DatasetDeleteCall.html) (none) +/// * [get iam policy datasets](struct.DatasetGetIamPolicyCall.html) (none) +/// * [test iam permissions datasets](struct.DatasetTestIamPermissionCall.html) (none) /// * [get datasets](struct.DatasetGetCall.html) (response) /// * [undelete datasets](struct.DatasetUndeleteCall.html) (response) /// * [create datasets](struct.DatasetCreateCall.html) (request|response) @@ -1267,22 +1320,22 @@ impl ResponseResult for Dataset {} /// This type is not used in any activity, and only used as *part* of another schema. /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] -pub struct Program { - /// The command line used to run this program. - #[serde(rename="commandLine")] - pub command_line: Option, - /// The version of the program run. - pub version: Option, - /// The user specified locally unique ID of the program. Used along with `prevProgramId` to define an ordering between programs. - pub id: Option, - /// The name of the program. - pub name: Option, - /// The ID of the program run before this one. - #[serde(rename="prevProgramId")] - pub prev_program_id: Option, +pub struct Experiment { + /// The sequencing center used as part of this experiment. + #[serde(rename="sequencingCenter")] + pub sequencing_center: Option, + /// The library used as part of this experiment. Note: This is not an actual ID within this repository, but rather an identifier for a library which may be meaningful to some external system. + #[serde(rename="libraryId")] + pub library_id: Option, + /// The instrument model used as part of this experiment. This maps to sequencing technology in BAM. + #[serde(rename="instrumentModel")] + pub instrument_model: Option, + /// The platform unit used as part of this experiment e.g. flowcell-barcode.lane for Illumina or slide for SOLiD. Corresponds to the @RG PU field in the SAM spec. + #[serde(rename="platformUnit")] + pub platform_unit: Option, } -impl Part for Program {} +impl Part for Experiment {} /// A read group is all the data that's processed the same way by the sequencer. @@ -1320,7 +1373,7 @@ pub struct ReadGroup { impl Part for ReadGroup {} -/// The request message for [Operations.CancelOperation][google.longrunning.Operations.CancelOperation]. +/// The request message for Operations.CancelOperation. /// /// # Activities /// @@ -1335,42 +1388,80 @@ pub struct CancelOperationRequest; impl RequestValue for CancelOperationRequest {} -/// The read group set search response. +/// The read search 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*). /// -/// * [search readgroupsets](struct.ReadgroupsetSearchCall.html) (response) +/// * [search reads](struct.ReadSearchCall.html) (request) /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] -pub struct SearchReadGroupSetsResponse { - /// 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. This field will be empty if there aren't any additional results. - #[serde(rename="nextPageToken")] - pub next_page_token: Option, - /// The list of matching read group sets. - #[serde(rename="readGroupSets")] - pub read_group_sets: Option>, +pub struct SearchReadsRequest { + /// The start position of the range on the reference, 0-based inclusive. If specified, `referenceName` must also be specified. + pub start: Option, + /// The IDs of the read groups sets within which to search for reads. All specified read group sets must be aligned against a common set of reference sequences; this defines the genomic coordinates for the query. Must specify one of `readGroupSetIds` or `readGroupIds`. + #[serde(rename="readGroupSetIds")] + pub read_group_set_ids: Option>, + /// The IDs of the read groups within which to search for reads. All specified read groups must belong to the same read group sets. Must specify one of `readGroupSetIds` or `readGroupIds`. + #[serde(rename="readGroupIds")] + pub read_group_ids: Option>, + /// Specifies number of results to return in a single page. If unspecified, it will default to 256. The maximum value is 2048. + #[serde(rename="pageSize")] + pub page_size: Option, + /// 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. + #[serde(rename="pageToken")] + pub page_token: Option, + /// The end position of the range on the reference, 0-based exclusive. If specified, `referenceName` must also be specified. + pub end: Option, + /// The reference sequence name, for example `chr1`, `1`, or `chrX`. If set to *, only unmapped reads are returned. + #[serde(rename="referenceName")] + pub reference_name: Option, } -impl ResponseResult for SearchReadGroupSetsResponse {} +impl RequestValue for SearchReadsRequest {} -/// A bucket over which read coverage has been precomputed. A bucket corresponds to a specific range of the reference sequence. +/// The variant search request. /// -/// This type is not used in any activity, and only used as *part* of another schema. +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [search variants](struct.VariantSearchCall.html) (request) /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] -pub struct CoverageBucket { - /// The average number of reads which are aligned to each individual reference base in this bucket. - #[serde(rename="meanCoverage")] - pub mean_coverage: Option, - /// The genomic coordinate range spanned by this bucket. - pub range: Option, +pub struct SearchVariantsRequest { + /// The end of the window, 0-based exclusive. If unspecified or 0, defaults to the length of the reference. + pub end: Option, + /// The maximum number of variants to return. If unspecified, defaults to 5000. + #[serde(rename="pageSize")] + pub page_size: Option, + /// 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. + #[serde(rename="pageToken")] + pub page_token: Option, + /// The maximum number of calls to return. However, at least one variant will always be returned, even if it has more calls than this limit. If unspecified, defaults to 5000. + #[serde(rename="maxCalls")] + pub max_calls: Option, + /// The beginning of the window (0-based, inclusive) for which overlapping variants should be returned. If unspecified, defaults to 0. + pub start: Option, + /// Only return variant calls which belong to call sets with these ids. Leaving this blank returns all variant calls. If a variant has no calls belonging to any of these call sets, it won't be returned at all. Currently, variants with no calls from any call set will never be returned. + #[serde(rename="callSetIds")] + pub call_set_ids: Option>, + /// Only return variants which have exactly this name. + #[serde(rename="variantName")] + pub variant_name: Option, + /// Required. Only return variants in this reference sequence. + #[serde(rename="referenceName")] + pub reference_name: Option, + /// At most one variant set ID must be provided. Only variants from this variant set will be returned. If omitted, a call set id must be included in the request. + #[serde(rename="variantSetIds")] + pub variant_set_ids: Option>, } -impl Part for CoverageBucket {} +impl RequestValue for SearchVariantsRequest {} /// The call set search response. @@ -1438,7 +1529,7 @@ pub struct SearchReadsResponse { /// 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. This field will be empty if there aren't any additional results. #[serde(rename="nextPageToken")] pub next_page_token: Option, - /// The list of matching alignments sorted by mapped genomic coordinate, if any, ascending in position within the same reference. Unmapped reads, which have no position, are returned last and are further sorted in ascending lexicographic order by fragment name. + /// The list of matching alignments sorted by mapped genomic coordinate, if any, ascending in position within the same reference. Unmapped reads, which have no position, are returned contiguously and are sorted in ascending lexicographic order by fragment name. pub alignments: Option>, } @@ -1490,7 +1581,7 @@ impl<'a, C, A> OperationMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Starts asynchronous cancellation on a long-running operation. The server makes a best effort to cancel the operation, but success is not guaranteed. Clients may use [Operations.GetOperation][google.longrunning.Operations.GetOperation] or [Operations.ListOperations][google.longrunning.Operations.ListOperations] to check whether the cancellation succeeded or the operation completed despite cancellation. + /// Starts asynchronous cancellation on a long-running operation. The server makes a best effort to cancel the operation, but success is not guaranteed. Clients may use Operations.GetOperation or Operations.ListOperations to check whether the cancellation succeeded or the operation completed despite cancellation. /// /// # Arguments /// @@ -1546,7 +1637,7 @@ impl<'a, C, A> OperationMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// This method is not implemented. To cancel an operation, please use [Operations.CancelOperation][google.longrunning.Operations.CancelOperation]. + /// This method is not implemented. To cancel an operation, please use Operations.CancelOperation. /// /// # Arguments /// @@ -1587,7 +1678,7 @@ impl<'a, C, A> OperationMethods<'a, C, A> { /// ::default(), None); /// let mut hub = Genomics::new(hyper::Client::new(), auth); /// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* -/// // like `create(...)`, `delete(...)`, `get(...)`, `list(...)`, `patch(...)` and `undelete(...)` +/// // like `create(...)`, `delete(...)`, `get(...)`, `get_iam_policy(...)`, `list(...)`, `patch(...)`, `set_iam_policy(...)`, `test_iam_permissions(...)` and `undelete(...)` /// // to build up your call. /// let rb = hub.datasets(); /// # } @@ -1655,6 +1746,44 @@ impl<'a, C, A> DatasetMethods<'a, C, A> { } } + /// Create a builder to help you perform the following task: + /// + /// Sets the access control policy on the specified dataset. Replaces any existing policy. See Setting a Policy for more information. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `resource` - REQUIRED: The resource for which policy is being specified. Format is `datasets/`. + pub fn set_iam_policy(&self, request: SetIamPolicyRequest, resource: &str) -> DatasetSetIamPolicyCall<'a, C, A> { + DatasetSetIamPolicyCall { + hub: self.hub, + _request: request, + _resource: resource.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Returns permissions that a caller has on the specified resource. See Testing Permissions for more information. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `resource` - REQUIRED: The resource for which policy is being specified. Format is `datasets/`. + pub fn test_iam_permissions(&self, request: TestIamPermissionsRequest, resource: &str) -> DatasetTestIamPermissionCall<'a, C, A> { + DatasetTestIamPermissionCall { + hub: self.hub, + _request: request, + _resource: resource.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + /// Create a builder to help you perform the following task: /// /// Gets a dataset by ID. @@ -1672,6 +1801,40 @@ impl<'a, C, A> DatasetMethods<'a, C, A> { } } + /// Create a builder to help you perform the following task: + /// + /// Lists datasets within a project. + pub fn list(&self) -> DatasetListCall<'a, C, A> { + DatasetListCall { + hub: self.hub, + _project_id: Default::default(), + _page_token: Default::default(), + _page_size: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets the access control policy for the dataset. Is empty if the policy or the resource does not exist. See Getting a Policy for more information. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `resource` - REQUIRED: The resource for which policy is being specified. Format is `datasets/`. + pub fn get_iam_policy(&self, request: GetIamPolicyRequest, resource: &str) -> DatasetGetIamPolicyCall<'a, C, A> { + DatasetGetIamPolicyCall { + hub: self.hub, + _request: request, + _resource: resource.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + /// Create a builder to help you perform the following task: /// /// Updates a dataset. This method supports patch semantics. @@ -1691,21 +1854,6 @@ impl<'a, C, A> DatasetMethods<'a, C, A> { _additional_params: Default::default(), } } - - /// Create a builder to help you perform the following task: - /// - /// Lists datasets within a project. - pub fn list(&self) -> DatasetListCall<'a, C, A> { - DatasetListCall { - hub: self.hub, - _project_id: Default::default(), - _page_token: Default::default(), - _page_size: Default::default(), - _delegate: Default::default(), - _scopes: Default::default(), - _additional_params: Default::default(), - } - } } @@ -2012,7 +2160,7 @@ impl<'a, C, A> ReadgroupsetMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Exports a read group set to a BAM file in Google Cloud Storage. Note that currently there may be some differences between exported BAM files and the original BAM file at the time of import. In particular, comments in the input file header will not be preserved, some custom tags will be converted to strings, and original reference sequence order is not necessarily preserved. + /// Exports a read group set to a BAM file in Google Cloud Storage. Note that currently there may be some differences between exported BAM files and the original BAM file at the time of import. See [ImportReadGroupSets](google.genomics.v1.ReadServiceV1.ImportReadGroupSets) for caveats. /// /// # Arguments /// @@ -2031,7 +2179,7 @@ impl<'a, C, A> ReadgroupsetMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Creates read group sets by asynchronously importing the provided information. Note that currently comments in the input file header are **not** imported and some custom tags will be converted to strings, rather than preserving tag types. The caller must have WRITE permissions to the dataset. + /// Creates read group sets by asynchronously importing the provided information. The caller must have WRITE permissions to the dataset. ## Notes on [BAM](https://samtools.github.io/hts-specs/SAMv1.pdf) import - Tags will be converted to strings - tag types are not preserved - Comments (`@CO`) in the input file header will not be preserved - Original header order of references (`@SQ`) will not be preserved - Any reverse stranded unmapped reads will be reverse complemented, and their qualities (and "BQ" tag, if any) will be reversed - Unmapped reads will be stripped of positional information (reference name and position) /// /// # Arguments /// @@ -2066,6 +2214,23 @@ impl<'a, C, A> ReadgroupsetMethods<'a, C, A> { } } + /// Create a builder to help you perform the following task: + /// + /// Gets a read group set by ID. + /// + /// # Arguments + /// + /// * `readGroupSetId` - The ID of the read group set. + pub fn get(&self, read_group_set_id: &str) -> ReadgroupsetGetCall<'a, C, A> { + ReadgroupsetGetCall { + hub: self.hub, + _read_group_set_id: read_group_set_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + /// Create a builder to help you perform the following task: /// /// Lists fixed width coverage buckets for a read group set, each of which correspond to a range of a reference sequence. Each bucket summarizes coverage information across its corresponding genomic range. Coverage is defined as the number of reads which are aligned to a given base in the reference sequence. Coverage buckets are available at several precomputed bucket widths, enabling retrieval of various coverage 'zoom levels'. The caller must have READ permissions for the target read group set. @@ -2122,23 +2287,6 @@ impl<'a, C, A> ReadgroupsetMethods<'a, C, A> { _additional_params: Default::default(), } } - - /// Create a builder to help you perform the following task: - /// - /// Gets a read group set by ID. - /// - /// # Arguments - /// - /// * `readGroupSetId` - The ID of the read group set. - pub fn get(&self, read_group_set_id: &str) -> ReadgroupsetGetCall<'a, C, A> { - ReadgroupsetGetCall { - hub: self.hub, - _read_group_set_id: read_group_set_id.to_string(), - _delegate: Default::default(), - _scopes: Default::default(), - _additional_params: Default::default(), - } - } } @@ -2262,7 +2410,7 @@ impl<'a, C, A> ReferenceMethods<'a, C, A> { /// ::default(), None); /// let mut hub = Genomics::new(hyper::Client::new(), auth); /// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* -/// // like `create(...)`, `delete(...)`, `get(...)`, `import(...)`, `merge(...)`, `patch(...)` and `search(...)` +/// // like `create(...)`, `delete(...)`, `get(...)`, `import(...)`, `patch(...)` and `search(...)` /// // to build up your call. /// let rb = hub.variants(); /// # } @@ -2328,23 +2476,6 @@ impl<'a, C, A> VariantMethods<'a, C, A> { } } - /// Create a builder to help you perform the following task: - /// - /// Merges the given variants with existing variants. Each variant will be merged with an existing variant that matches its reference sequence, start, end, reference bases, and alternative bases. If no such variant exists, a new one will be created. When variants are merged, the call information from the new variant is added to the existing variant, and other fields (such as key/value pairs) are discarded. - /// - /// # Arguments - /// - /// * `request` - No description provided. - pub fn merge(&self, request: MergeVariantsRequest) -> VariantMergeCall<'a, C, A> { - VariantMergeCall { - hub: self.hub, - _request: request, - _delegate: Default::default(), - _scopes: Default::default(), - _additional_params: Default::default(), - } - } - /// Create a builder to help you perform the following task: /// /// Creates a new variant. @@ -2364,7 +2495,7 @@ impl<'a, C, A> VariantMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Creates variant data by asynchronously importing the provided information. The variants for import will be merged with any existing data and each other according to the behavior of mergeVariants. In particular, this means for merged VCF variants that have conflicting INFO fields, some data will be arbitrarily discarded. As a special case, for single-sample VCF files, QUAL and FILTER fields will be moved to the call level; these are sometimes interpreted in a call-specific context. Imported VCF headers are appended to the metadata already in a variant set. + /// Creates variant data by asynchronously importing the provided information. The variants for import will be merged with any existing variant that matches its reference sequence, start, end, reference bases, and alternative bases. If no such variant exists, a new one will be created. When variants are merged, the call information from the new variant is added to the existing variant, and other fields (such as key/value pairs) are discarded. In particular, this means for merged VCF variants that have conflicting INFO fields, some data will be arbitrarily discarded. As a special case, for single-sample VCF files, QUAL and FILTER fields will be moved to the call level; these are sometimes interpreted in a call-specific context. Imported VCF headers are appended to the metadata already in a variant set. /// /// # Arguments /// @@ -2442,7 +2573,7 @@ impl<'a, C, A> VariantsetMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Creates a new variant set. + /// Creates a new variant set. The provided variant set must have a valid `datasetId` set - all other fields are optional. Note that the `id` field will be ignored, as this is assigned by the server. /// /// # Arguments /// @@ -2556,7 +2687,7 @@ impl<'a, C, A> VariantsetMethods<'a, C, A> { // CallBuilders ### // ################# -/// Starts asynchronous cancellation on a long-running operation. The server makes a best effort to cancel the operation, but success is not guaranteed. Clients may use [Operations.GetOperation][google.longrunning.Operations.GetOperation] or [Operations.ListOperations][google.longrunning.Operations.ListOperations] to check whether the cancellation succeeded or the operation completed despite cancellation. +/// Starts asynchronous cancellation on a long-running operation. The server makes a best effort to cancel the operation, but success is not guaranteed. Clients may use Operations.GetOperation or Operations.ListOperations to check whether the cancellation succeeded or the operation completed despite cancellation. /// /// A builder for the *cancel* method supported by a *operation* resource. /// It is not used directly, but through a `OperationMethods` instance. @@ -3106,9 +3237,9 @@ impl<'a, C, A> OperationGetCall<'a, C, A> where C: BorrowMut, A: /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.operations().list("name") -/// .page_token("erat") -/// .page_size(-35) -/// .filter("sea") +/// .page_token("accusam") +/// .page_size(-8) +/// .filter("justo") /// .doit(); /// # } /// ``` @@ -3282,7 +3413,7 @@ impl<'a, C, A> OperationListCall<'a, C, A> where C: BorrowMut, A: self._name = new_value.to_string(); self } - /// The standard List page token. + /// The standard list page token. /// /// Sets the *page token* query property to the given value. pub fn page_token(mut self, new_value: &str) -> OperationListCall<'a, C, A> { @@ -3296,7 +3427,7 @@ impl<'a, C, A> OperationListCall<'a, C, A> where C: BorrowMut, A: self._page_size = Some(new_value); self } - /// A string for filtering [Operations][google.longrunning.Operation]. The following filter fields are supported: * projectId: Required. Corresponds to [OperationMetadata.projectId][google.genomics.v1.OperationMetadata.project_id]. * createTime: The time this job was created, in seconds from the [epoch](http://en.wikipedia.org/wiki/Unix_time). Can use `>=` and/or `= 1432140000` * `projectId = my-project AND createTime >= 1432140000 AND createTime <= 1432150000 AND status = RUNNING` + /// A string for filtering Operations. The following filter fields are supported: * projectId: Required. Corresponds to OperationMetadata.projectId. * createTime: The time this job was created, in seconds from the [epoch](http://en.wikipedia.org/wiki/Unix_time). Can use `>=` and/or `= 1432140000` * `projectId = my-project AND createTime >= 1432140000 AND createTime <= 1432150000 AND status = RUNNING` /// /// Sets the *filter* query property to the given value. pub fn filter(mut self, new_value: &str) -> OperationListCall<'a, C, A> { @@ -3361,7 +3492,7 @@ impl<'a, C, A> OperationListCall<'a, C, A> where C: BorrowMut, A: } -/// This method is not implemented. To cancel an operation, please use [Operations.CancelOperation][google.longrunning.Operations.CancelOperation]. +/// This method is not implemented. To cancel an operation, please use Operations.CancelOperation. /// /// A builder for the *delete* method supported by a *operation* resource. /// It is not used directly, but through a `OperationMethods` instance. @@ -4362,6 +4493,560 @@ impl<'a, C, A> DatasetUndeleteCall<'a, C, A> where C: BorrowMut, } +/// Sets the access control policy on the specified dataset. Replaces any existing policy. See Setting a Policy for more information. +/// +/// A builder for the *setIamPolicy* method supported by a *dataset* resource. +/// It is not used directly, but through a `DatasetMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_genomics1 as genomics1; +/// use genomics1::SetIamPolicyRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use genomics1::Genomics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Genomics::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req = SetIamPolicyRequest::default(); +/// +/// // You can configure optional parameters by calling 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().set_iam_policy(req, "resource") +/// .doit(); +/// # } +/// ``` +pub struct DatasetSetIamPolicyCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Genomics, + _request: SetIamPolicyRequest, + _resource: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for DatasetSetIamPolicyCall<'a, C, A> {} + +impl<'a, C, A> DatasetSetIamPolicyCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Policy)> { + use url::percent_encoding::{percent_encode, FORM_URLENCODED_ENCODE_SET}; + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "genomics.datasets.setIamPolicy", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("resource", self._resource.to_string())); + for &field in ["alt", "resource"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://genomics.googleapis.com/v1/{+resource}:setIamPolicy".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{+resource}", "resource")].iter() { + let mut replace_with = String::new(); + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = value.to_string(); + break; + } + } + if find_this.as_bytes()[1] == '+' as u8 { + replace_with = percent_encode(replace_with.as_bytes(), FORM_URLENCODED_ENCODE_SET); + } + url = url.replace(find_this, &replace_with); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["resource"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: SetIamPolicyRequest) -> DatasetSetIamPolicyCall<'a, C, A> { + self._request = new_value; + self + } + /// REQUIRED: The resource for which policy is being specified. Format is `datasets/`. + /// + /// 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. + pub fn resource(mut self, new_value: &str) -> DatasetSetIamPolicyCall<'a, C, A> { + self._resource = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DatasetSetIamPolicyCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> DatasetSetIamPolicyCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DatasetSetIamPolicyCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Returns permissions that a caller has on the specified resource. See Testing Permissions for more information. +/// +/// A builder for the *testIamPermissions* method supported by a *dataset* resource. +/// It is not used directly, but through a `DatasetMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_genomics1 as genomics1; +/// use genomics1::TestIamPermissionsRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use genomics1::Genomics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Genomics::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req = TestIamPermissionsRequest::default(); +/// +/// // You can configure optional parameters by calling 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().test_iam_permissions(req, "resource") +/// .doit(); +/// # } +/// ``` +pub struct DatasetTestIamPermissionCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Genomics, + _request: TestIamPermissionsRequest, + _resource: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for DatasetTestIamPermissionCall<'a, C, A> {} + +impl<'a, C, A> DatasetTestIamPermissionCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, TestIamPermissionsResponse)> { + use url::percent_encoding::{percent_encode, FORM_URLENCODED_ENCODE_SET}; + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "genomics.datasets.testIamPermissions", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("resource", self._resource.to_string())); + for &field in ["alt", "resource"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://genomics.googleapis.com/v1/{+resource}:testIamPermissions".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{+resource}", "resource")].iter() { + let mut replace_with = String::new(); + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = value.to_string(); + break; + } + } + if find_this.as_bytes()[1] == '+' as u8 { + replace_with = percent_encode(replace_with.as_bytes(), FORM_URLENCODED_ENCODE_SET); + } + url = url.replace(find_this, &replace_with); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["resource"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: TestIamPermissionsRequest) -> DatasetTestIamPermissionCall<'a, C, A> { + self._request = new_value; + self + } + /// REQUIRED: The resource for which policy is being specified. Format is `datasets/`. + /// + /// 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. + pub fn resource(mut self, new_value: &str) -> DatasetTestIamPermissionCall<'a, C, A> { + self._resource = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DatasetTestIamPermissionCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> DatasetTestIamPermissionCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DatasetTestIamPermissionCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + /// Gets a dataset by ID. /// /// A builder for the *get* method supported by a *dataset* resource. @@ -4604,291 +5289,6 @@ impl<'a, C, A> DatasetGetCall<'a, C, A> where C: BorrowMut, A: oa } -/// Updates a dataset. 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` instance. -/// -/// # Example -/// -/// Instantiate a resource method builder -/// -/// ```test_harness,no_run -/// # extern crate hyper; -/// # extern crate yup_oauth2 as oauth2; -/// # extern crate google_genomics1 as genomics1; -/// use genomics1::Dataset; -/// # #[test] fn egal() { -/// # use std::default::Default; -/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; -/// # use genomics1::Genomics; -/// -/// # let secret: ApplicationSecret = Default::default(); -/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, -/// # hyper::Client::new(), -/// # ::default(), None); -/// # let mut hub = Genomics::new(hyper::Client::new(), auth); -/// // As the method needs a request, you would usually fill it with the desired information -/// // into the 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(); -/// -/// // You can configure optional parameters by calling 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, "datasetId") -/// .update_mask("ea") -/// .doit(); -/// # } -/// ``` -pub struct DatasetPatchCall<'a, C, A> - where C: 'a, A: 'a { - - hub: &'a Genomics, - _request: Dataset, - _dataset_id: String, - _update_mask: Option, - _delegate: Option<&'a mut Delegate>, - _additional_params: HashMap, - _scopes: BTreeMap -} - -impl<'a, C, A> CallBuilder for DatasetPatchCall<'a, C, A> {} - -impl<'a, C, A> DatasetPatchCall<'a, C, A> where 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: "genomics.datasets.patch", - http_method: hyper::method::Method::Patch }); - let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); - params.push(("datasetId", self._dataset_id.to_string())); - if let Some(value) = self._update_mask { - params.push(("updateMask", value.to_string())); - } - for &field in ["alt", "datasetId", "updateMask"].iter() { - if self._additional_params.contains_key(field) { - dlg.finished(false); - return Err(Error::FieldClash(field)); - } - } - for (name, value) in self._additional_params.iter() { - params.push((&name, value.clone())); - } - - params.push(("alt", "json".to_string())); - - let mut url = "https://genomics.googleapis.com/v1/datasets/{datasetId}".to_string(); - if self._scopes.len() == 0 { - self._scopes.insert(Scope::CloudPlatform.as_ref().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() { - if let Some(index) = params.iter().position(|t| &t.0 == param_name) { - indices_for_removal.push(index); - } - } - for &index in indices_for_removal.iter() { - params.remove(index); - } - } - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); - let mut request_value_reader = - { - let mut value = json::value::to_value(&self._request); - remove_json_null_values(&mut value); - let mut dst = io::Cursor::new(Vec::with_capacity(128)); - json::to_writer(&mut dst, &value).unwrap(); - dst - }; - let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); - request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_token }); - request_value_reader.seek(io::SeekFrom::Start(0)).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) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()) - .header(ContentType(json_mime_type.clone())) - .header(ContentLength(request_size as u64)) - .body(&mut request_value_reader); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = { - let mut json_response = String::new(); - res.read_to_string(&mut json_response).unwrap(); - match json::from_str(&json_response) { - Ok(decoded) => (res, decoded), - Err(err) => { - dlg.response_json_decode_error(&json_response, &err); - return Err(Error::JsonDecodeError(json_response, err)); - } - } - }; - - dlg.finished(true); - return Ok(result_value) - } - } - } - } - - - /// - /// Sets the *request* property to the given value. - /// - /// Even though 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, A> { - self._request = new_value; - self - } - /// The ID of the dataset to be updated. - /// - /// 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. - pub fn dataset_id(mut self, new_value: &str) -> DatasetPatchCall<'a, C, A> { - self._dataset_id = new_value.to_string(); - self - } - /// An optional mask specifying which fields to update. At this time, the only mutable field is [name][google.genomics.v1.Dataset.name]. The only acceptable value is "name". If unspecified, all mutable fields will be updated. - /// - /// Sets the *update mask* query property to the given value. - pub fn update_mask(mut self, new_value: &str) -> DatasetPatchCall<'a, C, A> { - self._update_mask = Some(new_value.to_string()); - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> DatasetPatchCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *bearer_token* (query-string) - OAuth bearer token. - /// * *pp* (query-boolean) - Pretty-print response. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). - /// * *access_token* (query-string) - OAuth access token. - /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. - /// * *callback* (query-string) - JSONP - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). - /// * *alt* (query-string) - Data format for response. - /// * *$.xgafv* (query-string) - V1 error format. - pub fn param(mut self, name: T, value: T) -> DatasetPatchCall<'a, C, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::CloudPlatform`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing 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, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().to_string(), ()); - self - } -} - - /// Lists datasets within a project. /// /// A builder for the *list* method supported by a *dataset* resource. @@ -4916,9 +5316,9 @@ impl<'a, C, A> DatasetPatchCall<'a, C, A> where C: BorrowMut, A: /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.datasets().list() -/// .project_id("no") -/// .page_token("justo") -/// .page_size(-21) +/// .project_id("gubergren") +/// .page_token("sadipscing") +/// .page_size(-31) /// .doit(); /// # } /// ``` @@ -5134,6 +5534,568 @@ impl<'a, C, A> DatasetListCall<'a, C, A> where C: BorrowMut, A: o } +/// Gets the access control policy for the dataset. Is empty if the policy or the resource does not exist. See Getting a Policy for more information. +/// +/// A builder for the *getIamPolicy* method supported by a *dataset* resource. +/// It is not used directly, but through a `DatasetMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_genomics1 as genomics1; +/// use genomics1::GetIamPolicyRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use genomics1::Genomics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Genomics::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req = GetIamPolicyRequest::default(); +/// +/// // You can configure optional parameters by calling 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_iam_policy(req, "resource") +/// .doit(); +/// # } +/// ``` +pub struct DatasetGetIamPolicyCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Genomics, + _request: GetIamPolicyRequest, + _resource: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for DatasetGetIamPolicyCall<'a, C, A> {} + +impl<'a, C, A> DatasetGetIamPolicyCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Policy)> { + use url::percent_encoding::{percent_encode, FORM_URLENCODED_ENCODE_SET}; + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "genomics.datasets.getIamPolicy", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("resource", self._resource.to_string())); + for &field in ["alt", "resource"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://genomics.googleapis.com/v1/{+resource}:getIamPolicy".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{+resource}", "resource")].iter() { + let mut replace_with = String::new(); + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = value.to_string(); + break; + } + } + if find_this.as_bytes()[1] == '+' as u8 { + replace_with = percent_encode(replace_with.as_bytes(), FORM_URLENCODED_ENCODE_SET); + } + url = url.replace(find_this, &replace_with); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["resource"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: GetIamPolicyRequest) -> DatasetGetIamPolicyCall<'a, C, A> { + self._request = new_value; + self + } + /// REQUIRED: The resource for which policy is being specified. Format is `datasets/`. + /// + /// 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. + pub fn resource(mut self, new_value: &str) -> DatasetGetIamPolicyCall<'a, C, A> { + self._resource = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DatasetGetIamPolicyCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> DatasetGetIamPolicyCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> DatasetGetIamPolicyCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Updates a dataset. 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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_genomics1 as genomics1; +/// use genomics1::Dataset; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use genomics1::Genomics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Genomics::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the 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(); +/// +/// // You can configure optional parameters by calling 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, "datasetId") +/// .update_mask("justo") +/// .doit(); +/// # } +/// ``` +pub struct DatasetPatchCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Genomics, + _request: Dataset, + _dataset_id: String, + _update_mask: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for DatasetPatchCall<'a, C, A> {} + +impl<'a, C, A> DatasetPatchCall<'a, C, A> where 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: "genomics.datasets.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("datasetId", self._dataset_id.to_string())); + if let Some(value) = self._update_mask { + params.push(("updateMask", value.to_string())); + } + for &field in ["alt", "datasetId", "updateMask"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://genomics.googleapis.com/v1/datasets/{datasetId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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, A> { + self._request = new_value; + self + } + /// The ID of the dataset to be updated. + /// + /// 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. + pub fn dataset_id(mut self, new_value: &str) -> DatasetPatchCall<'a, C, A> { + self._dataset_id = new_value.to_string(); + self + } + /// An optional mask specifying which fields to update. At this time, the only mutable field is name. The only acceptable value is "name". If unspecified, all mutable fields will be updated. + /// + /// Sets the *update mask* query property to the given value. + pub fn update_mask(mut self, new_value: &str) -> DatasetPatchCall<'a, C, A> { + self._update_mask = Some(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> DatasetPatchCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> DatasetPatchCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + /// Searches for reference sets which match the given criteria. Implements [GlobalAllianceApi.searchReferenceSets](http://ga4gh.org/documentation/api/v0.5.1/ga4gh_api.html#/schema/org.ga4gh.searchReferenceSets). /// /// A builder for the *search* method supported by a *referenceset* resource. @@ -5889,7 +6851,7 @@ impl<'a, C, A> CallsetSearchCall<'a, C, A> where C: BorrowMut, A: /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.callsets().patch(req, "callSetId") -/// .update_mask("diam") +/// .update_mask("et") /// .doit(); /// # } /// ``` @@ -6076,7 +7038,7 @@ impl<'a, C, A> CallsetPatchCall<'a, C, A> where C: BorrowMut, A: self._call_set_id = new_value.to_string(); self } - /// An optional mask specifying which fields to update. At this time, the only mutable field is [name][google.genomics.v1.CallSet.name]. The only acceptable value is "name". If unspecified, all mutable fields will be updated. + /// An optional mask specifying which fields to update. At this time, the only mutable field is name. The only acceptable value is "name". If unspecified, all mutable fields will be updated. /// /// Sets the *update mask* query property to the given value. pub fn update_mask(mut self, new_value: &str) -> CallsetPatchCall<'a, C, A> { @@ -7105,7 +8067,7 @@ impl<'a, C, A> ReadSearchCall<'a, C, A> where C: BorrowMut, A: oa } -/// Exports a read group set to a BAM file in Google Cloud Storage. Note that currently there may be some differences between exported BAM files and the original BAM file at the time of import. In particular, comments in the input file header will not be preserved, some custom tags will be converted to strings, and original reference sequence order is not necessarily preserved. +/// Exports a read group set to a BAM file in Google Cloud Storage. Note that currently there may be some differences between exported BAM files and the original BAM file at the time of import. See [ImportReadGroupSets](google.genomics.v1.ReadServiceV1.ImportReadGroupSets) for caveats. /// /// A builder for the *export* method supported by a *readgroupset* resource. /// It is not used directly, but through a `ReadgroupsetMethods` instance. @@ -7378,7 +8340,7 @@ impl<'a, C, A> ReadgroupsetExportCall<'a, C, A> where C: BorrowMut ReadgroupsetImportCall<'a, C, A> where C: BorrowMut ReadgroupsetPatchCall<'a, C, A> where C: BorrowMut self._read_group_set_id = new_value.to_string(); self } - /// An optional mask specifying which fields to update. At this time, mutable fields are [referenceSetId][google.genomics.v1.ReadGroupSet.reference_set_id] and [name][google.genomics.v1.ReadGroupSet.name]. Acceptable values are "referenceSetId" and "name". If unspecified, all mutable fields will be updated. + /// An optional mask specifying which fields to update. At this time, mutable fields are referenceSetId and name. Acceptable values are "referenceSetId" and "name". If unspecified, all mutable fields will be updated. /// /// Sets the *update mask* query property to the given value. pub fn update_mask(mut self, new_value: &str) -> ReadgroupsetPatchCall<'a, C, A> { @@ -7903,6 +8865,248 @@ impl<'a, C, A> ReadgroupsetPatchCall<'a, C, A> where C: BorrowMut } +/// Gets a read group set by ID. +/// +/// A builder for the *get* method supported by a *readgroupset* resource. +/// It is not used directly, but through a `ReadgroupsetMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_genomics1 as genomics1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use genomics1::Genomics; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Genomics::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.readgroupsets().get("readGroupSetId") +/// .doit(); +/// # } +/// ``` +pub struct ReadgroupsetGetCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Genomics, + _read_group_set_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ReadgroupsetGetCall<'a, C, A> {} + +impl<'a, C, A> ReadgroupsetGetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ReadGroupSet)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "genomics.readgroupsets.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("readGroupSetId", self._read_group_set_id.to_string())); + for &field in ["alt", "readGroupSetId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://genomics.googleapis.com/v1/readgroupsets/{readGroupSetId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{readGroupSetId}", "readGroupSetId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["readGroupSetId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The ID of the read group set. + /// + /// Sets the *read group set id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn read_group_set_id(mut self, new_value: &str) -> ReadgroupsetGetCall<'a, C, A> { + self._read_group_set_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ReadgroupsetGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> ReadgroupsetGetCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Readonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ReadgroupsetGetCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + /// Lists fixed width coverage buckets for a read group set, each of which correspond to a range of a reference sequence. Each bucket summarizes coverage information across its corresponding genomic range. Coverage is defined as the number of reads which are aligned to a given base in the reference sequence. Coverage buckets are available at several precomputed bucket widths, enabling retrieval of various coverage 'zoom levels'. The caller must have READ permissions for the target read group set. /// /// A builder for the *coveragebuckets.list* method supported by a *readgroupset* resource. @@ -8699,248 +9903,6 @@ impl<'a, C, A> ReadgroupsetSearchCall<'a, C, A> where C: BorrowMut::default(), None); -/// # let mut hub = Genomics::new(hyper::Client::new(), auth); -/// // You can configure optional parameters by calling the respective setters at will, and -/// // execute the final call using `doit()`. -/// // Values shown here are possibly random and not representative ! -/// let result = hub.readgroupsets().get("readGroupSetId") -/// .doit(); -/// # } -/// ``` -pub struct ReadgroupsetGetCall<'a, C, A> - where C: 'a, A: 'a { - - hub: &'a Genomics, - _read_group_set_id: String, - _delegate: Option<&'a mut Delegate>, - _additional_params: HashMap, - _scopes: BTreeMap -} - -impl<'a, C, A> CallBuilder for ReadgroupsetGetCall<'a, C, A> {} - -impl<'a, C, A> ReadgroupsetGetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { - - - /// Perform the operation you have build so far. - pub fn doit(mut self) -> Result<(hyper::client::Response, ReadGroupSet)> { - use std::io::{Read, Seek}; - use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; - let mut dd = DefaultDelegate; - let mut dlg: &mut Delegate = match self._delegate { - Some(d) => d, - None => &mut dd - }; - dlg.begin(MethodInfo { id: "genomics.readgroupsets.get", - http_method: hyper::method::Method::Get }); - let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); - params.push(("readGroupSetId", self._read_group_set_id.to_string())); - for &field in ["alt", "readGroupSetId"].iter() { - if self._additional_params.contains_key(field) { - dlg.finished(false); - return Err(Error::FieldClash(field)); - } - } - for (name, value) in self._additional_params.iter() { - params.push((&name, value.clone())); - } - - params.push(("alt", "json".to_string())); - - let mut url = "https://genomics.googleapis.com/v1/readgroupsets/{readGroupSetId}".to_string(); - if self._scopes.len() == 0 { - self._scopes.insert(Scope::Readonly.as_ref().to_string(), ()); - } - - for &(find_this, param_name) in [("{readGroupSetId}", "readGroupSetId")].iter() { - let mut replace_with: Option<&str> = None; - for &(name, ref value) in params.iter() { - if name == param_name { - replace_with = Some(value); - break; - } - } - url = url.replace(find_this, replace_with.expect("to find substitution value in params")); - } - { - let mut indices_for_removal: Vec = Vec::with_capacity(1); - for param_name in ["readGroupSetId"].iter() { - if let Some(index) = params.iter().position(|t| &t.0 == param_name) { - indices_for_removal.push(index); - } - } - for &index in indices_for_removal.iter() { - params.remove(index); - } - } - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_token }); - let mut req_result = { - let mut client = &mut *self.hub.client.borrow_mut(); - let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = { - let mut json_response = String::new(); - res.read_to_string(&mut json_response).unwrap(); - match json::from_str(&json_response) { - Ok(decoded) => (res, decoded), - Err(err) => { - dlg.response_json_decode_error(&json_response, &err); - return Err(Error::JsonDecodeError(json_response, err)); - } - } - }; - - dlg.finished(true); - return Ok(result_value) - } - } - } - } - - - /// The ID of the read group set. - /// - /// Sets the *read group set id* path property to the given value. - /// - /// Even though the property as already been set when instantiating this call, - /// we provide this method for API completeness. - pub fn read_group_set_id(mut self, new_value: &str) -> ReadgroupsetGetCall<'a, C, A> { - self._read_group_set_id = new_value.to_string(); - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> ReadgroupsetGetCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *bearer_token* (query-string) - OAuth bearer token. - /// * *pp* (query-boolean) - Pretty-print response. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). - /// * *access_token* (query-string) - OAuth access token. - /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. - /// * *callback* (query-string) - JSONP - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). - /// * *alt* (query-string) - Data format for response. - /// * *$.xgafv* (query-string) - V1 error format. - pub fn param(mut self, name: T, value: T) -> ReadgroupsetGetCall<'a, C, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::Readonly`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be - /// sufficient, a read-write scope will do as well. - pub fn add_scope(mut self, scope: T) -> ReadgroupsetGetCall<'a, C, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().to_string(), ()); - self - } -} - - /// Lists the bases in a reference, optionally restricted to a range. Implements [GlobalAllianceApi.getReferenceBases](https://github.com/ga4gh/schemas/blob/v0.5.1/src/main/resources/avro/referencemethods.avdl#L221). /// /// A builder for the *bases.list* method supported by a *reference* resource. @@ -8968,10 +9930,10 @@ impl<'a, C, A> ReadgroupsetGetCall<'a, C, A> where C: BorrowMut, /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.references().bases_list("referenceId") -/// .start("labore") -/// .page_token("eirmod") -/// .page_size(-33) -/// .end("invidunt") +/// .start("no") +/// .page_token("labore") +/// .page_size(-39) +/// .end("dolore") /// .doit(); /// # } /// ``` @@ -10437,246 +11399,6 @@ impl<'a, C, A> VariantGetCall<'a, C, A> where C: BorrowMut, A: oa } -/// Merges the given variants with existing variants. Each variant will be merged with an existing variant that matches its reference sequence, start, end, reference bases, and alternative bases. If no such variant exists, a new one will be created. When variants are merged, the call information from the new variant is added to the existing variant, and other fields (such as key/value pairs) are discarded. -/// -/// A builder for the *merge* method supported by a *variant* resource. -/// It is not used directly, but through a `VariantMethods` instance. -/// -/// # Example -/// -/// Instantiate a resource method builder -/// -/// ```test_harness,no_run -/// # extern crate hyper; -/// # extern crate yup_oauth2 as oauth2; -/// # extern crate google_genomics1 as genomics1; -/// use genomics1::MergeVariantsRequest; -/// # #[test] fn egal() { -/// # use std::default::Default; -/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; -/// # use genomics1::Genomics; -/// -/// # let secret: ApplicationSecret = Default::default(); -/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, -/// # hyper::Client::new(), -/// # ::default(), None); -/// # let mut hub = Genomics::new(hyper::Client::new(), auth); -/// // As the method needs a request, you would usually fill it with the desired information -/// // into the respective structure. Some of the parts shown here might not be applicable ! -/// // Values shown here are possibly random and not representative ! -/// let mut req = MergeVariantsRequest::default(); -/// -/// // You can configure optional parameters by calling the respective setters at will, and -/// // execute the final call using `doit()`. -/// // Values shown here are possibly random and not representative ! -/// let result = hub.variants().merge(req) -/// .doit(); -/// # } -/// ``` -pub struct VariantMergeCall<'a, C, A> - where C: 'a, A: 'a { - - hub: &'a Genomics, - _request: MergeVariantsRequest, - _delegate: Option<&'a mut Delegate>, - _additional_params: HashMap, - _scopes: BTreeMap -} - -impl<'a, C, A> CallBuilder for VariantMergeCall<'a, C, A> {} - -impl<'a, C, A> VariantMergeCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { - - - /// Perform the operation you have build so far. - pub fn doit(mut self) -> Result<(hyper::client::Response, Empty)> { - use std::io::{Read, Seek}; - use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; - let mut dd = DefaultDelegate; - let mut dlg: &mut Delegate = match self._delegate { - Some(d) => d, - None => &mut dd - }; - dlg.begin(MethodInfo { id: "genomics.variants.merge", - 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 Err(Error::FieldClash(field)); - } - } - for (name, value) in self._additional_params.iter() { - params.push((&name, value.clone())); - } - - params.push(("alt", "json".to_string())); - - let mut url = "https://genomics.googleapis.com/v1/variants:merge".to_string(); - if self._scopes.len() == 0 { - self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); - } - - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); - let mut request_value_reader = - { - let mut value = json::value::to_value(&self._request); - remove_json_null_values(&mut value); - let mut dst = io::Cursor::new(Vec::with_capacity(128)); - json::to_writer(&mut dst, &value).unwrap(); - dst - }; - let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); - request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_token }); - request_value_reader.seek(io::SeekFrom::Start(0)).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) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()) - .header(ContentType(json_mime_type.clone())) - .header(ContentLength(request_size as u64)) - .body(&mut request_value_reader); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = { - let mut json_response = String::new(); - res.read_to_string(&mut json_response).unwrap(); - match json::from_str(&json_response) { - Ok(decoded) => (res, decoded), - Err(err) => { - dlg.response_json_decode_error(&json_response, &err); - return Err(Error::JsonDecodeError(json_response, err)); - } - } - }; - - dlg.finished(true); - return Ok(result_value) - } - } - } - } - - - /// - /// Sets the *request* property to the given value. - /// - /// Even though the property as already been set when instantiating this call, - /// we provide this method for API completeness. - pub fn request(mut self, new_value: MergeVariantsRequest) -> VariantMergeCall<'a, C, A> { - self._request = new_value; - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> VariantMergeCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *bearer_token* (query-string) - OAuth bearer token. - /// * *pp* (query-boolean) - Pretty-print response. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). - /// * *access_token* (query-string) - OAuth access token. - /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. - /// * *callback* (query-string) - JSONP - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). - /// * *alt* (query-string) - Data format for response. - /// * *$.xgafv* (query-string) - V1 error format. - pub fn param(mut self, name: T, value: T) -> VariantMergeCall<'a, C, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::CloudPlatform`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be - /// sufficient, a read-write scope will do as well. - pub fn add_scope(mut self, scope: T) -> VariantMergeCall<'a, C, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().to_string(), ()); - self - } -} - - /// Creates a new variant. /// /// A builder for the *create* method supported by a *variant* resource. @@ -10917,7 +11639,7 @@ impl<'a, C, A> VariantCreateCall<'a, C, A> where C: BorrowMut, A: } -/// Creates variant data by asynchronously importing the provided information. The variants for import will be merged with any existing data and each other according to the behavior of mergeVariants. In particular, this means for merged VCF variants that have conflicting INFO fields, some data will be arbitrarily discarded. As a special case, for single-sample VCF files, QUAL and FILTER fields will be moved to the call level; these are sometimes interpreted in a call-specific context. Imported VCF headers are appended to the metadata already in a variant set. +/// Creates variant data by asynchronously importing the provided information. The variants for import will be merged with any existing variant that matches its reference sequence, start, end, reference bases, and alternative bases. If no such variant exists, a new one will be created. When variants are merged, the call information from the new variant is added to the existing variant, and other fields (such as key/value pairs) are discarded. In particular, this means for merged VCF variants that have conflicting INFO fields, some data will be arbitrarily discarded. As a special case, for single-sample VCF files, QUAL and FILTER fields will be moved to the call level; these are sometimes interpreted in a call-specific context. Imported VCF headers are appended to the metadata already in a variant set. /// /// A builder for the *import* method supported by a *variant* resource. /// It is not used directly, but through a `VariantMethods` instance. @@ -11190,7 +11912,7 @@ impl<'a, C, A> VariantImportCall<'a, C, A> where C: BorrowMut, A: /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.variants().patch(req, "variantId") -/// .update_mask("et") +/// .update_mask("sea") /// .doit(); /// # } /// ``` @@ -11377,7 +12099,7 @@ impl<'a, C, A> VariantPatchCall<'a, C, A> where C: BorrowMut, A: self._variant_id = new_value.to_string(); self } - /// An optional mask specifying which fields to update. At this time, mutable fields are [names][google.genomics.v1.Variant.names] and [info][google.genomics.v1.Variant.info]. Acceptable values are "names" and "info". If unspecified, all mutable fields will be updated. + /// An optional mask specifying which fields to update. At this time, mutable fields are names and info. Acceptable values are "names" and "info". If unspecified, all mutable fields will be updated. /// /// Sets the *update mask* query property to the given value. pub fn update_mask(mut self, new_value: &str) -> VariantPatchCall<'a, C, A> { @@ -11442,7 +12164,7 @@ impl<'a, C, A> VariantPatchCall<'a, C, A> where C: BorrowMut, A: } -/// Creates a new variant set. +/// Creates a new variant set. The provided variant set must have a valid `datasetId` set - all other fields are optional. Note that the `id` field will be ignored, as this is assigned by the server. /// /// A builder for the *create* method supported by a *variantset* resource. /// It is not used directly, but through a `VariantsetMethods` instance. @@ -11988,7 +12710,7 @@ impl<'a, C, A> VariantsetExportCall<'a, C, A> where C: BorrowMut, /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.variantsets().patch(req, "variantSetId") -/// .update_mask("eirmod") +/// .update_mask("et") /// .doit(); /// # } /// ``` @@ -12175,7 +12897,7 @@ impl<'a, C, A> VariantsetPatchCall<'a, C, A> where C: BorrowMut, self._variant_set_id = new_value.to_string(); self } - /// An optional mask specifying which fields to update. At this time, the only mutable field is [metadata][google.genomics.v1.VariantSet.metadata]. The only acceptable value is "metadata". If unspecified, all mutable fields will be updated. + /// An optional mask specifying which fields to update. At this time, the only mutable field is metadata. The only acceptable value is "metadata". If unspecified, all mutable fields will be updated. /// /// Sets the *update mask* query property to the given value. pub fn update_mask(mut self, new_value: &str) -> VariantsetPatchCall<'a, C, A> { diff --git a/gen/gmail1-cli/Cargo.toml b/gen/gmail1-cli/Cargo.toml index 24b54c0814..8f9957e7cf 100644 --- a/gen/gmail1-cli/Cargo.toml +++ b/gen/gmail1-cli/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-gmail1-cli" -version = "0.3.2+20150526" +version = "0.3.2+20150910" authors = ["Sebastian Thiel "] description = "A complete library to interact with gmail (protocol v1)" repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/gmail1-cli" diff --git a/gen/gmail1-cli/README.md b/gen/gmail1-cli/README.md index 3a0e8a7cbd..c230e511bc 100644 --- a/gen/gmail1-cli/README.md +++ b/gen/gmail1-cli/README.md @@ -24,7 +24,7 @@ Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/ma # Usage -This documentation was generated from the *gmail* API at revision *20150526*. The CLI is at version *0.3.2*. +This documentation was generated from the *gmail* API at revision *20150910*. The CLI is at version *0.3.2*. ```bash gmail1 [options] diff --git a/gen/gmail1-cli/mkdocs.yml b/gen/gmail1-cli/mkdocs.yml index bf63eb9ecb..fdb690e2b8 100644 --- a/gen/gmail1-cli/mkdocs.yml +++ b/gen/gmail1-cli/mkdocs.yml @@ -1,4 +1,4 @@ -site_name: gmail v0.3.2+20150526 +site_name: gmail v0.3.2+20150910 site_url: http://byron.github.io/google-apis-rs/google-gmail1-cli site_description: Write integrating applications with bcore diff --git a/gen/gmail1-cli/src/main.rs b/gen/gmail1-cli/src/main.rs index e96da8d471..8f76683ab8 100644 --- a/gen/gmail1-cli/src/main.rs +++ b/gen/gmail1-cli/src/main.rs @@ -3383,7 +3383,7 @@ fn main() { let mut app = App::new("gmail1") .author("Sebastian Thiel ") - .version("0.3.2+20150526") + .version("0.3.2+20150910") .about("The Gmail REST API.") .after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_gmail1_cli") .arg(Arg::with_name("url") diff --git a/gen/gmail1/Cargo.toml b/gen/gmail1/Cargo.toml index 1352fa1826..5a75bd3a63 100644 --- a/gen/gmail1/Cargo.toml +++ b/gen/gmail1/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-gmail1" -version = "0.1.9+20150526" +version = "0.1.9+20150910" authors = ["Sebastian Thiel "] description = "A complete library to interact with gmail (protocol v1)" repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/gmail1" diff --git a/gen/gmail1/README.md b/gen/gmail1/README.md index 0f7608e021..dde56e9fef 100644 --- a/gen/gmail1/README.md +++ b/gen/gmail1/README.md @@ -5,7 +5,7 @@ DO NOT EDIT ! --> The `google-gmail1` library allows access to all features of the *Google gmail* service. -This documentation was generated from *gmail* crate version *0.1.9+20150526*, where *20150526* is the exact revision of the *gmail:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +This documentation was generated from *gmail* crate version *0.1.9+20150910*, where *20150910* is the exact revision of the *gmail:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. Everything else about the *gmail* *v1* API can be found at the [official documentation site](https://developers.google.com/gmail/api/). diff --git a/gen/gmail1/src/lib.rs b/gen/gmail1/src/lib.rs index 284f80223f..318e884dc2 100644 --- a/gen/gmail1/src/lib.rs +++ b/gen/gmail1/src/lib.rs @@ -2,7 +2,7 @@ // This file was generated automatically from 'src/mako/api/lib.rs.mako' // DO NOT EDIT ! -//! This documentation was generated from *gmail* crate version *0.1.9+20150526*, where *20150526* is the exact revision of the *gmail:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +//! This documentation was generated from *gmail* crate version *0.1.9+20150910*, where *20150910* is the exact revision of the *gmail:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. //! //! Everything else about the *gmail* *v1* API can be found at the //! [official documentation site](https://developers.google.com/gmail/api/). diff --git a/gen/gmail1/src/lib.rs.in b/gen/gmail1/src/lib.rs.in index 904fd24bc4..944a6a5b3b 100644 --- a/gen/gmail1/src/lib.rs.in +++ b/gen/gmail1/src/lib.rs.in @@ -41,6 +41,9 @@ pub enum Scope { /// View and manage your mail Gmai, + /// Send email on your behalf + Send, + /// View and modify but not delete your email Modify, @@ -59,6 +62,7 @@ impl AsRef for Scope { match *self { Scope::Insert => "https://www.googleapis.com/auth/gmail.insert", Scope::Gmai => "https://mail.google.com/", + Scope::Send => "https://www.googleapis.com/auth/gmail.send", Scope::Modify => "https://www.googleapis.com/auth/gmail.modify", Scope::Compose => "https://www.googleapis.com/auth/gmail.compose", Scope::Label => "https://www.googleapis.com/auth/gmail.labels", @@ -1933,10 +1937,10 @@ impl<'a, C, A> UserMessageImportCall<'a, C, A> where C: BorrowMut self.doit(stream, mime_type, "simple") } /// Upload media in a resumable fashion. - /// Even if the upload fails or is interrupted, it can be resumed for a + /// Even if the upload fails or is interrupted, it can be resumed for a /// certain amount of time as the server maintains state temporarily. /// - /// The delegate will be asked for an `upload_url()`, and if not provided, will be asked to store an upload URL + /// The delegate will be asked for an `upload_url()`, and if not provided, will be asked to store an upload URL /// that was provided by the server, using `store_upload_url(...)`. The upload will be done in chunks, the delegate /// may specify the `chunk_size()` and may cancel the operation before each chunk is uploaded, using /// `cancel_chunk_upload(...)`. @@ -2626,10 +2630,10 @@ impl<'a, C, A> UserDraftCreateCall<'a, C, A> where C: BorrowMut, self.doit(stream, mime_type, "simple") } /// Upload media in a resumable fashion. - /// Even if the upload fails or is interrupted, it can be resumed for a + /// Even if the upload fails or is interrupted, it can be resumed for a /// certain amount of time as the server maintains state temporarily. /// - /// The delegate will be asked for an `upload_url()`, and if not provided, will be asked to store an upload URL + /// The delegate will be asked for an `upload_url()`, and if not provided, will be asked to store an upload URL /// that was provided by the server, using `store_upload_url(...)`. The upload will be done in chunks, the delegate /// may specify the `chunk_size()` and may cancel the operation before each chunk is uploaded, using /// `cancel_chunk_upload(...)`. @@ -4007,10 +4011,10 @@ impl<'a, C, A> UserDraftSendCall<'a, C, A> where C: BorrowMut, A: self.doit(stream, mime_type, "simple") } /// Upload media in a resumable fashion. - /// Even if the upload fails or is interrupted, it can be resumed for a + /// Even if the upload fails or is interrupted, it can be resumed for a /// certain amount of time as the server maintains state temporarily. /// - /// The delegate will be asked for an `upload_url()`, and if not provided, will be asked to store an upload URL + /// The delegate will be asked for an `upload_url()`, and if not provided, will be asked to store an upload URL /// that was provided by the server, using `store_upload_url(...)`. The upload will be done in chunks, the delegate /// may specify the `chunk_size()` and may cancel the operation before each chunk is uploaded, using /// `cancel_chunk_upload(...)`. @@ -5111,10 +5115,10 @@ impl<'a, C, A> UserDraftUpdateCall<'a, C, A> where C: BorrowMut, self.doit(stream, mime_type, "simple") } /// Upload media in a resumable fashion. - /// Even if the upload fails or is interrupted, it can be resumed for a + /// Even if the upload fails or is interrupted, it can be resumed for a /// certain amount of time as the server maintains state temporarily. /// - /// The delegate will be asked for an `upload_url()`, and if not provided, will be asked to store an upload URL + /// The delegate will be asked for an `upload_url()`, and if not provided, will be asked to store an upload URL /// that was provided by the server, using `store_upload_url(...)`. The upload will be done in chunks, the delegate /// may specify the `chunk_size()` and may cancel the operation before each chunk is uploaded, using /// `cancel_chunk_upload(...)`. @@ -8936,10 +8940,10 @@ impl<'a, C, A> UserMessageSendCall<'a, C, A> where C: BorrowMut, self.doit(stream, mime_type, "simple") } /// Upload media in a resumable fashion. - /// Even if the upload fails or is interrupted, it can be resumed for a + /// Even if the upload fails or is interrupted, it can be resumed for a /// certain amount of time as the server maintains state temporarily. /// - /// The delegate will be asked for an `upload_url()`, and if not provided, will be asked to store an upload URL + /// The delegate will be asked for an `upload_url()`, and if not provided, will be asked to store an upload URL /// that was provided by the server, using `store_upload_url(...)`. The upload will be done in chunks, the delegate /// may specify the `chunk_size()` and may cancel the operation before each chunk is uploaded, using /// `cancel_chunk_upload(...)`. @@ -10418,10 +10422,10 @@ impl<'a, C, A> UserMessageInsertCall<'a, C, A> where C: BorrowMut self.doit(stream, mime_type, "simple") } /// Upload media in a resumable fashion. - /// Even if the upload fails or is interrupted, it can be resumed for a + /// Even if the upload fails or is interrupted, it can be resumed for a /// certain amount of time as the server maintains state temporarily. /// - /// The delegate will be asked for an `upload_url()`, and if not provided, will be asked to store an upload URL + /// The delegate will be asked for an `upload_url()`, and if not provided, will be asked to store an upload URL /// that was provided by the server, using `store_upload_url(...)`. The upload will be done in chunks, the delegate /// may specify the `chunk_size()` and may cancel the operation before each chunk is uploaded, using /// `cancel_chunk_upload(...)`. diff --git a/gen/groupsmigration1/src/lib.rs.in b/gen/groupsmigration1/src/lib.rs.in index 368c64587f..57c62d177b 100644 --- a/gen/groupsmigration1/src/lib.rs.in +++ b/gen/groupsmigration1/src/lib.rs.in @@ -507,10 +507,10 @@ impl<'a, C, A> ArchiveInsertCall<'a, C, A> where C: BorrowMut, A: self.doit(stream, mime_type, "simple") } /// Upload media in a resumable fashion. - /// Even if the upload fails or is interrupted, it can be resumed for a + /// Even if the upload fails or is interrupted, it can be resumed for a /// certain amount of time as the server maintains state temporarily. /// - /// The delegate will be asked for an `upload_url()`, and if not provided, will be asked to store an upload URL + /// The delegate will be asked for an `upload_url()`, and if not provided, will be asked to store an upload URL /// that was provided by the server, using `store_upload_url(...)`. The upload will be done in chunks, the delegate /// may specify the `chunk_size()` and may cancel the operation before each chunk is uploaded, using /// `cancel_chunk_upload(...)`. diff --git a/gen/identitytoolkit3-cli/Cargo.toml b/gen/identitytoolkit3-cli/Cargo.toml index 2de142a8b9..848977c160 100644 --- a/gen/identitytoolkit3-cli/Cargo.toml +++ b/gen/identitytoolkit3-cli/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-identitytoolkit3-cli" -version = "0.3.2+20150710" +version = "0.3.2+20151008" authors = ["Sebastian Thiel "] description = "A complete library to interact with Identity Toolkit (protocol v3)" repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/identitytoolkit3-cli" diff --git a/gen/identitytoolkit3-cli/README.md b/gen/identitytoolkit3-cli/README.md index f5109023c7..06d3280e23 100644 --- a/gen/identitytoolkit3-cli/README.md +++ b/gen/identitytoolkit3-cli/README.md @@ -24,7 +24,7 @@ Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/ma # Usage -This documentation was generated from the *Identity Toolkit* API at revision *20150710*. The CLI is at version *0.3.2*. +This documentation was generated from the *Identity Toolkit* API at revision *20151008*. The CLI is at version *0.3.2*. ```bash identitytoolkit3 [options] diff --git a/gen/identitytoolkit3-cli/mkdocs.yml b/gen/identitytoolkit3-cli/mkdocs.yml index be27c14160..e88581942e 100644 --- a/gen/identitytoolkit3-cli/mkdocs.yml +++ b/gen/identitytoolkit3-cli/mkdocs.yml @@ -1,4 +1,4 @@ -site_name: Identity Toolkit v0.3.2+20150710 +site_name: Identity Toolkit v0.3.2+20151008 site_url: http://byron.github.io/google-apis-rs/google-identitytoolkit3-cli site_description: Write integrating applications with bcore diff --git a/gen/identitytoolkit3-cli/src/main.rs b/gen/identitytoolkit3-cli/src/main.rs index b365b8bdc4..e17789fc2f 100644 --- a/gen/identitytoolkit3-cli/src/main.rs +++ b/gen/identitytoolkit3-cli/src/main.rs @@ -1398,7 +1398,7 @@ fn main() { let mut app = App::new("identitytoolkit3") .author("Sebastian Thiel ") - .version("0.3.2+20150710") + .version("0.3.2+20151008") .about("Help the third party sites to implement federated login.") .after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_identitytoolkit3_cli") .arg(Arg::with_name("folder") diff --git a/gen/identitytoolkit3/Cargo.toml b/gen/identitytoolkit3/Cargo.toml index b2622ecb28..a8afa4c6b7 100644 --- a/gen/identitytoolkit3/Cargo.toml +++ b/gen/identitytoolkit3/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-identitytoolkit3" -version = "0.1.9+20150710" +version = "0.1.9+20151008" authors = ["Sebastian Thiel "] description = "A complete library to interact with Identity Toolkit (protocol v3)" repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/identitytoolkit3" diff --git a/gen/identitytoolkit3/README.md b/gen/identitytoolkit3/README.md index a387abb434..b8044dd981 100644 --- a/gen/identitytoolkit3/README.md +++ b/gen/identitytoolkit3/README.md @@ -5,7 +5,7 @@ DO NOT EDIT ! --> The `google-identitytoolkit3` library allows access to all features of the *Google Identity Toolkit* service. -This documentation was generated from *Identity Toolkit* crate version *0.1.9+20150710*, where *20150710* is the exact revision of the *identitytoolkit:v3* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +This documentation was generated from *Identity Toolkit* crate version *0.1.9+20151008*, where *20151008* is the exact revision of the *identitytoolkit:v3* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. Everything else about the *Identity Toolkit* *v3* API can be found at the [official documentation site](https://developers.google.com/identity-toolkit/v3/). diff --git a/gen/identitytoolkit3/src/lib.rs b/gen/identitytoolkit3/src/lib.rs index 576d724379..24372f7a8e 100644 --- a/gen/identitytoolkit3/src/lib.rs +++ b/gen/identitytoolkit3/src/lib.rs @@ -2,7 +2,7 @@ // This file was generated automatically from 'src/mako/api/lib.rs.mako' // DO NOT EDIT ! -//! This documentation was generated from *Identity Toolkit* crate version *0.1.9+20150710*, where *20150710* is the exact revision of the *identitytoolkit:v3* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +//! This documentation was generated from *Identity Toolkit* crate version *0.1.9+20151008*, where *20151008* is the exact revision of the *identitytoolkit:v3* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. //! //! Everything else about the *Identity Toolkit* *v3* API can be found at the //! [official documentation site](https://developers.google.com/identity-toolkit/v3/). diff --git a/gen/identitytoolkit3/src/lib.rs.in b/gen/identitytoolkit3/src/lib.rs.in index ab62c1b985..91d3793638 100644 --- a/gen/identitytoolkit3/src/lib.rs.in +++ b/gen/identitytoolkit3/src/lib.rs.in @@ -412,15 +412,17 @@ pub struct VerifyAssertionResponse { /// The URI of the public accessible profiel picture. #[serde(rename="photoUrl")] pub photo_url: Option, + /// The original email stored in the mapping storage. It's returned when the federated ID is associated to a different email. + #[serde(rename="originalEmail")] + pub original_email: Option, /// It's the identifier param in the createAuthUri request if the identifier is an email. It can be used to check whether the user input email is different from the asserted email. #[serde(rename="inputEmail")] pub input_email: Option, /// The scope for the OpenID OAuth extension. #[serde(rename="oauthScope")] pub oauth_scope: Option, - /// The value is true if the IDP is also the email provider. It means the user owns the email. - #[serde(rename="emailVerified")] - pub email_verified: Option, + /// The language preference of the user. + pub language: Option, /// Whether the assertion is from a non-trusted IDP and need account linking confirmation. #[serde(rename="needConfirmation")] pub need_confirmation: Option, @@ -438,8 +440,9 @@ pub struct VerifyAssertionResponse { /// The display name of the user. #[serde(rename="displayName")] pub display_name: Option, - /// The language preference of the user. - pub language: Option, + /// The OAuth2 access token. + #[serde(rename="oauthAccessToken")] + pub oauth_access_token: Option, /// The first name of the user. #[serde(rename="firstName")] pub first_name: Option, @@ -455,18 +458,15 @@ pub struct VerifyAssertionResponse { /// When action is 'map', contains the idps which can be used for confirmation. #[serde(rename="verifiedProvider")] pub verified_provider: Option>, - /// The OAuth2 access token. - #[serde(rename="oauthAccessToken")] - pub oauth_access_token: Option, + /// Whether need client to supply email to complete the federated login flow. + #[serde(rename="needEmail")] + pub need_email: Option, /// The user approved request token for the OpenID OAuth extension. #[serde(rename="oauthRequestToken")] pub oauth_request_token: Option, /// The birth date of the IdP account. #[serde(rename="dateOfBirth")] pub date_of_birth: Option, - /// The original email stored in the mapping storage. It's returned when the federated ID is associated to a different email. - #[serde(rename="originalEmail")] - pub original_email: Option, /// The IdP ID. For white listed IdPs it's a short domain name e.g. google.com, aol.com, live.net and yahoo.com. If the "providerId" param is set to OpenID OP identifer other than the whilte listed IdPs the OP identifier is returned. If the "identifier" param is federated ID in the createAuthUri request. The domain part of the federated ID is returned. #[serde(rename="providerId")] pub provider_id: Option, @@ -480,6 +480,9 @@ pub struct VerifyAssertionResponse { /// The timezone of the user. #[serde(rename="timeZone")] pub time_zone: Option, + /// The value is true if the IDP is also the email provider. It means the user owns the email. + #[serde(rename="emailVerified")] + pub email_verified: Option, /// The nick name of the user. #[serde(rename="nickName")] pub nick_name: Option, @@ -580,14 +583,23 @@ pub struct VerifyPasswordResponse { /// The RP local ID if it's already been mapped to the IdP account identified by the federated ID. #[serde(rename="localId")] pub local_id: Option, + /// The OAuth2 access token. + #[serde(rename="oauthAccessToken")] + pub oauth_access_token: Option, /// The URI of the user's photo at IdP #[serde(rename="photoUrl")] pub photo_url: Option, + /// The lifetime in seconds of the OAuth2 access token. + #[serde(rename="oauthExpireIn")] + pub oauth_expire_in: Option, /// The GITKit token for authenticated user. #[serde(rename="idToken")] pub id_token: Option, /// Whether the email is registered. pub registered: Option, + /// The OAuth2 authorization code. + #[serde(rename="oauthAuthorizationCode")] + pub oauth_authorization_code: Option, /// The email returned by the IdP. NOTE: The federated login user may not own the email. pub email: Option, } @@ -862,19 +874,22 @@ impl ResponseResult for GetAccountInfoResponse {} /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct SetAccountInfoResponse { - /// The Gitkit id token to login the newly sign up user. - #[serde(rename="idToken")] - pub id_token: Option, /// The fixed string "identitytoolkit#SetAccountInfoResponse". pub kind: Option, /// The name of the user. #[serde(rename="displayName")] pub display_name: Option, - /// The email of the user. - pub email: Option, + /// The new email the user attempts to change to. + #[serde(rename="newEmail")] + pub new_email: Option, /// The user's profiles at the associated IdPs. #[serde(rename="providerUserInfo")] pub provider_user_info: Option>, + /// The Gitkit id token to login the newly sign up user. + #[serde(rename="idToken")] + pub id_token: Option, + /// The email of the user. + pub email: Option, } impl ResponseResult for SetAccountInfoResponse {} diff --git a/gen/logging1_beta3-cli/Cargo.toml b/gen/logging1_beta3-cli/Cargo.toml index 7507d30071..9b4ac376cd 100644 --- a/gen/logging1_beta3-cli/Cargo.toml +++ b/gen/logging1_beta3-cli/Cargo.toml @@ -4,10 +4,11 @@ [package] name = "google-logging1_beta3-cli" -version = "0.3.2+20150326" +version = "0.3.2+20151007" authors = ["Sebastian Thiel "] description = "A complete library to interact with logging (protocol v1beta3)" repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/logging1_beta3-cli" +homepage = "https://cloud.google.com/logging/docs/" documentation = "http://byron.github.io/google-apis-rs/google_logging1_beta3_cli" license = "MIT" keywords = ["logging", "google", "cli"] diff --git a/gen/logging1_beta3-cli/README.md b/gen/logging1_beta3-cli/README.md index fdd338aa33..acadf4330e 100644 --- a/gen/logging1_beta3-cli/README.md +++ b/gen/logging1_beta3-cli/README.md @@ -10,6 +10,9 @@ capabilities. Errors will be printed to standard error, and cause the program's If data-structures are requested, these will be returned as pretty-printed JSON, to be useful as input to other tools. +Everything else about the *logging* API can be found at the +[official documentation site](https://cloud.google.com/logging/docs/). + # Downloads You can download the pre-compiled 64bit binaries for the following platforms: @@ -21,7 +24,7 @@ Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/ma # Usage -This documentation was generated from the *logging* API at revision *20150326*. The CLI is at version *0.3.2*. +This documentation was generated from the *logging* API at revision *20151007*. The CLI is at version *0.3.2*. ```bash logging1-beta3 [options] @@ -41,6 +44,16 @@ logging1-beta3 [options] logs-sinks-get [-p ]... [-o ] logs-sinks-list [-p ]... [-o ] logs-sinks-update (-r )... [-p ]... [-o ] + metrics-create (-r )... [-p ]... [-o ] + metrics-delete [-p ]... [-o ] + metrics-get [-p ]... [-o ] + metrics-list [-p ]... [-o ] + metrics-update (-r )... [-p ]... [-o ] + sinks-create (-r )... [-p ]... [-o ] + sinks-delete [-p ]... [-o ] + sinks-get [-p ]... [-o ] + sinks-list [-p ]... [-o ] + sinks-update (-r )... [-p ]... [-o ] logging1-beta3 --help Configuration: diff --git a/gen/logging1_beta3-cli/mkdocs.yml b/gen/logging1_beta3-cli/mkdocs.yml index 46f273f91c..fb316aa9ea 100644 --- a/gen/logging1_beta3-cli/mkdocs.yml +++ b/gen/logging1_beta3-cli/mkdocs.yml @@ -1,4 +1,4 @@ -site_name: logging v0.3.2+20150326 +site_name: logging v0.3.2+20151007 site_url: http://byron.github.io/google-apis-rs/google-logging1_beta3-cli site_description: Write integrating applications with bcore @@ -24,6 +24,16 @@ pages: - ['projects_logs-sinks-get.md', 'Projects', 'Logs Sinks Get'] - ['projects_logs-sinks-list.md', 'Projects', 'Logs Sinks List'] - ['projects_logs-sinks-update.md', 'Projects', 'Logs Sinks Update'] +- ['projects_metrics-create.md', 'Projects', 'Metrics Create'] +- ['projects_metrics-delete.md', 'Projects', 'Metrics Delete'] +- ['projects_metrics-get.md', 'Projects', 'Metrics Get'] +- ['projects_metrics-list.md', 'Projects', 'Metrics List'] +- ['projects_metrics-update.md', 'Projects', 'Metrics Update'] +- ['projects_sinks-create.md', 'Projects', 'Sinks Create'] +- ['projects_sinks-delete.md', 'Projects', 'Sinks Delete'] +- ['projects_sinks-get.md', 'Projects', 'Sinks Get'] +- ['projects_sinks-list.md', 'Projects', 'Sinks List'] +- ['projects_sinks-update.md', 'Projects', 'Sinks Update'] theme: readthedocs diff --git a/gen/logging1_beta3-cli/src/main.rs b/gen/logging1_beta3-cli/src/main.rs index 5a699c6e18..f1e00a4fe7 100644 --- a/gen/logging1_beta3-cli/src/main.rs +++ b/gen/logging1_beta3-cli/src/main.rs @@ -57,9 +57,6 @@ impl<'n, 'a> Engine<'n, 'a> { "page-size" => { call = call.page_size(arg_from_str(value.unwrap_or("-0"), err, "page-size", "integer")); }, - "log" => { - call = call.log(value.unwrap_or("")); - }, "index-prefix" => { call = call.index_prefix(value.unwrap_or("")); }, @@ -79,7 +76,7 @@ impl<'n, 'a> Engine<'n, 'a> { err.issues.push(CLIError::UnknownParameter(key.to_string(), {let mut v = Vec::new(); v.extend(self.gp.iter().map(|v|*v)); - v.extend(["page-token", "depth", "index-prefix", "log", "page-size"].iter().map(|v|*v)); + v.extend(["page-token", "depth", "index-prefix", "page-size"].iter().map(|v|*v)); v } )); } } @@ -125,9 +122,6 @@ impl<'n, 'a> Engine<'n, 'a> { "page-size" => { call = call.page_size(arg_from_str(value.unwrap_or("-0"), err, "page-size", "integer")); }, - "log" => { - call = call.log(value.unwrap_or("")); - }, _ => { let mut found = false; for param in &self.gp { @@ -141,7 +135,7 @@ impl<'n, 'a> Engine<'n, 'a> { err.issues.push(CLIError::UnknownParameter(key.to_string(), {let mut v = Vec::new(); v.extend(self.gp.iter().map(|v|*v)); - v.extend(["page-token", "log", "page-size"].iter().map(|v|*v)); + v.extend(["page-token", "page-size"].iter().map(|v|*v)); v } )); } } @@ -198,10 +192,11 @@ impl<'n, 'a> Engine<'n, 'a> { let type_info: Option<(&'static str, JsonTypeInfo)> = match &temp_cursor.to_string()[..] { + "filter" => Some(("filter", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "destination" => Some(("destination", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), _ => { - let suggestion = FieldCursor::did_you_mean(key, &vec!["destination", "name"]); + let suggestion = FieldCursor::did_you_mean(key, &vec!["destination", "filter", "name"]); err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); None } @@ -440,10 +435,11 @@ impl<'n, 'a> Engine<'n, 'a> { let type_info: Option<(&'static str, JsonTypeInfo)> = match &temp_cursor.to_string()[..] { + "filter" => Some(("filter", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "destination" => Some(("destination", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), _ => { - let suggestion = FieldCursor::did_you_mean(key, &vec!["destination", "name"]); + let suggestion = FieldCursor::did_you_mean(key, &vec!["destination", "filter", "name"]); err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); None } @@ -728,10 +724,11 @@ impl<'n, 'a> Engine<'n, 'a> { let type_info: Option<(&'static str, JsonTypeInfo)> = match &temp_cursor.to_string()[..] { + "filter" => Some(("filter", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "destination" => Some(("destination", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), _ => { - let suggestion = FieldCursor::did_you_mean(key, &vec!["destination", "name"]); + let suggestion = FieldCursor::did_you_mean(key, &vec!["destination", "filter", "name"]); err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); None } @@ -970,10 +967,11 @@ impl<'n, 'a> Engine<'n, 'a> { let type_info: Option<(&'static str, JsonTypeInfo)> = match &temp_cursor.to_string()[..] { + "filter" => Some(("filter", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "destination" => Some(("destination", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), _ => { - let suggestion = FieldCursor::did_you_mean(key, &vec!["destination", "name"]); + let suggestion = FieldCursor::did_you_mean(key, &vec!["destination", "filter", "name"]); err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); None } @@ -1033,6 +1031,673 @@ impl<'n, 'a> Engine<'n, 'a> { } } + fn _projects_metrics_create(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "filter" => Some(("filter", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "description" => Some(("description", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["description", "filter", "name"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::LogMetric = json::value::from_value(object).unwrap(); + let mut call = self.hub.projects().metrics_create(request, opt.value_of("projects-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _projects_metrics_delete(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.projects().metrics_delete(opt.value_of("projects-id").unwrap_or(""), opt.value_of("metrics-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _projects_metrics_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.projects().metrics_get(opt.value_of("projects-id").unwrap_or(""), opt.value_of("metrics-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _projects_metrics_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.projects().metrics_list(opt.value_of("projects-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "page-size" => { + call = call.page_size(arg_from_str(value.unwrap_or("-0"), err, "page-size", "integer")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["page-token", "page-size"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _projects_metrics_update(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "filter" => Some(("filter", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "description" => Some(("description", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["description", "filter", "name"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::LogMetric = json::value::from_value(object).unwrap(); + let mut call = self.hub.projects().metrics_update(request, opt.value_of("projects-id").unwrap_or(""), opt.value_of("metrics-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _projects_sinks_create(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "filter" => Some(("filter", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "destination" => Some(("destination", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["destination", "filter", "name"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::LogSink = json::value::from_value(object).unwrap(); + let mut call = self.hub.projects().sinks_create(request, opt.value_of("projects-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _projects_sinks_delete(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.projects().sinks_delete(opt.value_of("projects-id").unwrap_or(""), opt.value_of("sinks-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _projects_sinks_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.projects().sinks_get(opt.value_of("projects-id").unwrap_or(""), opt.value_of("sinks-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _projects_sinks_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.projects().sinks_list(opt.value_of("projects-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _projects_sinks_update(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "filter" => Some(("filter", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "destination" => Some(("destination", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["destination", "filter", "name"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::LogSink = json::value::from_value(object).unwrap(); + let mut call = self.hub.projects().sinks_update(request, opt.value_of("projects-id").unwrap_or(""), opt.value_of("sinks-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + fn _doit(&self, dry_run: bool) -> Result, Option> { let mut err = InvalidOptionsError::new(); let mut call_result: Result<(), DoitError> = Ok(()); @@ -1085,6 +1750,36 @@ impl<'n, 'a> Engine<'n, 'a> { ("logs-sinks-update", Some(opt)) => { call_result = self._projects_logs_sinks_update(opt, dry_run, &mut err); }, + ("metrics-create", Some(opt)) => { + call_result = self._projects_metrics_create(opt, dry_run, &mut err); + }, + ("metrics-delete", Some(opt)) => { + call_result = self._projects_metrics_delete(opt, dry_run, &mut err); + }, + ("metrics-get", Some(opt)) => { + call_result = self._projects_metrics_get(opt, dry_run, &mut err); + }, + ("metrics-list", Some(opt)) => { + call_result = self._projects_metrics_list(opt, dry_run, &mut err); + }, + ("metrics-update", Some(opt)) => { + call_result = self._projects_metrics_update(opt, dry_run, &mut err); + }, + ("sinks-create", Some(opt)) => { + call_result = self._projects_sinks_create(opt, dry_run, &mut err); + }, + ("sinks-delete", Some(opt)) => { + call_result = self._projects_sinks_delete(opt, dry_run, &mut err); + }, + ("sinks-get", Some(opt)) => { + call_result = self._projects_sinks_get(opt, dry_run, &mut err); + }, + ("sinks-list", Some(opt)) => { + call_result = self._projects_sinks_list(opt, dry_run, &mut err); + }, + ("sinks-update", Some(opt)) => { + call_result = self._projects_sinks_update(opt, dry_run, &mut err); + }, _ => { err.issues.push(CLIError::MissingMethodError("projects".to_string())); writeln!(io::stderr(), "{}\n", opt.usage()).ok(); @@ -1146,7 +1841,7 @@ impl<'n, 'a> Engine<'n, 'a> { let engine = Engine { opt: opt, hub: api::Logging::new(client, auth), - gp: vec!["$-xgafv", "access-token", "alt", "bearer-token", "callback", "fields", "key", "oauth-token", "pp", "pretty-print", "quota-user"], + gp: vec!["$-xgafv", "access-token", "alt", "bearer-token", "callback", "fields", "key", "oauth-token", "pp", "pretty-print", "quota-user", "upload-type", "upload-protocol"], gpm: vec![ ("$-xgafv", "$.xgafv"), ("access-token", "access_token"), @@ -1154,6 +1849,8 @@ impl<'n, 'a> Engine<'n, 'a> { ("oauth-token", "oauth_token"), ("pretty-print", "prettyPrint"), ("quota-user", "quotaUser"), + ("upload-type", "uploadType"), + ("upload-protocol", "upload_protocol"), ] }; @@ -1175,14 +1872,14 @@ impl<'n, 'a> Engine<'n, 'a> { fn main() { let mut exit_status = 0i32; let arg_data = [ - ("projects", "methods: 'log-services-indexes-list', 'log-services-list', 'log-services-sinks-create', 'log-services-sinks-delete', 'log-services-sinks-get', 'log-services-sinks-list', 'log-services-sinks-update', 'logs-delete', 'logs-entries-write', 'logs-list', 'logs-sinks-create', 'logs-sinks-delete', 'logs-sinks-get', 'logs-sinks-list' and 'logs-sinks-update'", vec![ + ("projects", "methods: 'log-services-indexes-list', 'log-services-list', 'log-services-sinks-create', 'log-services-sinks-delete', 'log-services-sinks-get', 'log-services-sinks-list', 'log-services-sinks-update', 'logs-delete', 'logs-entries-write', 'logs-list', 'logs-sinks-create', 'logs-sinks-delete', 'logs-sinks-get', 'logs-sinks-list', 'logs-sinks-update', 'metrics-create', 'metrics-delete', 'metrics-get', 'metrics-list', 'metrics-update', 'sinks-create', 'sinks-delete', 'sinks-get', 'sinks-list' and 'sinks-update'", vec![ ("log-services-indexes-list", - Some(r##"Lists log service indexes associated with a log service."##), + Some(r##"Lists the current index values for a log service."##), "Details at http://byron.github.io/google-apis-rs/google_logging1_beta3_cli/projects_log-services-indexes-list", vec![ (Some(r##"projects-id"##), None, - Some(r##"Part of `serviceName`. A log service resource of the form `/projects/*/logServices/*`. The service indexes of the log service are returned. Example: `"/projects/myProj/logServices/appengine.googleapis.com"`."##), + Some(r##"Part of `serviceName`. The resource name of a log service whose service indexes are requested. Example: `"projects/my-project-id/logServices/appengine.googleapis.com"`."##), Some(true), Some(false)), @@ -1205,12 +1902,12 @@ fn main() { Some(false)), ]), ("log-services-list", - Some(r##"Lists log services associated with log entries ingested for a project."##), + Some(r##"Lists the log services that have log entries in this project."##), "Details at http://byron.github.io/google-apis-rs/google_logging1_beta3_cli/projects_log-services-list", vec![ (Some(r##"projects-id"##), None, - Some(r##"Part of `projectName`. The project resource whose services are to be listed."##), + Some(r##"Part of `projectName`. The resource name of the project whose services are to be listed."##), Some(true), Some(false)), @@ -1227,12 +1924,12 @@ fn main() { Some(false)), ]), ("log-services-sinks-create", - Some(r##"Creates the specified log service sink resource."##), + Some(r##"Creates a log service sink. All log entries from a specified log service are written to the destination."##), "Details at http://byron.github.io/google-apis-rs/google_logging1_beta3_cli/projects_log-services-sinks-create", vec![ (Some(r##"projects-id"##), None, - Some(r##"Part of `serviceName`. The name of the service in which to create a sink."##), + Some(r##"Part of `serviceName`. The resource name of the log service to which the sink is bound."##), Some(true), Some(false)), @@ -1261,12 +1958,12 @@ fn main() { Some(false)), ]), ("log-services-sinks-delete", - Some(r##"Deletes the specified log service sink."##), + Some(r##"Deletes a log service sink. After deletion, no new log entries are written to the destination."##), "Details at http://byron.github.io/google-apis-rs/google_logging1_beta3_cli/projects_log-services-sinks-delete", vec![ (Some(r##"projects-id"##), None, - Some(r##"Part of `sinkName`. The name of the sink to delete."##), + Some(r##"Part of `sinkName`. The resource name of the log service sink to delete."##), Some(true), Some(false)), @@ -1295,12 +1992,12 @@ fn main() { Some(false)), ]), ("log-services-sinks-get", - Some(r##"Gets the specified log service sink resource."##), + Some(r##"Gets a log service sink."##), "Details at http://byron.github.io/google-apis-rs/google_logging1_beta3_cli/projects_log-services-sinks-get", vec![ (Some(r##"projects-id"##), None, - Some(r##"Part of `sinkName`. The name of the sink to return."##), + Some(r##"Part of `sinkName`. The resource name of the log service sink to return."##), Some(true), Some(false)), @@ -1329,12 +2026,12 @@ fn main() { Some(false)), ]), ("log-services-sinks-list", - Some(r##"Lists log service sinks associated with the specified service."##), + Some(r##"Lists log service sinks associated with a log service."##), "Details at http://byron.github.io/google-apis-rs/google_logging1_beta3_cli/projects_log-services-sinks-list", vec![ (Some(r##"projects-id"##), None, - Some(r##"Part of `serviceName`. The name of the service for which to list sinks."##), + Some(r##"Part of `serviceName`. The log service whose sinks are wanted."##), Some(true), Some(false)), @@ -1357,12 +2054,12 @@ fn main() { Some(false)), ]), ("log-services-sinks-update", - Some(r##"Creates or update the specified log service sink resource."##), + Some(r##"Updates a log service sink. If the sink does not exist, it is created."##), "Details at http://byron.github.io/google-apis-rs/google_logging1_beta3_cli/projects_log-services-sinks-update", vec![ (Some(r##"projects-id"##), None, - Some(r##"Part of `sinkName`. The name of the sink to update."##), + Some(r##"Part of `sinkName`. The resource name of the log service sink to update."##), Some(true), Some(false)), @@ -1397,12 +2094,12 @@ fn main() { Some(false)), ]), ("logs-delete", - Some(r##"Deletes the specified log resource and all log entries contained in it."##), + Some(r##"Deletes a log and all its log entries. The log will reappear if it receives new entries."##), "Details at http://byron.github.io/google-apis-rs/google_logging1_beta3_cli/projects_logs-delete", vec![ (Some(r##"projects-id"##), None, - Some(r##"Part of `logName`. The log resource to delete."##), + Some(r##"Part of `logName`. The resource name of the log to be deleted."##), Some(true), Some(false)), @@ -1425,12 +2122,12 @@ fn main() { Some(false)), ]), ("logs-entries-write", - Some(r##"Creates one or more log entries in a log. You must supply a list of `LogEntry` objects, named `entries`. Each `LogEntry` object must contain a payload object and a `LogEntryMetadata` object that describes the entry. You must fill in all the fields of the entry, metadata, and payload. You can also supply a map, `commonLabels`, that supplies default (key, value) data for the `entries[].metadata.labels` maps, saving you the trouble of creating identical copies for each entry."##), + Some(r##"Writes log entries to Cloud Logging. Each entry consists of a `LogEntry` object. You must fill in all the fields of the object, including one of the payload fields. You may supply a map, `commonLabels`, that holds default (key, value) data for the `entries[].metadata.labels` map in each entry, saving you the trouble of creating identical copies for each entry."##), "Details at http://byron.github.io/google-apis-rs/google_logging1_beta3_cli/projects_logs-entries-write", vec![ (Some(r##"projects-id"##), None, - Some(r##"Part of `logName`. The name of the log resource into which to insert the log entries."##), + Some(r##"Part of `logName`. The resource name of the log that will receive the log entries."##), Some(true), Some(false)), @@ -1459,12 +2156,12 @@ fn main() { Some(false)), ]), ("logs-list", - Some(r##"Lists log resources belonging to the specified project."##), + Some(r##"Lists the logs in the project. Only logs that have entries are listed."##), "Details at http://byron.github.io/google-apis-rs/google_logging1_beta3_cli/projects_logs-list", vec![ (Some(r##"projects-id"##), None, - Some(r##"Part of `projectName`. The project name for which to list the log resources."##), + Some(r##"Part of `projectName`. The resource name of the project whose logs are requested. If both `serviceName` and `serviceIndexPrefix` are empty, then all logs with entries in this project are listed."##), Some(true), Some(false)), @@ -1481,12 +2178,12 @@ fn main() { Some(false)), ]), ("logs-sinks-create", - Some(r##"Creates the specified log sink resource."##), + Some(r##"Creates a log sink. All log entries for a specified log are written to the destination."##), "Details at http://byron.github.io/google-apis-rs/google_logging1_beta3_cli/projects_logs-sinks-create", vec![ (Some(r##"projects-id"##), None, - Some(r##"Part of `logName`. The log in which to create a sink resource."##), + Some(r##"Part of `logName`. The resource name of the log to which to the sink is bound."##), Some(true), Some(false)), @@ -1515,12 +2212,12 @@ fn main() { Some(false)), ]), ("logs-sinks-delete", - Some(r##"Deletes the specified log sink resource."##), + Some(r##"Deletes a log sink. After deletion, no new log entries are written to the destination."##), "Details at http://byron.github.io/google-apis-rs/google_logging1_beta3_cli/projects_logs-sinks-delete", vec![ (Some(r##"projects-id"##), None, - Some(r##"Part of `sinkName`. The name of the sink to delete."##), + Some(r##"Part of `sinkName`. The resource name of the log sink to delete."##), Some(true), Some(false)), @@ -1549,12 +2246,12 @@ fn main() { Some(false)), ]), ("logs-sinks-get", - Some(r##"Gets the specified log sink resource."##), + Some(r##"Gets a log sink."##), "Details at http://byron.github.io/google-apis-rs/google_logging1_beta3_cli/projects_logs-sinks-get", vec![ (Some(r##"projects-id"##), None, - Some(r##"Part of `sinkName`. The name of the sink resource to return."##), + Some(r##"Part of `sinkName`. The resource name of the log sink to return."##), Some(true), Some(false)), @@ -1583,12 +2280,12 @@ fn main() { Some(false)), ]), ("logs-sinks-list", - Some(r##"Lists log sinks associated with the specified log."##), + Some(r##"Lists log sinks associated with a log."##), "Details at http://byron.github.io/google-apis-rs/google_logging1_beta3_cli/projects_logs-sinks-list", vec![ (Some(r##"projects-id"##), None, - Some(r##"Part of `logName`. The log for which to list sinks."##), + Some(r##"Part of `logName`. The log whose sinks are wanted. For example, `"compute.google.com/syslog"`."##), Some(true), Some(false)), @@ -1611,12 +2308,12 @@ fn main() { Some(false)), ]), ("logs-sinks-update", - Some(r##"Creates or updates the specified log sink resource."##), + Some(r##"Updates a log sink. If the sink does not exist, it is created."##), "Details at http://byron.github.io/google-apis-rs/google_logging1_beta3_cli/projects_logs-sinks-update", vec![ (Some(r##"projects-id"##), None, - Some(r##"Part of `sinkName`. The name of the sink to update."##), + Some(r##"Part of `sinkName`. The resource name of the sink to update."##), Some(true), Some(false)), @@ -1644,6 +2341,286 @@ fn main() { Some(false), Some(true)), + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("metrics-create", + Some(r##"Create the specified log metric resource."##), + "Details at http://byron.github.io/google-apis-rs/google_logging1_beta3_cli/projects_metrics-create", + vec![ + (Some(r##"projects-id"##), + None, + Some(r##"Part of `projectName`. The resource name of the project in which to create the metric."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("metrics-delete", + Some(r##"Deletes the specified log metric."##), + "Details at http://byron.github.io/google-apis-rs/google_logging1_beta3_cli/projects_metrics-delete", + vec![ + (Some(r##"projects-id"##), + None, + Some(r##"Part of `metricName`. The resource name of the metric to delete."##), + Some(true), + Some(false)), + + (Some(r##"metrics-id"##), + None, + Some(r##"Part of `metricName`. See documentation of `projectsId`."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("metrics-get", + Some(r##"Get the specified log metric resource."##), + "Details at http://byron.github.io/google-apis-rs/google_logging1_beta3_cli/projects_metrics-get", + vec![ + (Some(r##"projects-id"##), + None, + Some(r##"Part of `metricName`. The resource name of the desired metric."##), + Some(true), + Some(false)), + + (Some(r##"metrics-id"##), + None, + Some(r##"Part of `metricName`. See documentation of `projectsId`."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("metrics-list", + Some(r##"List log metrics associated with the specified project."##), + "Details at http://byron.github.io/google-apis-rs/google_logging1_beta3_cli/projects_metrics-list", + vec![ + (Some(r##"projects-id"##), + None, + Some(r##"Part of `projectName`. The resource name for the project whose metrics are wanted."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("metrics-update", + Some(r##"Create or update the specified log metric resource."##), + "Details at http://byron.github.io/google-apis-rs/google_logging1_beta3_cli/projects_metrics-update", + vec![ + (Some(r##"projects-id"##), + None, + Some(r##"Part of `metricName`. The resource name of the metric to update."##), + Some(true), + Some(false)), + + (Some(r##"metrics-id"##), + None, + Some(r##"Part of `metricName`. See documentation of `projectsId`."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("sinks-create", + Some(r##"Creates a project sink. A logs filter determines which log entries are written to the destination."##), + "Details at http://byron.github.io/google-apis-rs/google_logging1_beta3_cli/projects_sinks-create", + vec![ + (Some(r##"projects-id"##), + None, + Some(r##"Part of `projectName`. The resource name of the project to which the sink is bound."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("sinks-delete", + Some(r##"Deletes a project sink. After deletion, no new log entries are written to the destination."##), + "Details at http://byron.github.io/google-apis-rs/google_logging1_beta3_cli/projects_sinks-delete", + vec![ + (Some(r##"projects-id"##), + None, + Some(r##"Part of `sinkName`. The resource name of the project sink to delete."##), + Some(true), + Some(false)), + + (Some(r##"sinks-id"##), + None, + Some(r##"Part of `sinkName`. See documentation of `projectsId`."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("sinks-get", + Some(r##"Gets a project sink."##), + "Details at http://byron.github.io/google-apis-rs/google_logging1_beta3_cli/projects_sinks-get", + vec![ + (Some(r##"projects-id"##), + None, + Some(r##"Part of `sinkName`. The resource name of the project sink to return."##), + Some(true), + Some(false)), + + (Some(r##"sinks-id"##), + None, + Some(r##"Part of `sinkName`. See documentation of `projectsId`."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("sinks-list", + Some(r##"Lists project sinks associated with a project."##), + "Details at http://byron.github.io/google-apis-rs/google_logging1_beta3_cli/projects_sinks-list", + vec![ + (Some(r##"projects-id"##), + None, + Some(r##"Part of `projectName`. The project whose sinks are wanted."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("sinks-update", + Some(r##"Updates a project sink. If the sink does not exist, it is created. The destination, filter, or both may be updated."##), + "Details at http://byron.github.io/google-apis-rs/google_logging1_beta3_cli/projects_sinks-update", + vec![ + (Some(r##"projects-id"##), + None, + Some(r##"Part of `sinkName`. The resource name of the project sink to update."##), + Some(true), + Some(false)), + + (Some(r##"sinks-id"##), + None, + Some(r##"Part of `sinkName`. See documentation of `projectsId`."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + (Some(r##"out"##), Some(r##"o"##), Some(r##"Specify the file into which to write the program's output"##), @@ -1656,7 +2633,7 @@ fn main() { let mut app = App::new("logging1-beta3") .author("Sebastian Thiel ") - .version("0.3.2+20150326") + .version("0.3.2+20151007") .about("Google Cloud Logging API lets you create logs, ingest log entries, and manage log sinks.") .after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_logging1_beta3_cli") .arg(Arg::with_name("url") diff --git a/gen/logging1_beta3/Cargo.toml b/gen/logging1_beta3/Cargo.toml index 5862d0d64e..f1abaf331f 100644 --- a/gen/logging1_beta3/Cargo.toml +++ b/gen/logging1_beta3/Cargo.toml @@ -4,10 +4,11 @@ [package] name = "google-logging1_beta3" -version = "0.1.9+20150326" +version = "0.1.9+20151007" authors = ["Sebastian Thiel "] description = "A complete library to interact with logging (protocol v1beta3)" repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/logging1_beta3" +homepage = "https://cloud.google.com/logging/docs/" documentation = "http://byron.github.io/google-apis-rs/google_logging1_beta3" license = "MIT" keywords = ["logging", "google", "protocol", "web", "api"] diff --git a/gen/logging1_beta3/README.md b/gen/logging1_beta3/README.md index 24f35b0933..31ed93b744 100644 --- a/gen/logging1_beta3/README.md +++ b/gen/logging1_beta3/README.md @@ -5,13 +5,16 @@ DO NOT EDIT ! --> The `google-logging1_beta3` library allows access to all features of the *Google logging* service. -This documentation was generated from *logging* crate version *0.1.9+20150326*, where *20150326* is the exact revision of the *logging:v1beta3* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +This documentation was generated from *logging* crate version *0.1.9+20151007*, where *20151007* is the exact revision of the *logging:v1beta3* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. + +Everything else about the *logging* *v1_beta3* API can be found at the +[official documentation site](https://cloud.google.com/logging/docs/). # Features Handle the following *Resources* with ease from the central [hub](http://byron.github.io/google-apis-rs/google_logging1_beta3/struct.Logging.html) ... * projects - * [*log services indexes list*](http://byron.github.io/google-apis-rs/google_logging1_beta3/struct.ProjectLogServiceIndexeListCall.html), [*log services list*](http://byron.github.io/google-apis-rs/google_logging1_beta3/struct.ProjectLogServiceListCall.html), [*log services sinks create*](http://byron.github.io/google-apis-rs/google_logging1_beta3/struct.ProjectLogServiceSinkCreateCall.html), [*log services sinks delete*](http://byron.github.io/google-apis-rs/google_logging1_beta3/struct.ProjectLogServiceSinkDeleteCall.html), [*log services sinks get*](http://byron.github.io/google-apis-rs/google_logging1_beta3/struct.ProjectLogServiceSinkGetCall.html), [*log services sinks list*](http://byron.github.io/google-apis-rs/google_logging1_beta3/struct.ProjectLogServiceSinkListCall.html), [*log services sinks update*](http://byron.github.io/google-apis-rs/google_logging1_beta3/struct.ProjectLogServiceSinkUpdateCall.html), [*logs delete*](http://byron.github.io/google-apis-rs/google_logging1_beta3/struct.ProjectLogDeleteCall.html), [*logs entries write*](http://byron.github.io/google-apis-rs/google_logging1_beta3/struct.ProjectLogEntryWriteCall.html), [*logs list*](http://byron.github.io/google-apis-rs/google_logging1_beta3/struct.ProjectLogListCall.html), [*logs sinks create*](http://byron.github.io/google-apis-rs/google_logging1_beta3/struct.ProjectLogSinkCreateCall.html), [*logs sinks delete*](http://byron.github.io/google-apis-rs/google_logging1_beta3/struct.ProjectLogSinkDeleteCall.html), [*logs sinks get*](http://byron.github.io/google-apis-rs/google_logging1_beta3/struct.ProjectLogSinkGetCall.html), [*logs sinks list*](http://byron.github.io/google-apis-rs/google_logging1_beta3/struct.ProjectLogSinkListCall.html) and [*logs sinks update*](http://byron.github.io/google-apis-rs/google_logging1_beta3/struct.ProjectLogSinkUpdateCall.html) + * [*log services indexes list*](http://byron.github.io/google-apis-rs/google_logging1_beta3/struct.ProjectLogServiceIndexeListCall.html), [*log services list*](http://byron.github.io/google-apis-rs/google_logging1_beta3/struct.ProjectLogServiceListCall.html), [*log services sinks create*](http://byron.github.io/google-apis-rs/google_logging1_beta3/struct.ProjectLogServiceSinkCreateCall.html), [*log services sinks delete*](http://byron.github.io/google-apis-rs/google_logging1_beta3/struct.ProjectLogServiceSinkDeleteCall.html), [*log services sinks get*](http://byron.github.io/google-apis-rs/google_logging1_beta3/struct.ProjectLogServiceSinkGetCall.html), [*log services sinks list*](http://byron.github.io/google-apis-rs/google_logging1_beta3/struct.ProjectLogServiceSinkListCall.html), [*log services sinks update*](http://byron.github.io/google-apis-rs/google_logging1_beta3/struct.ProjectLogServiceSinkUpdateCall.html), [*logs delete*](http://byron.github.io/google-apis-rs/google_logging1_beta3/struct.ProjectLogDeleteCall.html), [*logs entries write*](http://byron.github.io/google-apis-rs/google_logging1_beta3/struct.ProjectLogEntryWriteCall.html), [*logs list*](http://byron.github.io/google-apis-rs/google_logging1_beta3/struct.ProjectLogListCall.html), [*logs sinks create*](http://byron.github.io/google-apis-rs/google_logging1_beta3/struct.ProjectLogSinkCreateCall.html), [*logs sinks delete*](http://byron.github.io/google-apis-rs/google_logging1_beta3/struct.ProjectLogSinkDeleteCall.html), [*logs sinks get*](http://byron.github.io/google-apis-rs/google_logging1_beta3/struct.ProjectLogSinkGetCall.html), [*logs sinks list*](http://byron.github.io/google-apis-rs/google_logging1_beta3/struct.ProjectLogSinkListCall.html), [*logs sinks update*](http://byron.github.io/google-apis-rs/google_logging1_beta3/struct.ProjectLogSinkUpdateCall.html), [*metrics create*](http://byron.github.io/google-apis-rs/google_logging1_beta3/struct.ProjectMetricCreateCall.html), [*metrics delete*](http://byron.github.io/google-apis-rs/google_logging1_beta3/struct.ProjectMetricDeleteCall.html), [*metrics get*](http://byron.github.io/google-apis-rs/google_logging1_beta3/struct.ProjectMetricGetCall.html), [*metrics list*](http://byron.github.io/google-apis-rs/google_logging1_beta3/struct.ProjectMetricListCall.html), [*metrics update*](http://byron.github.io/google-apis-rs/google_logging1_beta3/struct.ProjectMetricUpdateCall.html), [*sinks create*](http://byron.github.io/google-apis-rs/google_logging1_beta3/struct.ProjectSinkCreateCall.html), [*sinks delete*](http://byron.github.io/google-apis-rs/google_logging1_beta3/struct.ProjectSinkDeleteCall.html), [*sinks get*](http://byron.github.io/google-apis-rs/google_logging1_beta3/struct.ProjectSinkGetCall.html), [*sinks list*](http://byron.github.io/google-apis-rs/google_logging1_beta3/struct.ProjectSinkListCall.html) and [*sinks update*](http://byron.github.io/google-apis-rs/google_logging1_beta3/struct.ProjectSinkUpdateCall.html) @@ -45,11 +48,14 @@ Or specifically ... ```ignore let r = hub.projects().logs_sinks_get(...).doit() +let r = hub.projects().sinks_create(...).doit() let r = hub.projects().log_services_sinks_update(...).doit() +let r = hub.projects().sinks_update(...).doit() let r = hub.projects().logs_sinks_update(...).doit() let r = hub.projects().log_services_sinks_create(...).doit() let r = hub.projects().logs_sinks_create(...).doit() let r = hub.projects().log_services_sinks_get(...).doit() +let r = hub.projects().sinks_get(...).doit() ``` The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` diff --git a/gen/logging1_beta3/src/lib.rs b/gen/logging1_beta3/src/lib.rs index bc4af56048..3f41dc05ce 100644 --- a/gen/logging1_beta3/src/lib.rs +++ b/gen/logging1_beta3/src/lib.rs @@ -2,14 +2,17 @@ // This file was generated automatically from 'src/mako/api/lib.rs.mako' // DO NOT EDIT ! -//! This documentation was generated from *logging* crate version *0.1.9+20150326*, where *20150326* is the exact revision of the *logging:v1beta3* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +//! This documentation was generated from *logging* crate version *0.1.9+20151007*, where *20151007* is the exact revision of the *logging:v1beta3* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +//! +//! Everything else about the *logging* *v1_beta3* API can be found at the +//! [official documentation site](https://cloud.google.com/logging/docs/). //! The original source code is [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/logging1_beta3). //! # Features //! //! Handle the following *Resources* with ease from the central [hub](struct.Logging.html) ... //! //! * projects -//! * [*log services indexes list*](struct.ProjectLogServiceIndexeListCall.html), [*log services list*](struct.ProjectLogServiceListCall.html), [*log services sinks create*](struct.ProjectLogServiceSinkCreateCall.html), [*log services sinks delete*](struct.ProjectLogServiceSinkDeleteCall.html), [*log services sinks get*](struct.ProjectLogServiceSinkGetCall.html), [*log services sinks list*](struct.ProjectLogServiceSinkListCall.html), [*log services sinks update*](struct.ProjectLogServiceSinkUpdateCall.html), [*logs delete*](struct.ProjectLogDeleteCall.html), [*logs entries write*](struct.ProjectLogEntryWriteCall.html), [*logs list*](struct.ProjectLogListCall.html), [*logs sinks create*](struct.ProjectLogSinkCreateCall.html), [*logs sinks delete*](struct.ProjectLogSinkDeleteCall.html), [*logs sinks get*](struct.ProjectLogSinkGetCall.html), [*logs sinks list*](struct.ProjectLogSinkListCall.html) and [*logs sinks update*](struct.ProjectLogSinkUpdateCall.html) +//! * [*log services indexes list*](struct.ProjectLogServiceIndexeListCall.html), [*log services list*](struct.ProjectLogServiceListCall.html), [*log services sinks create*](struct.ProjectLogServiceSinkCreateCall.html), [*log services sinks delete*](struct.ProjectLogServiceSinkDeleteCall.html), [*log services sinks get*](struct.ProjectLogServiceSinkGetCall.html), [*log services sinks list*](struct.ProjectLogServiceSinkListCall.html), [*log services sinks update*](struct.ProjectLogServiceSinkUpdateCall.html), [*logs delete*](struct.ProjectLogDeleteCall.html), [*logs entries write*](struct.ProjectLogEntryWriteCall.html), [*logs list*](struct.ProjectLogListCall.html), [*logs sinks create*](struct.ProjectLogSinkCreateCall.html), [*logs sinks delete*](struct.ProjectLogSinkDeleteCall.html), [*logs sinks get*](struct.ProjectLogSinkGetCall.html), [*logs sinks list*](struct.ProjectLogSinkListCall.html), [*logs sinks update*](struct.ProjectLogSinkUpdateCall.html), [*metrics create*](struct.ProjectMetricCreateCall.html), [*metrics delete*](struct.ProjectMetricDeleteCall.html), [*metrics get*](struct.ProjectMetricGetCall.html), [*metrics list*](struct.ProjectMetricListCall.html), [*metrics update*](struct.ProjectMetricUpdateCall.html), [*sinks create*](struct.ProjectSinkCreateCall.html), [*sinks delete*](struct.ProjectSinkDeleteCall.html), [*sinks get*](struct.ProjectSinkGetCall.html), [*sinks list*](struct.ProjectSinkListCall.html) and [*sinks update*](struct.ProjectSinkUpdateCall.html) //! //! //! @@ -45,11 +48,14 @@ //! //! ```ignore //! let r = hub.projects().logs_sinks_get(...).doit() +//! let r = hub.projects().sinks_create(...).doit() //! let r = hub.projects().log_services_sinks_update(...).doit() +//! let r = hub.projects().sinks_update(...).doit() //! let r = hub.projects().logs_sinks_update(...).doit() //! let r = hub.projects().log_services_sinks_create(...).doit() //! let r = hub.projects().logs_sinks_create(...).doit() //! let r = hub.projects().log_services_sinks_get(...).doit() +//! let r = hub.projects().sinks_get(...).doit() //! ``` //! //! The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities` diff --git a/gen/logging1_beta3/src/lib.rs.in b/gen/logging1_beta3/src/lib.rs.in index 5eff017479..01b963c655 100644 --- a/gen/logging1_beta3/src/lib.rs.in +++ b/gen/logging1_beta3/src/lib.rs.in @@ -35,21 +35,37 @@ pub use cmn::{MultiPartReader, ToParts, MethodInfo, Result, Error, CallBuilder, /// [authorization token](https://developers.google.com/youtube/v3/guides/authentication). #[derive(PartialEq, Eq, Hash)] pub enum Scope { + /// Administrate log data for your projects + Admin, + + /// View log data for your projects + Read, + + /// Submit log data for your projects + Write, + /// View and manage your data across Google Cloud Platform services CloudPlatform, + + /// View your data across Google Cloud Platform services + CloudPlatformReadOnly, } impl AsRef for Scope { fn as_ref(&self) -> &str { match *self { + Scope::Admin => "https://www.googleapis.com/auth/logging.admin", + Scope::Read => "https://www.googleapis.com/auth/logging.read", + Scope::Write => "https://www.googleapis.com/auth/logging.write", Scope::CloudPlatform => "https://www.googleapis.com/auth/cloud-platform", + Scope::CloudPlatformReadOnly => "https://www.googleapis.com/auth/cloud-platform.read-only", } } } impl Default for Scope { fn default() -> Scope { - Scope::CloudPlatform + Scope::Read } } @@ -155,60 +171,100 @@ impl<'a, C, A> Logging // ############ // SCHEMAS ### // ########## -/// Represents the RPC error status for Google APIs. See http://go/errormodel for details. +/// A common proto for logging HTTP 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 Status { - /// A developer-facing error message, which should be in English. The user-facing error message should be localized and stored in the [google.rpc.Status.details][google.rpc.Status.details] field. - pub message: Option, - /// The status code, which should be an enum value of [google.rpc.Code][]. - pub code: Option, - /// A list of messages that carry the error details. There will be a common set of message types for APIs to use. - pub details: Option>>, +pub struct HttpRequest { + /// A response code indicates the status of response, e.g., 200. + pub status: Option, + /// Request method, such as `GET`, `HEAD`, `PUT` or `POST`. + #[serde(rename="requestMethod")] + pub request_method: Option, + /// Contains the scheme (http|https), the host name, the path and the query portion of the URL that was requested. + #[serde(rename="requestUrl")] + pub request_url: Option, + /// Whether or not an entity was served from cache (with or without validation). + #[serde(rename="cacheHit")] + pub cache_hit: Option, + /// Referer (a.k.a. referrer) URL of request, as defined in http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html. + pub referer: Option, + /// IP address of the client who issues the HTTP request. Could be either IPv4 or IPv6. + #[serde(rename="remoteIp")] + pub remote_ip: Option, + /// User agent sent by the client, e.g., "Mozilla/4.0 (compatible; MSIE 6.0; Windows 98; Q312461; .NET CLR 1.0.3705)". + #[serde(rename="userAgent")] + pub user_agent: Option, + /// Whether or not the response was validated with the origin server before being served from cache. This field is only meaningful if cache_hit is True. + #[serde(rename="validatedWithOriginServer")] + pub validated_with_origin_server: Option, + /// Size of the HTTP request message in bytes, including request headers and the request body. + #[serde(rename="requestSize")] + pub request_size: Option, + /// Size of the HTTP response message in bytes sent back to the client, including response headers and response body. + #[serde(rename="responseSize")] + pub response_size: Option, } -impl Part for Status {} +impl Part for HttpRequest {} -/// A problem in a sink or the sink's configuration. +/// Describes a problem with a logging resource or operation. /// /// This type is not used in any activity, and only used as *part* of another schema. /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct LogError { - /// The description of the last error observed. + /// The error description, including a classification code, an error message, and other details. pub status: Option, - /// The last time the error was observed, in nanoseconds since the Unix epoch. + /// The time the error was observed, in nanoseconds since the Unix epoch. #[serde(rename="timeNanos")] pub time_nanos: Option, - /// The resource associated with the error. It may be different from the sink destination. For example, the sink may point to a BigQuery dataset, but the error may refer to a table resource inside the dataset. + /// A resource name associated with this error. For example, the name of a Cloud Storage bucket that has insufficient permissions to be a destination for log entries. pub resource: Option, } impl Part for LogError {} -/// A log object. +/// _Output only._ Describes a log, which is a named stream of log entries. /// /// This type is not used in any activity, and only used as *part* of another schema. /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct Log { - /// Type URL describing the expected payload type for the log. + /// _Optional_. A URI representing the expected payload type for log entries. #[serde(rename="payloadType")] pub payload_type: Option, - /// Name used when displaying the log to the user (for example, in a UI). Example: `"activity_log"` + /// _Optional._ The common name of the log. Example: `"request_log"`. #[serde(rename="displayName")] pub display_name: Option, - /// REQUIRED: The log's name name. Example: `"compute.googleapis.com/activity_log"`. + /// The resource name of the log. Example: `"/projects/my-gcp-project-id/logs/LOG_NAME"`, where `LOG_NAME` is the URL-encoded given name of the log. The log includes those log entries whose `LogEntry.log` field contains this given name. To avoid name collisions, it is a best practice to prefix the given log name with the service name, but this is not required. Examples of log given names: `"appengine.googleapis.com/request_log"`, `"apache-access"`. pub name: Option, } impl Part for Log {} +/// Result returned from `ListLogServiceSinks`. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [log services sinks list projects](struct.ProjectLogServiceSinkListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ListLogServiceSinksResponse { + /// The requested log service sinks. If a returned `LogSink` object has an empty `destination` field, the client can retrieve the complete `LogSink` object by calling `logServices.sinks.get`. + pub sinks: Option>, +} + +impl ResponseResult for ListLogServiceSinksResponse {} + + /// Result returned from ListLogs. /// /// # Activities @@ -223,81 +279,32 @@ pub struct ListLogsResponse { /// If there are more results, then `nextPageToken` is returned in the response. To get the next batch of logs, use the value of `nextPageToken` as `pageToken` in the next call of `ListLogs`. If `nextPageToken` is empty, then there are no more results. #[serde(rename="nextPageToken")] pub next_page_token: Option, - /// A list of log resources. + /// A list of log descriptions matching the criteria. pub logs: Option>, } impl ResponseResult for ListLogsResponse {} -/// A log service object. -/// -/// This type is not used in any activity, and only used as *part* of another schema. -/// -#[derive(Default, Clone, Debug, Serialize, Deserialize)] -pub struct LogService { - /// Label keys used when labeling log entries for this service. The order of the keys is significant, with higher priority keys coming earlier in the list. - #[serde(rename="indexKeys")] - pub index_keys: Option>, - /// The service's name. - pub name: Option, -} - -impl Part for LogService {} - - -/// Result returned from WriteLogEntries. empty +/// Result returned from ListLogMetrics. /// /// # Activities /// /// This type is used in activities, which are methods you may call on this type or where this type is involved in. /// The list links the activity name, along with information about where it is used (one of *request* and *response*). /// -/// * [logs entries write projects](struct.ProjectLogEntryWriteCall.html) (response) +/// * [metrics list projects](struct.ProjectMetricListCall.html) (response) /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] -pub struct WriteLogEntriesResponse; - -impl ResponseResult for WriteLogEntriesResponse {} - - -/// Result returned from `ListLogSinks`. -/// -/// # Activities -/// -/// This type is used in activities, which are methods you may call on this type or where this type is involved in. -/// The list links the activity name, along with information about where it is used (one of *request* and *response*). -/// -/// * [logs sinks list projects](struct.ProjectLogSinkListCall.html) (response) -/// -#[derive(Default, Clone, Debug, Serialize, Deserialize)] -pub struct ListLogSinksResponse { - /// The requested log sinks. If any of the returned `LogSink` objects have an empty `destination` field, then call `logServices.sinks.get` to retrieve the complete `LogSink` object. - pub sinks: Option>, +pub struct ListLogMetricsResponse { + /// The list of metrics that was requested. + pub metrics: Option>, + /// If there are more results, then `nextPageToken` is returned in the response. To get the next batch of entries, use the value of `nextPageToken` as `pageToken` in the next call of `ListLogMetrics`. If `nextPageToken` is empty, then there are no more results. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, } -impl ResponseResult for ListLogSinksResponse {} - - -/// The parameters to WriteLogEntries. -/// -/// # Activities -/// -/// This type is used in activities, which are methods you may call on this type or where this type is involved in. -/// The list links the activity name, along with information about where it is used (one of *request* and *response*). -/// -/// * [logs entries write projects](struct.ProjectLogEntryWriteCall.html) (request) -/// -#[derive(Default, Clone, Debug, Serialize, Deserialize)] -pub struct WriteLogEntriesRequest { - /// Metadata labels that apply to all entries in this request. If one of the log entries contains a (key, value) with the same key that is in `commonLabels`, then the entry's (key, value) overrides the one in `commonLabels`. - #[serde(rename="commonLabels")] - pub common_labels: Option>, - /// Log entries to insert. - pub entries: Option>, -} - -impl RequestValue for WriteLogEntriesRequest {} +impl ResponseResult for ListLogMetricsResponse {} /// Result returned from `ListLogServicesRequest`. @@ -322,31 +329,78 @@ pub struct ListLogServicesResponse { impl ResponseResult for ListLogServicesResponse {} -/// An individual entry in a log. +/// Result returned from ListLogServiceIndexesRequest. /// -/// This type is not used in any activity, and only used as *part* of another schema. +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [log services indexes list projects](struct.ProjectLogServiceIndexeListCall.html) (response) /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] -pub struct LogEntry { - /// The log entry payload, represented as a protocol buffer that is expressed as a JSON object. You can only pass `protoPayload` values that belong to a set of approved types. - #[serde(rename="protoPayload")] - pub proto_payload: Option>, - /// The log to which this entry belongs. When a log entry is ingested, the value of this field is set by the logging system. - pub log: Option, - /// The log entry payload, represented as a text string. - #[serde(rename="textPayload")] - pub text_payload: Option, - /// A unique ID for the log entry. If you provide this field, the logging service considers other log entries in the same log with the same ID as duplicates which can be removed. - #[serde(rename="insertId")] - pub insert_id: Option, - /// The log entry payload, represented as a structure that is expressed as a JSON object. - #[serde(rename="structPayload")] - pub struct_payload: Option>, - /// Information about the log entry. - pub metadata: Option, +pub struct ListLogServiceIndexesResponse { + /// If there are more results, then `nextPageToken` is returned in the response. To get the next batch of indexes, use the value of `nextPageToken` as `pageToken` in the next call of `ListLogServiceIndexes`. If `nextPageToken` is empty, then there are no more results. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// A list of log service index values. Each index value has the form `"/value1/value2/..."`, where `value1` is a value in the primary index, `value2` is a value in the secondary index, and so forth. + #[serde(rename="serviceIndexPrefixes")] + pub service_index_prefixes: Option>, } -impl Part for LogEntry {} +impl ResponseResult for ListLogServiceIndexesResponse {} + + +/// Describes where log entries are written outside of Cloud Logging. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [logs sinks get projects](struct.ProjectLogSinkGetCall.html) (response) +/// * [sinks create projects](struct.ProjectSinkCreateCall.html) (request|response) +/// * [log services sinks update projects](struct.ProjectLogServiceSinkUpdateCall.html) (request|response) +/// * [sinks update projects](struct.ProjectSinkUpdateCall.html) (request|response) +/// * [logs sinks update projects](struct.ProjectLogSinkUpdateCall.html) (request|response) +/// * [log services sinks create projects](struct.ProjectLogServiceSinkCreateCall.html) (request|response) +/// * [logs sinks create projects](struct.ProjectLogSinkCreateCall.html) (request|response) +/// * [log services sinks get projects](struct.ProjectLogServiceSinkGetCall.html) (response) +/// * [sinks get projects](struct.ProjectSinkGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct LogSink { + /// An advanced logs filter. If present, only log entries matching the filter are written. Only project sinks use this field; log sinks and log service sinks must not include a filter. + pub filter: Option, + /// The resource name of the destination. Cloud Logging writes designated log entries to this destination. For example, `"storage.googleapis.com/my-output-bucket"`. + pub destination: Option, + /// _Output only._ If any errors occur when invoking a sink method, then this field contains descriptions of the errors. + pub errors: Option>, + /// The client-assigned name of this sink. For example, `"my-syslog-sink"`. The name must be unique among the sinks of a similar kind in the project. + pub name: Option, +} + +impl RequestValue for LogSink {} +impl ResponseResult for LogSink {} + + +/// A generic empty message that you can re-use to avoid defining duplicated empty messages in your APIs. A typical example is to use it as the request or the response type of an API method. For instance: service Foo { rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); } The JSON representation for `Empty` is empty JSON object `{}`. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [sinks delete projects](struct.ProjectSinkDeleteCall.html) (response) +/// * [logs sinks delete projects](struct.ProjectLogSinkDeleteCall.html) (response) +/// * [log services sinks delete projects](struct.ProjectLogServiceSinkDeleteCall.html) (response) +/// * [metrics delete projects](struct.ProjectMetricDeleteCall.html) (response) +/// * [logs delete projects](struct.ProjectLogDeleteCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Empty; + +impl ResponseResult for Empty {} /// Additional data that is associated with a log entry, set by the service creating the log entry. @@ -379,89 +433,164 @@ pub struct LogEntryMetadata { impl Part for LogEntryMetadata {} -/// Result returned from ListLogServiceIndexesRequest. +/// The `Status` type defines a logical error model that is suitable for different programming environments, including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). The error model is designed to be: - Simple to use and understand for most users - Flexible enough to meet unexpected needs # Overview The `Status` message contains three pieces of data: error code, error message, and error details. The error code should be an enum value of google.rpc.Code, but it may accept additional error codes if needed. The error message should be a developer-facing English message that helps developers *understand* and *resolve* the error. If a localized user-facing error message is needed, put the localized message in the error details or localize it in the client. The optional error details may contain arbitrary information about the error. There is a predefined set of error detail types in the package `google.rpc` which can be used for common error conditions. # Language mapping The `Status` message is the logical representation of the error model, but it is not necessarily the actual wire format. When the `Status` message is exposed in different client libraries and different wire protocols, it can be mapped differently. For example, it will likely be mapped to some exceptions in Java, but more likely mapped to some error codes in C. # Other uses The error model and the `Status` message can be used in a variety of environments, either with or without APIs, to provide a consistent developer experience across different environments. Example uses of this error model include: - Partial errors. If a service needs to return partial errors to the client, it may embed the `Status` in the normal response to indicate the partial errors. - Workflow errors. A typical workflow has multiple steps. Each step may have a `Status` message for error reporting purpose. - Batch operations. If a client uses batch request and batch response, the `Status` message should be used directly inside batch response, one for each error sub-response. - Asynchronous operations. If an API call embeds asynchronous operation results in its response, the status of those operations should be represented directly using the `Status` message. - Logging. If some API errors are stored in logs, the message `Status` could be used directly after any stripping needed for security/privacy reasons. /// -/// # Activities -/// -/// This type is used in activities, which are methods you may call on this type or where this type is involved in. -/// The list links the activity name, along with information about where it is used (one of *request* and *response*). -/// -/// * [log services indexes list projects](struct.ProjectLogServiceIndexeListCall.html) (response) +/// This type is not used in any activity, and only used as *part* of another schema. /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] -pub struct ListLogServiceIndexesResponse { - /// If there are more results, then `nextPageToken` is returned in the response. To get the next batch of indexes, use the value of `nextPageToken` as `pageToken` in the next call of `ListLogServiceIndexess`. If `nextPageToken` is empty, then there are no more results. - #[serde(rename="nextPageToken")] - pub next_page_token: Option, - /// A list of log service index prefixes. - #[serde(rename="serviceIndexPrefixes")] - pub service_index_prefixes: Option>, +pub struct Status { + /// A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the google.rpc.Status.details field, or localized by the client. + pub message: Option, + /// The status code, which should be an enum value of google.rpc.Code. + pub code: Option, + /// A list of messages that carry the error details. There will be a common set of message types for APIs to use. + pub details: Option>>, } -impl ResponseResult for ListLogServiceIndexesResponse {} +impl Part for Status {} -/// An object that describes where a log may be written. +/// _Output only._ Describes a service that writes log entries. /// -/// # Activities -/// -/// This type is used in activities, which are methods you may call on this type or where this type is involved in. -/// The list links the activity name, along with information about where it is used (one of *request* and *response*). -/// -/// * [logs sinks get projects](struct.ProjectLogSinkGetCall.html) (response) -/// * [log services sinks update projects](struct.ProjectLogServiceSinkUpdateCall.html) (request|response) -/// * [logs sinks update projects](struct.ProjectLogSinkUpdateCall.html) (request|response) -/// * [log services sinks create projects](struct.ProjectLogServiceSinkCreateCall.html) (request|response) -/// * [logs sinks create projects](struct.ProjectLogSinkCreateCall.html) (request|response) -/// * [log services sinks get projects](struct.ProjectLogServiceSinkGetCall.html) (response) +/// This type is not used in any activity, and only used as *part* of another schema. /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] -pub struct LogSink { - /// The resource to send log entries to. The supported sink resource types are: + Google Cloud Storage: `storage.googleapis.com/BUCKET` or `BUCKET.storage.googleapis.com/` + Google BigQuery: `bigquery.googleapis.com/projects/PROJECT/datasets/DATASET` Currently the Cloud Logging API supports at most one sink for each resource type per log or log service resource. - pub destination: Option, - /// _Output only._ All active errors found for this sink. - pub errors: Option>, - /// The name of this sink. This is a client-assigned identifier for the resource. This is ignored by UpdateLogSink and UpdateLogServicesSink. +pub struct LogService { + /// A list of the names of the keys used to index and label individual log entries from this service. The first two keys are used as the primary and secondary index, respectively. Additional keys may be used to label the entries. For example, App Engine indexes its entries by module and by version, so its `indexKeys` field is the following: [ "appengine.googleapis.com/module_id", "appengine.googleapis.com/version_id" ] + #[serde(rename="indexKeys")] + pub index_keys: Option>, + /// The service's name. Example: `"appengine.googleapis.com"`. Log names beginning with this string are reserved for this service. This value can appear in the `LogEntry.metadata.serviceName` field of log entries associated with this log service. pub name: Option, } -impl RequestValue for LogSink {} -impl ResponseResult for LogSink {} +impl Part for LogService {} -/// A generic empty message that you can re-use to avoid defining duplicated empty messages in your APIs. A typical example is to use it as the request or the response type of an API method. For instance: service Foo { rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); } +/// Result returned from `ListSinks`. /// /// # Activities /// /// This type is used in activities, which are methods you may call on this type or where this type is involved in. /// The list links the activity name, along with information about where it is used (one of *request* and *response*). /// -/// * [logs sinks delete projects](struct.ProjectLogSinkDeleteCall.html) (response) -/// * [log services sinks delete projects](struct.ProjectLogServiceSinkDeleteCall.html) (response) -/// * [logs delete projects](struct.ProjectLogDeleteCall.html) (response) +/// * [sinks list projects](struct.ProjectSinkListCall.html) (response) /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] -pub struct Empty; - -impl ResponseResult for Empty {} - - -/// Result returned from `ListLogServiceSinks`. -/// -/// # Activities -/// -/// This type is used in activities, which are methods you may call on this type or where this type is involved in. -/// The list links the activity name, along with information about where it is used (one of *request* and *response*). -/// -/// * [log services sinks list projects](struct.ProjectLogServiceSinkListCall.html) (response) -/// -#[derive(Default, Clone, Debug, Serialize, Deserialize)] -pub struct ListLogServiceSinksResponse { - /// The requested log service sinks. If any of the returned `LogSink` objects have an empty `destination` field, then call `logServices.sinks.get` to retrieve the complete `LogSink` object. +pub struct ListSinksResponse { + /// The requested sinks. If a returned `LogSink` object has an empty `destination` field, the client can retrieve the complete `LogSink` object by calling `projects.sinks.get`. pub sinks: Option>, } -impl ResponseResult for ListLogServiceSinksResponse {} +impl ResponseResult for ListSinksResponse {} + + +/// Result returned from WriteLogEntries. empty +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [logs entries write projects](struct.ProjectLogEntryWriteCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct WriteLogEntriesResponse; + +impl ResponseResult for WriteLogEntriesResponse {} + + +/// Result returned from `ListLogSinks`. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [logs sinks list projects](struct.ProjectLogSinkListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ListLogSinksResponse { + /// The requested log sinks. If a returned `LogSink` object has an empty `destination` field, the client can retrieve the complete `LogSink` object by calling `log.sinks.get`. + pub sinks: Option>, +} + +impl ResponseResult for ListLogSinksResponse {} + + +/// The parameters to WriteLogEntries. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [logs entries write projects](struct.ProjectLogEntryWriteCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct WriteLogEntriesRequest { + /// Metadata labels that apply to all log entries in this request, so that you don't have to repeat them in each log entry's `metadata.labels` field. If any of the log entries contains a (key, value) with the same key that is in `commonLabels`, then the entry's (key, value) overrides the one in `commonLabels`. + #[serde(rename="commonLabels")] + pub common_labels: Option>, + /// Log entries to insert. + pub entries: Option>, +} + +impl RequestValue for WriteLogEntriesRequest {} + + +/// An individual entry in a log. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct LogEntry { + /// Information about the HTTP request associated with this log entry, if applicable. + #[serde(rename="httpRequest")] + pub http_request: Option, + /// The log entry payload, represented as a protocol buffer that is expressed as a JSON object. You can only pass `protoPayload` values that belong to a set of approved types. + #[serde(rename="protoPayload")] + pub proto_payload: Option>, + /// The log to which this entry belongs. When a log entry is ingested, the value of this field is set by the logging system. + pub log: Option, + /// The log entry payload, represented as a text string. + #[serde(rename="textPayload")] + pub text_payload: Option, + /// A unique ID for the log entry. If you provide this field, the logging service considers other log entries in the same log with the same ID as duplicates which can be removed. + #[serde(rename="insertId")] + pub insert_id: Option, + /// The log entry payload, represented as a structure that is expressed as a JSON object. + #[serde(rename="structPayload")] + pub struct_payload: Option>, + /// Information about the log entry. + pub metadata: Option, +} + +impl Part for LogEntry {} + + +/// Describes a collected, logs-based metric. The value of the metric is the number of log entries in the project that match the advanced logs filter in the `filter` 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*). +/// +/// * [metrics create projects](struct.ProjectMetricCreateCall.html) (request|response) +/// * [metrics get projects](struct.ProjectMetricGetCall.html) (response) +/// * [metrics update projects](struct.ProjectMetricUpdateCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct LogMetric { + /// An [advanced logs filter](/logging/docs/view/advanced_filters). Example: `"log:syslog AND metadata.severity>=ERROR"`. + pub filter: Option, + /// The client-assigned name for this metric, such as `"severe_errors"`. Metric names are limited to 1000 characters and can include only the following characters: `-A-Za-z0-9_.,+!*',()%/\`. The slash character `/` implies a hierarchy of name pieces, and cannot be the first character of the name. + pub name: Option, + /// A description of this metric. + pub description: Option, +} + +impl RequestValue for LogMetric {} +impl ResponseResult for LogMetric {} @@ -492,7 +621,7 @@ impl ResponseResult for ListLogServiceSinksResponse {} /// ::default(), None); /// let mut hub = Logging::new(hyper::Client::new(), auth); /// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* -/// // like `log_services_indexes_list(...)`, `log_services_list(...)`, `log_services_sinks_create(...)`, `log_services_sinks_delete(...)`, `log_services_sinks_get(...)`, `log_services_sinks_list(...)`, `log_services_sinks_update(...)`, `logs_delete(...)`, `logs_entries_write(...)`, `logs_list(...)`, `logs_sinks_create(...)`, `logs_sinks_delete(...)`, `logs_sinks_get(...)`, `logs_sinks_list(...)` and `logs_sinks_update(...)` +/// // like `log_services_indexes_list(...)`, `log_services_list(...)`, `log_services_sinks_create(...)`, `log_services_sinks_delete(...)`, `log_services_sinks_get(...)`, `log_services_sinks_list(...)`, `log_services_sinks_update(...)`, `logs_delete(...)`, `logs_entries_write(...)`, `logs_list(...)`, `logs_sinks_create(...)`, `logs_sinks_delete(...)`, `logs_sinks_get(...)`, `logs_sinks_list(...)`, `logs_sinks_update(...)`, `metrics_create(...)`, `metrics_delete(...)`, `metrics_get(...)`, `metrics_list(...)`, `metrics_update(...)`, `sinks_create(...)`, `sinks_delete(...)`, `sinks_get(...)`, `sinks_list(...)` and `sinks_update(...)` /// // to build up your call. /// let rb = hub.projects(); /// # } @@ -509,18 +638,17 @@ impl<'a, C, A> ProjectMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Lists log services associated with log entries ingested for a project. + /// Deletes a log and all its log entries. The log will reappear if it receives new entries. /// /// # Arguments /// - /// * `projectsId` - Part of `projectName`. The project resource whose services are to be listed. - pub fn log_services_list(&self, projects_id: &str) -> ProjectLogServiceListCall<'a, C, A> { - ProjectLogServiceListCall { + /// * `projectsId` - Part of `logName`. The resource name of the log to be deleted. + /// * `logsId` - Part of `logName`. See documentation of `projectsId`. + pub fn logs_delete(&self, projects_id: &str, logs_id: &str) -> ProjectLogDeleteCall<'a, C, A> { + ProjectLogDeleteCall { hub: self.hub, _projects_id: projects_id.to_string(), - _page_token: Default::default(), - _page_size: Default::default(), - _log: Default::default(), + _logs_id: logs_id.to_string(), _delegate: Default::default(), _scopes: Default::default(), _additional_params: Default::default(), @@ -529,11 +657,51 @@ impl<'a, C, A> ProjectMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Lists log resources belonging to the specified project. + /// Creates a log sink. All log entries for a specified log are written to the destination. /// /// # Arguments /// - /// * `projectsId` - Part of `projectName`. The project name for which to list the log resources. + /// * `request` - No description provided. + /// * `projectsId` - Part of `logName`. The resource name of the log to which to the sink is bound. + /// * `logsId` - Part of `logName`. See documentation of `projectsId`. + pub fn logs_sinks_create(&self, request: LogSink, projects_id: &str, logs_id: &str) -> ProjectLogSinkCreateCall<'a, C, A> { + ProjectLogSinkCreateCall { + hub: self.hub, + _request: request, + _projects_id: projects_id.to_string(), + _logs_id: logs_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 log metric resource. + /// + /// # Arguments + /// + /// * `projectsId` - Part of `metricName`. The resource name of the desired metric. + /// * `metricsId` - Part of `metricName`. See documentation of `projectsId`. + pub fn metrics_get(&self, projects_id: &str, metrics_id: &str) -> ProjectMetricGetCall<'a, C, A> { + ProjectMetricGetCall { + hub: self.hub, + _projects_id: projects_id.to_string(), + _metrics_id: metrics_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 logs in the project. Only logs that have entries are listed. + /// + /// # Arguments + /// + /// * `projectsId` - Part of `projectName`. The resource name of the project whose logs are requested. If both `serviceName` and `serviceIndexPrefix` are empty, then all logs with entries in this project are listed. pub fn logs_list(&self, projects_id: &str) -> ProjectLogListCall<'a, C, A> { ProjectLogListCall { hub: self.hub, @@ -550,11 +718,49 @@ impl<'a, C, A> ProjectMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Gets the specified log sink resource. + /// Create the specified log metric resource. /// /// # Arguments /// - /// * `projectsId` - Part of `sinkName`. The name of the sink resource to return. + /// * `request` - No description provided. + /// * `projectsId` - Part of `projectName`. The resource name of the project in which to create the metric. + pub fn metrics_create(&self, request: LogMetric, projects_id: &str) -> ProjectMetricCreateCall<'a, C, A> { + ProjectMetricCreateCall { + hub: self.hub, + _request: request, + _projects_id: projects_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 project sink. + /// + /// # Arguments + /// + /// * `projectsId` - Part of `sinkName`. The resource name of the project sink to return. + /// * `sinksId` - Part of `sinkName`. See documentation of `projectsId`. + pub fn sinks_get(&self, projects_id: &str, sinks_id: &str) -> ProjectSinkGetCall<'a, C, A> { + ProjectSinkGetCall { + hub: self.hub, + _projects_id: projects_id.to_string(), + _sinks_id: sinks_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 log sink. + /// + /// # Arguments + /// + /// * `projectsId` - Part of `sinkName`. The resource name of the log sink to return. /// * `logsId` - Part of `sinkName`. See documentation of `projectsId`. /// * `sinksId` - Part of `sinkName`. See documentation of `projectsId`. pub fn logs_sinks_get(&self, projects_id: &str, logs_id: &str, sinks_id: &str) -> ProjectLogSinkGetCall<'a, C, A> { @@ -571,12 +777,12 @@ impl<'a, C, A> ProjectMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Creates or update the specified log service sink resource. + /// Updates a log service sink. If the sink does not exist, it is created. /// /// # Arguments /// /// * `request` - No description provided. - /// * `projectsId` - Part of `sinkName`. The name of the sink to update. + /// * `projectsId` - Part of `sinkName`. The resource name of the log service sink to update. /// * `logServicesId` - Part of `sinkName`. See documentation of `projectsId`. /// * `sinksId` - Part of `sinkName`. See documentation of `projectsId`. pub fn log_services_sinks_update(&self, request: LogSink, projects_id: &str, log_services_id: &str, sinks_id: &str) -> ProjectLogServiceSinkUpdateCall<'a, C, A> { @@ -594,12 +800,92 @@ impl<'a, C, A> ProjectMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Creates one or more log entries in a log. You must supply a list of `LogEntry` objects, named `entries`. Each `LogEntry` object must contain a payload object and a `LogEntryMetadata` object that describes the entry. You must fill in all the fields of the entry, metadata, and payload. You can also supply a map, `commonLabels`, that supplies default (key, value) data for the `entries[].metadata.labels` maps, saving you the trouble of creating identical copies for each entry. + /// Updates a project sink. If the sink does not exist, it is created. The destination, filter, or both may be updated. /// /// # Arguments /// /// * `request` - No description provided. - /// * `projectsId` - Part of `logName`. The name of the log resource into which to insert the log entries. + /// * `projectsId` - Part of `sinkName`. The resource name of the project sink to update. + /// * `sinksId` - Part of `sinkName`. See documentation of `projectsId`. + pub fn sinks_update(&self, request: LogSink, projects_id: &str, sinks_id: &str) -> ProjectSinkUpdateCall<'a, C, A> { + ProjectSinkUpdateCall { + hub: self.hub, + _request: request, + _projects_id: projects_id.to_string(), + _sinks_id: sinks_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 current index values for a log service. + /// + /// # Arguments + /// + /// * `projectsId` - Part of `serviceName`. The resource name of a log service whose service indexes are requested. Example: `"projects/my-project-id/logServices/appengine.googleapis.com"`. + /// * `logServicesId` - Part of `serviceName`. See documentation of `projectsId`. + pub fn log_services_indexes_list(&self, projects_id: &str, log_services_id: &str) -> ProjectLogServiceIndexeListCall<'a, C, A> { + ProjectLogServiceIndexeListCall { + hub: self.hub, + _projects_id: projects_id.to_string(), + _log_services_id: log_services_id.to_string(), + _page_token: Default::default(), + _page_size: Default::default(), + _index_prefix: Default::default(), + _depth: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Lists project sinks associated with a project. + /// + /// # Arguments + /// + /// * `projectsId` - Part of `projectName`. The project whose sinks are wanted. + pub fn sinks_list(&self, projects_id: &str) -> ProjectSinkListCall<'a, C, A> { + ProjectSinkListCall { + hub: self.hub, + _projects_id: projects_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 log services that have log entries in this project. + /// + /// # Arguments + /// + /// * `projectsId` - Part of `projectName`. The resource name of the project whose services are to be listed. + pub fn log_services_list(&self, projects_id: &str) -> ProjectLogServiceListCall<'a, C, A> { + ProjectLogServiceListCall { + hub: self.hub, + _projects_id: projects_id.to_string(), + _page_token: Default::default(), + _page_size: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Writes log entries to Cloud Logging. Each entry consists of a `LogEntry` object. You must fill in all the fields of the object, including one of the payload fields. You may supply a map, `commonLabels`, that holds default (key, value) data for the `entries[].metadata.labels` map in each entry, saving you the trouble of creating identical copies for each entry. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `projectsId` - Part of `logName`. The resource name of the log that will receive the log entries. /// * `logsId` - Part of `logName`. See documentation of `projectsId`. pub fn logs_entries_write(&self, request: WriteLogEntriesRequest, projects_id: &str, logs_id: &str) -> ProjectLogEntryWriteCall<'a, C, A> { ProjectLogEntryWriteCall { @@ -615,11 +901,11 @@ impl<'a, C, A> ProjectMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Deletes the specified log service sink. + /// Deletes a log service sink. After deletion, no new log entries are written to the destination. /// /// # Arguments /// - /// * `projectsId` - Part of `sinkName`. The name of the sink to delete. + /// * `projectsId` - Part of `sinkName`. The resource name of the log service sink to delete. /// * `logServicesId` - Part of `sinkName`. See documentation of `projectsId`. /// * `sinksId` - Part of `sinkName`. See documentation of `projectsId`. pub fn log_services_sinks_delete(&self, projects_id: &str, log_services_id: &str, sinks_id: &str) -> ProjectLogServiceSinkDeleteCall<'a, C, A> { @@ -636,22 +922,17 @@ impl<'a, C, A> ProjectMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Lists log service indexes associated with a log service. + /// Deletes a project sink. After deletion, no new log entries are written to the destination. /// /// # Arguments /// - /// * `projectsId` - Part of `serviceName`. A log service resource of the form `/projects/*/logServices/*`. The service indexes of the log service are returned. Example: `"/projects/myProj/logServices/appengine.googleapis.com"`. - /// * `logServicesId` - Part of `serviceName`. See documentation of `projectsId`. - pub fn log_services_indexes_list(&self, projects_id: &str, log_services_id: &str) -> ProjectLogServiceIndexeListCall<'a, C, A> { - ProjectLogServiceIndexeListCall { + /// * `projectsId` - Part of `sinkName`. The resource name of the project sink to delete. + /// * `sinksId` - Part of `sinkName`. See documentation of `projectsId`. + pub fn sinks_delete(&self, projects_id: &str, sinks_id: &str) -> ProjectSinkDeleteCall<'a, C, A> { + ProjectSinkDeleteCall { hub: self.hub, _projects_id: projects_id.to_string(), - _log_services_id: log_services_id.to_string(), - _page_token: Default::default(), - _page_size: Default::default(), - _log: Default::default(), - _index_prefix: Default::default(), - _depth: Default::default(), + _sinks_id: sinks_id.to_string(), _delegate: Default::default(), _scopes: Default::default(), _additional_params: Default::default(), @@ -660,11 +941,93 @@ impl<'a, C, A> ProjectMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Lists log sinks associated with the specified log. + /// Creates a log service sink. All log entries from a specified log service are written to the destination. /// /// # Arguments /// - /// * `projectsId` - Part of `logName`. The log for which to list sinks. + /// * `request` - No description provided. + /// * `projectsId` - Part of `serviceName`. The resource name of the log service to which the sink is bound. + /// * `logServicesId` - Part of `serviceName`. See documentation of `projectsId`. + pub fn log_services_sinks_create(&self, request: LogSink, projects_id: &str, log_services_id: &str) -> ProjectLogServiceSinkCreateCall<'a, C, A> { + ProjectLogServiceSinkCreateCall { + hub: self.hub, + _request: request, + _projects_id: projects_id.to_string(), + _log_services_id: log_services_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 log sink. After deletion, no new log entries are written to the destination. + /// + /// # Arguments + /// + /// * `projectsId` - Part of `sinkName`. The resource name of the log sink to delete. + /// * `logsId` - Part of `sinkName`. See documentation of `projectsId`. + /// * `sinksId` - Part of `sinkName`. See documentation of `projectsId`. + pub fn logs_sinks_delete(&self, projects_id: &str, logs_id: &str, sinks_id: &str) -> ProjectLogSinkDeleteCall<'a, C, A> { + ProjectLogSinkDeleteCall { + hub: self.hub, + _projects_id: projects_id.to_string(), + _logs_id: logs_id.to_string(), + _sinks_id: sinks_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 project sink. A logs filter determines which log entries are written to the destination. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `projectsId` - Part of `projectName`. The resource name of the project to which the sink is bound. + pub fn sinks_create(&self, request: LogSink, projects_id: &str) -> ProjectSinkCreateCall<'a, C, A> { + ProjectSinkCreateCall { + hub: self.hub, + _request: request, + _projects_id: projects_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 log service sink. + /// + /// # Arguments + /// + /// * `projectsId` - Part of `sinkName`. The resource name of the log service sink to return. + /// * `logServicesId` - Part of `sinkName`. See documentation of `projectsId`. + /// * `sinksId` - Part of `sinkName`. See documentation of `projectsId`. + pub fn log_services_sinks_get(&self, projects_id: &str, log_services_id: &str, sinks_id: &str) -> ProjectLogServiceSinkGetCall<'a, C, A> { + ProjectLogServiceSinkGetCall { + hub: self.hub, + _projects_id: projects_id.to_string(), + _log_services_id: log_services_id.to_string(), + _sinks_id: sinks_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Lists log sinks associated with a log. + /// + /// # Arguments + /// + /// * `projectsId` - Part of `logName`. The log whose sinks are wanted. For example, `"compute.google.com/syslog"`. /// * `logsId` - Part of `logName`. See documentation of `projectsId`. pub fn logs_sinks_list(&self, projects_id: &str, logs_id: &str) -> ProjectLogSinkListCall<'a, C, A> { ProjectLogSinkListCall { @@ -679,12 +1042,33 @@ impl<'a, C, A> ProjectMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Creates or updates the specified log sink resource. + /// Create or update the specified log metric resource. /// /// # Arguments /// /// * `request` - No description provided. - /// * `projectsId` - Part of `sinkName`. The name of the sink to update. + /// * `projectsId` - Part of `metricName`. The resource name of the metric to update. + /// * `metricsId` - Part of `metricName`. See documentation of `projectsId`. + pub fn metrics_update(&self, request: LogMetric, projects_id: &str, metrics_id: &str) -> ProjectMetricUpdateCall<'a, C, A> { + ProjectMetricUpdateCall { + hub: self.hub, + _request: request, + _projects_id: projects_id.to_string(), + _metrics_id: metrics_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 log sink. If the sink does not exist, it is created. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `projectsId` - Part of `sinkName`. The resource name of the sink to update. /// * `logsId` - Part of `sinkName`. See documentation of `projectsId`. /// * `sinksId` - Part of `sinkName`. See documentation of `projectsId`. pub fn logs_sinks_update(&self, request: LogSink, projects_id: &str, logs_id: &str, sinks_id: &str) -> ProjectLogSinkUpdateCall<'a, C, A> { @@ -702,19 +1086,17 @@ impl<'a, C, A> ProjectMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Creates the specified log service sink resource. + /// Deletes the specified log metric. /// /// # Arguments /// - /// * `request` - No description provided. - /// * `projectsId` - Part of `serviceName`. The name of the service in which to create a sink. - /// * `logServicesId` - Part of `serviceName`. See documentation of `projectsId`. - pub fn log_services_sinks_create(&self, request: LogSink, projects_id: &str, log_services_id: &str) -> ProjectLogServiceSinkCreateCall<'a, C, A> { - ProjectLogServiceSinkCreateCall { + /// * `projectsId` - Part of `metricName`. The resource name of the metric to delete. + /// * `metricsId` - Part of `metricName`. See documentation of `projectsId`. + pub fn metrics_delete(&self, projects_id: &str, metrics_id: &str) -> ProjectMetricDeleteCall<'a, C, A> { + ProjectMetricDeleteCall { hub: self.hub, - _request: request, _projects_id: projects_id.to_string(), - _log_services_id: log_services_id.to_string(), + _metrics_id: metrics_id.to_string(), _delegate: Default::default(), _scopes: Default::default(), _additional_params: Default::default(), @@ -723,74 +1105,11 @@ impl<'a, C, A> ProjectMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Deletes the specified log sink resource. + /// Lists log service sinks associated with a log service. /// /// # Arguments /// - /// * `projectsId` - Part of `sinkName`. The name of the sink to delete. - /// * `logsId` - Part of `sinkName`. See documentation of `projectsId`. - /// * `sinksId` - Part of `sinkName`. See documentation of `projectsId`. - pub fn logs_sinks_delete(&self, projects_id: &str, logs_id: &str, sinks_id: &str) -> ProjectLogSinkDeleteCall<'a, C, A> { - ProjectLogSinkDeleteCall { - hub: self.hub, - _projects_id: projects_id.to_string(), - _logs_id: logs_id.to_string(), - _sinks_id: sinks_id.to_string(), - _delegate: Default::default(), - _scopes: Default::default(), - _additional_params: Default::default(), - } - } - - /// Create a builder to help you perform the following task: - /// - /// Creates the specified log sink resource. - /// - /// # Arguments - /// - /// * `request` - No description provided. - /// * `projectsId` - Part of `logName`. The log in which to create a sink resource. - /// * `logsId` - Part of `logName`. See documentation of `projectsId`. - pub fn logs_sinks_create(&self, request: LogSink, projects_id: &str, logs_id: &str) -> ProjectLogSinkCreateCall<'a, C, A> { - ProjectLogSinkCreateCall { - hub: self.hub, - _request: request, - _projects_id: projects_id.to_string(), - _logs_id: logs_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 log service sink resource. - /// - /// # Arguments - /// - /// * `projectsId` - Part of `sinkName`. The name of the sink to return. - /// * `logServicesId` - Part of `sinkName`. See documentation of `projectsId`. - /// * `sinksId` - Part of `sinkName`. See documentation of `projectsId`. - pub fn log_services_sinks_get(&self, projects_id: &str, log_services_id: &str, sinks_id: &str) -> ProjectLogServiceSinkGetCall<'a, C, A> { - ProjectLogServiceSinkGetCall { - hub: self.hub, - _projects_id: projects_id.to_string(), - _log_services_id: log_services_id.to_string(), - _sinks_id: sinks_id.to_string(), - _delegate: Default::default(), - _scopes: Default::default(), - _additional_params: Default::default(), - } - } - - /// Create a builder to help you perform the following task: - /// - /// Lists log service sinks associated with the specified service. - /// - /// # Arguments - /// - /// * `projectsId` - Part of `serviceName`. The name of the service for which to list sinks. + /// * `projectsId` - Part of `serviceName`. The log service whose sinks are wanted. /// * `logServicesId` - Part of `serviceName`. See documentation of `projectsId`. pub fn log_services_sinks_list(&self, projects_id: &str, log_services_id: &str) -> ProjectLogServiceSinkListCall<'a, C, A> { ProjectLogServiceSinkListCall { @@ -805,17 +1124,17 @@ impl<'a, C, A> ProjectMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Deletes the specified log resource and all log entries contained in it. + /// List log metrics associated with the specified project. /// /// # Arguments /// - /// * `projectsId` - Part of `logName`. The log resource to delete. - /// * `logsId` - Part of `logName`. See documentation of `projectsId`. - pub fn logs_delete(&self, projects_id: &str, logs_id: &str) -> ProjectLogDeleteCall<'a, C, A> { - ProjectLogDeleteCall { + /// * `projectsId` - Part of `projectName`. The resource name for the project whose metrics are wanted. + pub fn metrics_list(&self, projects_id: &str) -> ProjectMetricListCall<'a, C, A> { + ProjectMetricListCall { hub: self.hub, _projects_id: projects_id.to_string(), - _logs_id: logs_id.to_string(), + _page_token: Default::default(), + _page_size: Default::default(), _delegate: Default::default(), _scopes: Default::default(), _additional_params: Default::default(), @@ -831,9 +1150,9 @@ impl<'a, C, A> ProjectMethods<'a, C, A> { // CallBuilders ### // ################# -/// Lists log services associated with log entries ingested for a project. +/// Deletes a log and all its log entries. The log will reappear if it receives new entries. /// -/// A builder for the *logServices.list* method supported by a *project* resource. +/// A builder for the *logs.delete* method supported by a *project* resource. /// It is not used directly, but through a `ProjectMethods` instance. /// /// # Example @@ -857,33 +1176,28 @@ impl<'a, C, A> ProjectMethods<'a, C, A> { /// // You can configure optional parameters by calling 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().log_services_list("projectsId") -/// .page_token("accusam") -/// .page_size(-8) -/// .log("justo") +/// let result = hub.projects().logs_delete("projectsId", "logsId") /// .doit(); /// # } /// ``` -pub struct ProjectLogServiceListCall<'a, C, A> +pub struct ProjectLogDeleteCall<'a, C, A> where C: 'a, A: 'a { hub: &'a Logging, _projects_id: String, - _page_token: Option, - _page_size: Option, - _log: Option, + _logs_id: String, _delegate: Option<&'a mut Delegate>, _additional_params: HashMap, _scopes: BTreeMap } -impl<'a, C, A> CallBuilder for ProjectLogServiceListCall<'a, C, A> {} +impl<'a, C, A> CallBuilder for ProjectLogDeleteCall<'a, C, A> {} -impl<'a, C, A> ProjectLogServiceListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { +impl<'a, C, A> ProjectLogDeleteCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { /// Perform the operation you have build so far. - pub fn doit(mut self) -> Result<(hyper::client::Response, ListLogServicesResponse)> { + pub fn doit(mut self) -> Result<(hyper::client::Response, Empty)> { use std::io::{Read, Seek}; use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; let mut dd = DefaultDelegate; @@ -891,20 +1205,12 @@ impl<'a, C, A> ProjectLogServiceListCall<'a, C, A> where C: BorrowMut d, None => &mut dd }; - dlg.begin(MethodInfo { id: "logging.projects.logServices.list", - http_method: hyper::method::Method::Get }); - let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + dlg.begin(MethodInfo { id: "logging.projects.logs.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); params.push(("projectsId", self._projects_id.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._log { - params.push(("log", value.to_string())); - } - for &field in ["alt", "projectsId", "pageToken", "pageSize", "log"].iter() { + params.push(("logsId", self._logs_id.to_string())); + for &field in ["alt", "projectsId", "logsId"].iter() { if self._additional_params.contains_key(field) { dlg.finished(false); return Err(Error::FieldClash(field)); @@ -916,12 +1222,12 @@ impl<'a, C, A> ProjectLogServiceListCall<'a, C, A> where C: BorrowMut = None; for &(name, ref value) in params.iter() { if name == param_name { @@ -932,8 +1238,547 @@ impl<'a, C, A> ProjectLogServiceListCall<'a, C, A> where C: BorrowMut = Vec::with_capacity(1); - for param_name in ["projectsId"].iter() { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["logsId", "projectsId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Part of `logName`. The resource name of the log to be deleted. + /// + /// Sets the *projects id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn projects_id(mut self, new_value: &str) -> ProjectLogDeleteCall<'a, C, A> { + self._projects_id = new_value.to_string(); + self + } + /// Part of `logName`. See documentation of `projectsId`. + /// + /// Sets the *logs id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn logs_id(mut self, new_value: &str) -> ProjectLogDeleteCall<'a, C, A> { + self._logs_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectLogDeleteCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> ProjectLogDeleteCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProjectLogDeleteCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Creates a log sink. All log entries for a specified log are written to the destination. +/// +/// A builder for the *logs.sinks.create* method supported by a *project* resource. +/// It is not used directly, but through a `ProjectMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_logging1_beta3 as logging1_beta3; +/// use logging1_beta3::LogSink; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use logging1_beta3::Logging; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Logging::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req = LogSink::default(); +/// +/// // You can configure optional parameters by calling 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().logs_sinks_create(req, "projectsId", "logsId") +/// .doit(); +/// # } +/// ``` +pub struct ProjectLogSinkCreateCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Logging, + _request: LogSink, + _projects_id: String, + _logs_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ProjectLogSinkCreateCall<'a, C, A> {} + +impl<'a, C, A> ProjectLogSinkCreateCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, LogSink)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "logging.projects.logs.sinks.create", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("projectsId", self._projects_id.to_string())); + params.push(("logsId", self._logs_id.to_string())); + for &field in ["alt", "projectsId", "logsId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://logging.googleapis.com/v1beta3/projects/{projectsId}/logs/{logsId}/sinks".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{projectsId}", "projectsId"), ("{logsId}", "logsId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["logsId", "projectsId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: LogSink) -> ProjectLogSinkCreateCall<'a, C, A> { + self._request = new_value; + self + } + /// Part of `logName`. The resource name of the log to which to the sink is bound. + /// + /// Sets the *projects id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn projects_id(mut self, new_value: &str) -> ProjectLogSinkCreateCall<'a, C, A> { + self._projects_id = new_value.to_string(); + self + } + /// Part of `logName`. See documentation of `projectsId`. + /// + /// Sets the *logs id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn logs_id(mut self, new_value: &str) -> ProjectLogSinkCreateCall<'a, C, A> { + self._logs_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectLogSinkCreateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> ProjectLogSinkCreateCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProjectLogSinkCreateCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Get the specified log metric resource. +/// +/// A builder for the *metrics.get* method supported by a *project* resource. +/// It is not used directly, but through a `ProjectMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_logging1_beta3 as logging1_beta3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use logging1_beta3::Logging; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Logging::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling 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().metrics_get("projectsId", "metricsId") +/// .doit(); +/// # } +/// ``` +pub struct ProjectMetricGetCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Logging, + _projects_id: String, + _metrics_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ProjectMetricGetCall<'a, C, A> {} + +impl<'a, C, A> ProjectMetricGetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, LogMetric)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "logging.projects.metrics.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("projectsId", self._projects_id.to_string())); + params.push(("metricsId", self._metrics_id.to_string())); + for &field in ["alt", "projectsId", "metricsId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://logging.googleapis.com/v1beta3/projects/{projectsId}/metrics/{metricsId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{projectsId}", "projectsId"), ("{metricsId}", "metricsId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["metricsId", "projectsId"].iter() { if let Some(index) = params.iter().position(|t| &t.0 == param_name) { indices_for_removal.push(index); } @@ -1020,35 +1865,24 @@ impl<'a, C, A> ProjectLogServiceListCall<'a, C, A> where C: BorrowMut ProjectLogServiceListCall<'a, C, A> { + pub fn projects_id(mut self, new_value: &str) -> ProjectMetricGetCall<'a, C, A> { self._projects_id = new_value.to_string(); self } - /// An opaque token, returned as `nextPageToken` by a prior `ListLogServices` operation. If `pageToken` is supplied, then the other fields of this request are ignored, and instead the previous `ListLogServices` operation is continued. + /// Part of `metricName`. See documentation of `projectsId`. /// - /// Sets the *page token* query property to the given value. - pub fn page_token(mut self, new_value: &str) -> ProjectLogServiceListCall<'a, C, A> { - self._page_token = Some(new_value.to_string()); - self - } - /// The maximum number of `LogService` objects to return in one operation. + /// Sets the *metrics id* path property to the given value. /// - /// Sets the *page size* query property to the given value. - pub fn page_size(mut self, new_value: i32) -> ProjectLogServiceListCall<'a, C, A> { - self._page_size = Some(new_value); - self - } - /// The name of the log resource whose services are to be listed. log for which to list services. When empty, all services are listed. - /// - /// Sets the *log* query property to the given value. - pub fn log(mut self, new_value: &str) -> ProjectLogServiceListCall<'a, C, A> { - self._log = Some(new_value.to_string()); + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn metrics_id(mut self, new_value: &str) -> ProjectMetricGetCall<'a, C, A> { + self._metrics_id = new_value.to_string(); self } /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong @@ -1057,7 +1891,7 @@ impl<'a, C, A> ProjectLogServiceListCall<'a, C, A> where C: BorrowMut ProjectLogServiceListCall<'a, C, A> { + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectMetricGetCall<'a, C, A> { self._delegate = Some(new_value); self } @@ -1074,15 +1908,17 @@ impl<'a, C, A> ProjectLogServiceListCall<'a, C, A> where C: BorrowMut(mut self, name: T, value: T) -> ProjectLogServiceListCall<'a, C, A> + pub fn param(mut self, name: T, value: T) -> ProjectMetricGetCall<'a, C, A> where T: AsRef { self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); self @@ -1099,7 +1935,7 @@ impl<'a, C, A> ProjectLogServiceListCall<'a, C, A> where C: BorrowMut(mut self, scope: T) -> ProjectLogServiceListCall<'a, C, A> + pub fn add_scope(mut self, scope: T) -> ProjectMetricGetCall<'a, C, A> where T: AsRef { self._scopes.insert(scope.as_ref().to_string(), ()); self @@ -1107,7 +1943,7 @@ impl<'a, C, A> ProjectLogServiceListCall<'a, C, A> where C: BorrowMut ProjectLogServiceListCall<'a, C, A> where C: BorrowMut ProjectLogListCall<'a, C, A> where C: BorrowMut, A } - /// Part of `projectName`. The project name for which to list the log resources. + /// Part of `projectName`. The resource name of the project whose logs are requested. If both `serviceName` and `serviceIndexPrefix` are empty, then all logs with entries in this project are listed. /// /// Sets the *projects id* path property to the given value. /// @@ -1311,14 +2147,14 @@ impl<'a, C, A> ProjectLogListCall<'a, C, A> where C: BorrowMut, A self._projects_id = new_value.to_string(); self } - /// A service name for which to list logs. Only logs containing entries whose metadata includes this service name are returned. If `serviceName` and `serviceIndexPrefix` are both empty, then all log names are returned. To list all log names, regardless of service, leave both the `serviceName` and `serviceIndexPrefix` empty. To list log names containing entries with a particular service name (or explicitly empty service name) set `serviceName` to the desired value and `serviceIndexPrefix` to `"/"`. + /// If not empty, this field must be a log service name such as `"compute.googleapis.com"`. Only logs associated with that that log service are listed. /// /// Sets the *service name* query property to the given value. pub fn service_name(mut self, new_value: &str) -> ProjectLogListCall<'a, C, A> { self._service_name = Some(new_value.to_string()); self } - /// A log service index prefix for which to list logs. Only logs containing entries whose metadata that includes these label values (associated with index keys) are returned. The prefix is a slash separated list of values, and need not specify all index labels. An empty index (or a single slash) matches all log service indexes. + /// The purpose of this field is to restrict the listed logs to those with entries of a certain kind. If `serviceName` is the name of a log service, then this field may contain values for the log service's indexes. Only logs that have entries whose indexes include the values are listed. The format for this field is `"/val1/val2.../valN"`, where `val1` is a value for the first index, `val2` for the second index, etc. An empty value (a single slash) for an index matches all values, and you can omit values for later indexes entirely. /// /// Sets the *service index prefix* query property to the given value. pub fn service_index_prefix(mut self, new_value: &str) -> ProjectLogListCall<'a, C, A> { @@ -1362,12 +2198,14 @@ impl<'a, C, A> ProjectLogListCall<'a, C, A> where C: BorrowMut, A /// * *bearer_token* (query-string) - OAuth bearer token. /// * *pp* (query-boolean) - Pretty-print response. /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). /// * *access_token* (query-string) - OAuth access token. /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. /// * *callback* (query-string) - JSONP /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). /// * *alt* (query-string) - Data format for response. /// * *$.xgafv* (query-string) - V1 error format. pub fn param(mut self, name: T, value: T) -> ProjectLogListCall<'a, C, A> @@ -1395,7 +2233,534 @@ impl<'a, C, A> ProjectLogListCall<'a, C, A> where C: BorrowMut, A } -/// Gets the specified log sink resource. +/// Create the specified log metric resource. +/// +/// A builder for the *metrics.create* method supported by a *project* resource. +/// It is not used directly, but through a `ProjectMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_logging1_beta3 as logging1_beta3; +/// use logging1_beta3::LogMetric; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use logging1_beta3::Logging; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Logging::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req = LogMetric::default(); +/// +/// // You can configure optional parameters by calling 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().metrics_create(req, "projectsId") +/// .doit(); +/// # } +/// ``` +pub struct ProjectMetricCreateCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Logging, + _request: LogMetric, + _projects_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ProjectMetricCreateCall<'a, C, A> {} + +impl<'a, C, A> ProjectMetricCreateCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, LogMetric)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "logging.projects.metrics.create", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("projectsId", self._projects_id.to_string())); + for &field in ["alt", "projectsId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://logging.googleapis.com/v1beta3/projects/{projectsId}/metrics".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{projectsId}", "projectsId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["projectsId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: LogMetric) -> ProjectMetricCreateCall<'a, C, A> { + self._request = new_value; + self + } + /// Part of `projectName`. The resource name of the project in which to create the metric. + /// + /// Sets the *projects id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn projects_id(mut self, new_value: &str) -> ProjectMetricCreateCall<'a, C, A> { + self._projects_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectMetricCreateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> ProjectMetricCreateCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProjectMetricCreateCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Gets a project sink. +/// +/// A builder for the *sinks.get* method supported by a *project* resource. +/// It is not used directly, but through a `ProjectMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_logging1_beta3 as logging1_beta3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use logging1_beta3::Logging; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Logging::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling 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().sinks_get("projectsId", "sinksId") +/// .doit(); +/// # } +/// ``` +pub struct ProjectSinkGetCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Logging, + _projects_id: String, + _sinks_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ProjectSinkGetCall<'a, C, A> {} + +impl<'a, C, A> ProjectSinkGetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, LogSink)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "logging.projects.sinks.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("projectsId", self._projects_id.to_string())); + params.push(("sinksId", self._sinks_id.to_string())); + for &field in ["alt", "projectsId", "sinksId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://logging.googleapis.com/v1beta3/projects/{projectsId}/sinks/{sinksId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{projectsId}", "projectsId"), ("{sinksId}", "sinksId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["sinksId", "projectsId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Part of `sinkName`. The resource name of the project sink to return. + /// + /// Sets the *projects id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn projects_id(mut self, new_value: &str) -> ProjectSinkGetCall<'a, C, A> { + self._projects_id = new_value.to_string(); + self + } + /// Part of `sinkName`. See documentation of `projectsId`. + /// + /// Sets the *sinks id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn sinks_id(mut self, new_value: &str) -> ProjectSinkGetCall<'a, C, A> { + self._sinks_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectSinkGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> ProjectSinkGetCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProjectSinkGetCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Gets a log sink. /// /// A builder for the *logs.sinks.get* method supported by a *project* resource. /// It is not used directly, but through a `ProjectMethods` instance. @@ -1573,7 +2938,7 @@ impl<'a, C, A> ProjectLogSinkGetCall<'a, C, A> where C: BorrowMut } - /// Part of `sinkName`. The name of the sink resource to return. + /// Part of `sinkName`. The resource name of the log sink to return. /// /// Sets the *projects id* path property to the given value. /// @@ -1626,12 +2991,14 @@ impl<'a, C, A> ProjectLogSinkGetCall<'a, C, A> where C: BorrowMut /// * *bearer_token* (query-string) - OAuth bearer token. /// * *pp* (query-boolean) - Pretty-print response. /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). /// * *access_token* (query-string) - OAuth access token. /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. /// * *callback* (query-string) - JSONP /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). /// * *alt* (query-string) - Data format for response. /// * *$.xgafv* (query-string) - V1 error format. pub fn param(mut self, name: T, value: T) -> ProjectLogSinkGetCall<'a, C, A> @@ -1659,7 +3026,7 @@ impl<'a, C, A> ProjectLogSinkGetCall<'a, C, A> where C: BorrowMut } -/// Creates or update the specified log service sink resource. +/// Updates a log service sink. If the sink does not exist, it is created. /// /// A builder for the *logServices.sinks.update* method supported by a *project* resource. /// It is not used directly, but through a `ProjectMethods` instance. @@ -1868,7 +3235,7 @@ impl<'a, C, A> ProjectLogServiceSinkUpdateCall<'a, C, A> where C: BorrowMut ProjectLogServiceSinkUpdateCall<'a, C, A> where C: BorrowMut(mut self, name: T, value: T) -> ProjectLogServiceSinkUpdateCall<'a, C, A> @@ -1954,7 +3323,1102 @@ impl<'a, C, A> ProjectLogServiceSinkUpdateCall<'a, C, A> where C: BorrowMut::default(), None); +/// # let mut hub = Logging::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req = LogSink::default(); +/// +/// // You can configure optional parameters by calling 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().sinks_update(req, "projectsId", "sinksId") +/// .doit(); +/// # } +/// ``` +pub struct ProjectSinkUpdateCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Logging, + _request: LogSink, + _projects_id: String, + _sinks_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ProjectSinkUpdateCall<'a, C, A> {} + +impl<'a, C, A> ProjectSinkUpdateCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, LogSink)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "logging.projects.sinks.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("projectsId", self._projects_id.to_string())); + params.push(("sinksId", self._sinks_id.to_string())); + for &field in ["alt", "projectsId", "sinksId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://logging.googleapis.com/v1beta3/projects/{projectsId}/sinks/{sinksId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{projectsId}", "projectsId"), ("{sinksId}", "sinksId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["sinksId", "projectsId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: LogSink) -> ProjectSinkUpdateCall<'a, C, A> { + self._request = new_value; + self + } + /// Part of `sinkName`. The resource name of the project sink to update. + /// + /// Sets the *projects id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn projects_id(mut self, new_value: &str) -> ProjectSinkUpdateCall<'a, C, A> { + self._projects_id = new_value.to_string(); + self + } + /// Part of `sinkName`. See documentation of `projectsId`. + /// + /// Sets the *sinks id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn sinks_id(mut self, new_value: &str) -> ProjectSinkUpdateCall<'a, C, A> { + self._sinks_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectSinkUpdateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> ProjectSinkUpdateCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProjectSinkUpdateCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Lists the current index values for a log service. +/// +/// A builder for the *logServices.indexes.list* method supported by a *project* resource. +/// It is not used directly, but through a `ProjectMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_logging1_beta3 as logging1_beta3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use logging1_beta3::Logging; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Logging::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling 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().log_services_indexes_list("projectsId", "logServicesId") +/// .page_token("aliquyam") +/// .page_size(-9) +/// .index_prefix("Lorem") +/// .depth(-75) +/// .doit(); +/// # } +/// ``` +pub struct ProjectLogServiceIndexeListCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Logging, + _projects_id: String, + _log_services_id: String, + _page_token: Option, + _page_size: Option, + _index_prefix: Option, + _depth: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ProjectLogServiceIndexeListCall<'a, C, A> {} + +impl<'a, C, A> ProjectLogServiceIndexeListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ListLogServiceIndexesResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "logging.projects.logServices.indexes.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((8 + self._additional_params.len())); + params.push(("projectsId", self._projects_id.to_string())); + params.push(("logServicesId", self._log_services_id.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._index_prefix { + params.push(("indexPrefix", value.to_string())); + } + if let Some(value) = self._depth { + params.push(("depth", value.to_string())); + } + for &field in ["alt", "projectsId", "logServicesId", "pageToken", "pageSize", "indexPrefix", "depth"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://logging.googleapis.com/v1beta3/projects/{projectsId}/logServices/{logServicesId}/indexes".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{projectsId}", "projectsId"), ("{logServicesId}", "logServicesId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["logServicesId", "projectsId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Part of `serviceName`. The resource name of a log service whose service indexes are requested. Example: `"projects/my-project-id/logServices/appengine.googleapis.com"`. + /// + /// Sets the *projects id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn projects_id(mut self, new_value: &str) -> ProjectLogServiceIndexeListCall<'a, C, A> { + self._projects_id = new_value.to_string(); + self + } + /// Part of `serviceName`. See documentation of `projectsId`. + /// + /// Sets the *log services id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn log_services_id(mut self, new_value: &str) -> ProjectLogServiceIndexeListCall<'a, C, A> { + self._log_services_id = new_value.to_string(); + self + } + /// An opaque token, returned as `nextPageToken` by a prior `ListLogServiceIndexes` operation. If `pageToken` is supplied, then the other fields of this request are ignored, and instead the previous `ListLogServiceIndexes` operation is continued. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> ProjectLogServiceIndexeListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// The maximum number of log service index resources to return in one operation. + /// + /// Sets the *page size* query property to the given value. + pub fn page_size(mut self, new_value: i32) -> ProjectLogServiceIndexeListCall<'a, C, A> { + self._page_size = Some(new_value); + self + } + /// Restricts the index values returned to be those with a specified prefix for each index key. This field has the form `"/prefix1/prefix2/..."`, in order corresponding to the `LogService indexKeys`. Non-empty prefixes must begin with `/`. For example, App Engine's two keys are the module ID and the version ID. Following is the effect of using various values for `indexPrefix`: + `"/Mod/"` retrieves `/Mod/10` and `/Mod/11` but not `/ModA/10`. + `"/Mod` retrieves `/Mod/10`, `/Mod/11` and `/ModA/10` but not `/XXX/33`. + `"/Mod/1"` retrieves `/Mod/10` and `/Mod/11` but not `/ModA/10`. + `"/Mod/10/"` retrieves `/Mod/10` only. + An empty prefix or `"/"` retrieves all values. + /// + /// Sets the *index prefix* query property to the given value. + pub fn index_prefix(mut self, new_value: &str) -> ProjectLogServiceIndexeListCall<'a, C, A> { + self._index_prefix = Some(new_value.to_string()); + self + } + /// A non-negative integer that limits the number of levels of the index hierarchy that are returned. If `depth` is 1 (default), only the first index key value is returned. If `depth` is 2, both primary and secondary key values are returned. If `depth` is 0, the depth is the number of slash-separators in the `indexPrefix` field, not counting a slash appearing as the last character of the prefix. If the `indexPrefix` field is empty, the default depth is 1. It is an error for `depth` to be any positive value less than the number of components in `indexPrefix`. + /// + /// Sets the *depth* query property to the given value. + pub fn depth(mut self, new_value: i32) -> ProjectLogServiceIndexeListCall<'a, C, A> { + self._depth = Some(new_value); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectLogServiceIndexeListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> ProjectLogServiceIndexeListCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProjectLogServiceIndexeListCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Lists project sinks associated with a project. +/// +/// A builder for the *sinks.list* method supported by a *project* resource. +/// It is not used directly, but through a `ProjectMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_logging1_beta3 as logging1_beta3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use logging1_beta3::Logging; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Logging::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling 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().sinks_list("projectsId") +/// .doit(); +/// # } +/// ``` +pub struct ProjectSinkListCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Logging, + _projects_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ProjectSinkListCall<'a, C, A> {} + +impl<'a, C, A> ProjectSinkListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ListSinksResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "logging.projects.sinks.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("projectsId", self._projects_id.to_string())); + for &field in ["alt", "projectsId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://logging.googleapis.com/v1beta3/projects/{projectsId}/sinks".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{projectsId}", "projectsId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["projectsId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Part of `projectName`. The project whose sinks are wanted. + /// + /// Sets the *projects id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn projects_id(mut self, new_value: &str) -> ProjectSinkListCall<'a, C, A> { + self._projects_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectSinkListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> ProjectSinkListCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProjectSinkListCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Lists the log services that have log entries in this project. +/// +/// A builder for the *logServices.list* method supported by a *project* resource. +/// It is not used directly, but through a `ProjectMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_logging1_beta3 as logging1_beta3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use logging1_beta3::Logging; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Logging::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling 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().log_services_list("projectsId") +/// .page_token("dolor") +/// .page_size(-39) +/// .doit(); +/// # } +/// ``` +pub struct ProjectLogServiceListCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Logging, + _projects_id: String, + _page_token: Option, + _page_size: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ProjectLogServiceListCall<'a, C, A> {} + +impl<'a, C, A> ProjectLogServiceListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ListLogServicesResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "logging.projects.logServices.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("projectsId", self._projects_id.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())); + } + for &field in ["alt", "projectsId", "pageToken", "pageSize"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://logging.googleapis.com/v1beta3/projects/{projectsId}/logServices".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{projectsId}", "projectsId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["projectsId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Part of `projectName`. The resource name of the project whose services are to be listed. + /// + /// Sets the *projects id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn projects_id(mut self, new_value: &str) -> ProjectLogServiceListCall<'a, C, A> { + self._projects_id = new_value.to_string(); + self + } + /// An opaque token, returned as `nextPageToken` by a prior `ListLogServices` operation. If `pageToken` is supplied, then the other fields of this request are ignored, and instead the previous `ListLogServices` operation is continued. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> ProjectLogServiceListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// The maximum number of `LogService` objects to return in one operation. + /// + /// Sets the *page size* query property to the given value. + pub fn page_size(mut self, new_value: i32) -> ProjectLogServiceListCall<'a, C, A> { + self._page_size = Some(new_value); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectLogServiceListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> ProjectLogServiceListCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProjectLogServiceListCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Writes log entries to Cloud Logging. Each entry consists of a `LogEntry` object. You must fill in all the fields of the object, including one of the payload fields. You may supply a map, `commonLabels`, that holds default (key, value) data for the `entries[].metadata.labels` map in each entry, saving you the trouble of creating identical copies for each entry. /// /// A builder for the *logs.entries.write* method supported by a *project* resource. /// It is not used directly, but through a `ProjectMethods` instance. @@ -2161,7 +4625,7 @@ impl<'a, C, A> ProjectLogEntryWriteCall<'a, C, A> where C: BorrowMut ProjectLogEntryWriteCall<'a, C, A> where C: BorrowMut(mut self, name: T, value: T) -> ProjectLogEntryWriteCall<'a, C, A> @@ -2237,7 +4703,7 @@ impl<'a, C, A> ProjectLogEntryWriteCall<'a, C, A> where C: BorrowMut ProjectLogServiceSinkDeleteCall<'a, C, A> where C: BorrowMut ProjectLogServiceSinkDeleteCall<'a, C, A> where C: BorrowMut(mut self, name: T, value: T) -> ProjectLogServiceSinkDeleteCall<'a, C, A> @@ -2501,9 +4969,9 @@ impl<'a, C, A> ProjectLogServiceSinkDeleteCall<'a, C, A> where C: BorrowMut ProjectLogServiceSinkDeleteCall<'a, C, A> where C: BorrowMut +pub struct ProjectSinkDeleteCall<'a, C, A> where C: 'a, A: 'a { hub: &'a Logging, _projects_id: String, - _log_services_id: String, - _page_token: Option, - _page_size: Option, - _log: Option, - _index_prefix: Option, - _depth: Option, + _sinks_id: String, _delegate: Option<&'a mut Delegate>, _additional_params: HashMap, _scopes: BTreeMap } -impl<'a, C, A> CallBuilder for ProjectLogServiceIndexeListCall<'a, C, A> {} +impl<'a, C, A> CallBuilder for ProjectSinkDeleteCall<'a, C, A> {} -impl<'a, C, A> ProjectLogServiceIndexeListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { +impl<'a, C, A> ProjectSinkDeleteCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { /// Perform the operation you have build so far. - pub fn doit(mut self) -> Result<(hyper::client::Response, ListLogServiceIndexesResponse)> { + pub fn doit(mut self) -> Result<(hyper::client::Response, Empty)> { use std::io::{Read, Seek}; use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; let mut dd = DefaultDelegate; @@ -2566,27 +5024,12 @@ impl<'a, C, A> ProjectLogServiceIndexeListCall<'a, C, A> where C: BorrowMut d, None => &mut dd }; - dlg.begin(MethodInfo { id: "logging.projects.logServices.indexes.list", - http_method: hyper::method::Method::Get }); - let mut params: Vec<(&str, String)> = Vec::with_capacity((9 + self._additional_params.len())); + dlg.begin(MethodInfo { id: "logging.projects.sinks.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); params.push(("projectsId", self._projects_id.to_string())); - params.push(("logServicesId", self._log_services_id.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._log { - params.push(("log", value.to_string())); - } - if let Some(value) = self._index_prefix { - params.push(("indexPrefix", value.to_string())); - } - if let Some(value) = self._depth { - params.push(("depth", value.to_string())); - } - for &field in ["alt", "projectsId", "logServicesId", "pageToken", "pageSize", "log", "indexPrefix", "depth"].iter() { + params.push(("sinksId", self._sinks_id.to_string())); + for &field in ["alt", "projectsId", "sinksId"].iter() { if self._additional_params.contains_key(field) { dlg.finished(false); return Err(Error::FieldClash(field)); @@ -2598,7 +5041,268 @@ impl<'a, C, A> ProjectLogServiceIndexeListCall<'a, C, A> where C: BorrowMut = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["sinksId", "projectsId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Part of `sinkName`. The resource name of the project sink to delete. + /// + /// Sets the *projects id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn projects_id(mut self, new_value: &str) -> ProjectSinkDeleteCall<'a, C, A> { + self._projects_id = new_value.to_string(); + self + } + /// Part of `sinkName`. See documentation of `projectsId`. + /// + /// Sets the *sinks id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn sinks_id(mut self, new_value: &str) -> ProjectSinkDeleteCall<'a, C, A> { + self._sinks_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectSinkDeleteCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> ProjectSinkDeleteCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProjectSinkDeleteCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Creates a log service sink. All log entries from a specified log service are written to the destination. +/// +/// A builder for the *logServices.sinks.create* method supported by a *project* resource. +/// It is not used directly, but through a `ProjectMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_logging1_beta3 as logging1_beta3; +/// use logging1_beta3::LogSink; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use logging1_beta3::Logging; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Logging::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req = LogSink::default(); +/// +/// // You can configure optional parameters by calling 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().log_services_sinks_create(req, "projectsId", "logServicesId") +/// .doit(); +/// # } +/// ``` +pub struct ProjectLogServiceSinkCreateCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Logging, + _request: LogSink, + _projects_id: String, + _log_services_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ProjectLogServiceSinkCreateCall<'a, C, A> {} + +impl<'a, C, A> ProjectLogServiceSinkCreateCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, LogSink)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "logging.projects.logServices.sinks.create", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("projectsId", self._projects_id.to_string())); + params.push(("logServicesId", self._log_services_id.to_string())); + for &field in ["alt", "projectsId", "logServicesId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://logging.googleapis.com/v1beta3/projects/{projectsId}/logServices/{logServicesId}/sinks".to_string(); if self._scopes.len() == 0 { self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); } @@ -2630,6 +5334,825 @@ impl<'a, C, A> ProjectLogServiceIndexeListCall<'a, C, A> where C: BorrowMut token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: LogSink) -> ProjectLogServiceSinkCreateCall<'a, C, A> { + self._request = new_value; + self + } + /// Part of `serviceName`. The resource name of the log service to which the sink is bound. + /// + /// Sets the *projects id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn projects_id(mut self, new_value: &str) -> ProjectLogServiceSinkCreateCall<'a, C, A> { + self._projects_id = new_value.to_string(); + self + } + /// Part of `serviceName`. See documentation of `projectsId`. + /// + /// Sets the *log services id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn log_services_id(mut self, new_value: &str) -> ProjectLogServiceSinkCreateCall<'a, C, A> { + self._log_services_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectLogServiceSinkCreateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> ProjectLogServiceSinkCreateCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProjectLogServiceSinkCreateCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Deletes a log sink. After deletion, no new log entries are written to the destination. +/// +/// A builder for the *logs.sinks.delete* method supported by a *project* resource. +/// It is not used directly, but through a `ProjectMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_logging1_beta3 as logging1_beta3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use logging1_beta3::Logging; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Logging::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling 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().logs_sinks_delete("projectsId", "logsId", "sinksId") +/// .doit(); +/// # } +/// ``` +pub struct ProjectLogSinkDeleteCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Logging, + _projects_id: String, + _logs_id: String, + _sinks_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ProjectLogSinkDeleteCall<'a, C, A> {} + +impl<'a, C, A> ProjectLogSinkDeleteCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Empty)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "logging.projects.logs.sinks.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("projectsId", self._projects_id.to_string())); + params.push(("logsId", self._logs_id.to_string())); + params.push(("sinksId", self._sinks_id.to_string())); + for &field in ["alt", "projectsId", "logsId", "sinksId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://logging.googleapis.com/v1beta3/projects/{projectsId}/logs/{logsId}/sinks/{sinksId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{projectsId}", "projectsId"), ("{logsId}", "logsId"), ("{sinksId}", "sinksId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + 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 ["sinksId", "logsId", "projectsId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Part of `sinkName`. The resource name of the log sink to delete. + /// + /// Sets the *projects id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn projects_id(mut self, new_value: &str) -> ProjectLogSinkDeleteCall<'a, C, A> { + self._projects_id = new_value.to_string(); + self + } + /// Part of `sinkName`. See documentation of `projectsId`. + /// + /// Sets the *logs id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn logs_id(mut self, new_value: &str) -> ProjectLogSinkDeleteCall<'a, C, A> { + self._logs_id = new_value.to_string(); + self + } + /// Part of `sinkName`. See documentation of `projectsId`. + /// + /// Sets the *sinks id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn sinks_id(mut self, new_value: &str) -> ProjectLogSinkDeleteCall<'a, C, A> { + self._sinks_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectLogSinkDeleteCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> ProjectLogSinkDeleteCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProjectLogSinkDeleteCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Creates a project sink. A logs filter determines which log entries are written to the destination. +/// +/// A builder for the *sinks.create* method supported by a *project* resource. +/// It is not used directly, but through a `ProjectMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_logging1_beta3 as logging1_beta3; +/// use logging1_beta3::LogSink; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use logging1_beta3::Logging; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Logging::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req = LogSink::default(); +/// +/// // You can configure optional parameters by calling 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().sinks_create(req, "projectsId") +/// .doit(); +/// # } +/// ``` +pub struct ProjectSinkCreateCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Logging, + _request: LogSink, + _projects_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ProjectSinkCreateCall<'a, C, A> {} + +impl<'a, C, A> ProjectSinkCreateCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, LogSink)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "logging.projects.sinks.create", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("projectsId", self._projects_id.to_string())); + for &field in ["alt", "projectsId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://logging.googleapis.com/v1beta3/projects/{projectsId}/sinks".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{projectsId}", "projectsId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["projectsId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: LogSink) -> ProjectSinkCreateCall<'a, C, A> { + self._request = new_value; + self + } + /// Part of `projectName`. The resource name of the project to which the sink is bound. + /// + /// Sets the *projects id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn projects_id(mut self, new_value: &str) -> ProjectSinkCreateCall<'a, C, A> { + self._projects_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectSinkCreateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> ProjectSinkCreateCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProjectSinkCreateCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Gets a log service sink. +/// +/// A builder for the *logServices.sinks.get* method supported by a *project* resource. +/// It is not used directly, but through a `ProjectMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_logging1_beta3 as logging1_beta3; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use logging1_beta3::Logging; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Logging::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling 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().log_services_sinks_get("projectsId", "logServicesId", "sinksId") +/// .doit(); +/// # } +/// ``` +pub struct ProjectLogServiceSinkGetCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Logging, + _projects_id: String, + _log_services_id: String, + _sinks_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ProjectLogServiceSinkGetCall<'a, C, A> {} + +impl<'a, C, A> ProjectLogServiceSinkGetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, LogSink)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "logging.projects.logServices.sinks.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("projectsId", self._projects_id.to_string())); + params.push(("logServicesId", self._log_services_id.to_string())); + params.push(("sinksId", self._sinks_id.to_string())); + for &field in ["alt", "projectsId", "logServicesId", "sinksId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://logging.googleapis.com/v1beta3/projects/{projectsId}/logServices/{logServicesId}/sinks/{sinksId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{projectsId}", "projectsId"), ("{logServicesId}", "logServicesId"), ("{sinksId}", "sinksId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + 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 ["sinksId", "logServicesId", "projectsId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + loop { @@ -2702,59 +6225,34 @@ impl<'a, C, A> ProjectLogServiceIndexeListCall<'a, C, A> where C: BorrowMut ProjectLogServiceIndexeListCall<'a, C, A> { + pub fn projects_id(mut self, new_value: &str) -> ProjectLogServiceSinkGetCall<'a, C, A> { self._projects_id = new_value.to_string(); self } - /// Part of `serviceName`. See documentation of `projectsId`. + /// Part of `sinkName`. See documentation of `projectsId`. /// /// Sets the *log services id* path property to the given value. /// /// Even though the property as already been set when instantiating this call, /// we provide this method for API completeness. - pub fn log_services_id(mut self, new_value: &str) -> ProjectLogServiceIndexeListCall<'a, C, A> { + pub fn log_services_id(mut self, new_value: &str) -> ProjectLogServiceSinkGetCall<'a, C, A> { self._log_services_id = new_value.to_string(); self } - /// An opaque token, returned as `nextPageToken` by a prior `ListLogServiceIndexes` operation. If `pageToken` is supplied, then the other fields of this request are ignored, and instead the previous `ListLogServiceIndexes` operation is continued. + /// Part of `sinkName`. See documentation of `projectsId`. /// - /// Sets the *page token* query property to the given value. - pub fn page_token(mut self, new_value: &str) -> ProjectLogServiceIndexeListCall<'a, C, A> { - self._page_token = Some(new_value.to_string()); - self - } - /// The maximum number of log service index resources to return in one operation. + /// Sets the *sinks id* path property to the given value. /// - /// Sets the *page size* query property to the given value. - pub fn page_size(mut self, new_value: i32) -> ProjectLogServiceIndexeListCall<'a, C, A> { - self._page_size = Some(new_value); - self - } - /// A log resource like `/projects/project_id/logs/log_name`, identifying the log for which to list service indexes. - /// - /// Sets the *log* query property to the given value. - pub fn log(mut self, new_value: &str) -> ProjectLogServiceIndexeListCall<'a, C, A> { - self._log = Some(new_value.to_string()); - self - } - /// Restricts the indexes returned to be those with a specified prefix. The prefix has the form `"/label_value/label_value/..."`, in order corresponding to the [`LogService indexKeys`][google.logging.v1.LogService.index_keys]. Non-empty prefixes must begin with `/` . Example prefixes: + `"/myModule/"` retrieves App Engine versions associated with `myModule`. The trailing slash terminates the value. + `"/myModule"` retrieves App Engine modules with names beginning with `myModule`. + `""` retrieves all indexes. - /// - /// Sets the *index prefix* query property to the given value. - pub fn index_prefix(mut self, new_value: &str) -> ProjectLogServiceIndexeListCall<'a, C, A> { - self._index_prefix = Some(new_value.to_string()); - self - } - /// A limit to the number of levels of the index hierarchy that are expanded. If `depth` is 0, it defaults to the level specified by the prefix field (the number of slash separators). The default empty prefix implies a `depth` of 1. It is an error for `depth` to be any non-zero value less than the number of components in `indexPrefix`. - /// - /// Sets the *depth* query property to the given value. - pub fn depth(mut self, new_value: i32) -> ProjectLogServiceIndexeListCall<'a, C, A> { - self._depth = Some(new_value); + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn sinks_id(mut self, new_value: &str) -> ProjectLogServiceSinkGetCall<'a, C, A> { + self._sinks_id = new_value.to_string(); self } /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong @@ -2763,7 +6261,7 @@ impl<'a, C, A> ProjectLogServiceIndexeListCall<'a, C, A> where C: BorrowMut ProjectLogServiceIndexeListCall<'a, C, A> { + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectLogServiceSinkGetCall<'a, C, A> { self._delegate = Some(new_value); self } @@ -2780,15 +6278,17 @@ impl<'a, C, A> ProjectLogServiceIndexeListCall<'a, C, A> where C: BorrowMut(mut self, name: T, value: T) -> ProjectLogServiceIndexeListCall<'a, C, A> + pub fn param(mut self, name: T, value: T) -> ProjectLogServiceSinkGetCall<'a, C, A> where T: AsRef { self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); self @@ -2805,7 +6305,7 @@ impl<'a, C, A> ProjectLogServiceIndexeListCall<'a, C, A> where C: BorrowMut(mut self, scope: T) -> ProjectLogServiceIndexeListCall<'a, C, A> + pub fn add_scope(mut self, scope: T) -> ProjectLogServiceSinkGetCall<'a, C, A> where T: AsRef { self._scopes.insert(scope.as_ref().to_string(), ()); self @@ -2813,7 +6313,7 @@ impl<'a, C, A> ProjectLogServiceIndexeListCall<'a, C, A> where C: BorrowMut ProjectLogSinkListCall<'a, C, A> where C: BorrowMut ProjectLogSinkListCall<'a, C, A> where C: BorrowMut(mut self, name: T, value: T) -> ProjectLogSinkListCall<'a, C, A> @@ -3065,7 +6567,292 @@ impl<'a, C, A> ProjectLogSinkListCall<'a, C, A> where C: BorrowMut::default(), None); +/// # let mut hub = Logging::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req = LogMetric::default(); +/// +/// // You can configure optional parameters by calling 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().metrics_update(req, "projectsId", "metricsId") +/// .doit(); +/// # } +/// ``` +pub struct ProjectMetricUpdateCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Logging, + _request: LogMetric, + _projects_id: String, + _metrics_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ProjectMetricUpdateCall<'a, C, A> {} + +impl<'a, C, A> ProjectMetricUpdateCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, LogMetric)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "logging.projects.metrics.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("projectsId", self._projects_id.to_string())); + params.push(("metricsId", self._metrics_id.to_string())); + for &field in ["alt", "projectsId", "metricsId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://logging.googleapis.com/v1beta3/projects/{projectsId}/metrics/{metricsId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{projectsId}", "projectsId"), ("{metricsId}", "metricsId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["metricsId", "projectsId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: LogMetric) -> ProjectMetricUpdateCall<'a, C, A> { + self._request = new_value; + self + } + /// Part of `metricName`. The resource name of the metric to update. + /// + /// Sets the *projects id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn projects_id(mut self, new_value: &str) -> ProjectMetricUpdateCall<'a, C, A> { + self._projects_id = new_value.to_string(); + self + } + /// Part of `metricName`. See documentation of `projectsId`. + /// + /// Sets the *metrics id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn metrics_id(mut self, new_value: &str) -> ProjectMetricUpdateCall<'a, C, A> { + self._metrics_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectMetricUpdateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> ProjectMetricUpdateCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProjectMetricUpdateCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Updates a log sink. If the sink does not exist, it is created. /// /// A builder for the *logs.sinks.update* method supported by a *project* resource. /// It is not used directly, but through a `ProjectMethods` instance. @@ -3274,7 +7061,7 @@ impl<'a, C, A> ProjectLogSinkUpdateCall<'a, C, A> where C: BorrowMut ProjectLogSinkUpdateCall<'a, C, A> where C: BorrowMut(mut self, name: T, value: T) -> ProjectLogSinkUpdateCall<'a, C, A> @@ -3360,292 +7149,9 @@ impl<'a, C, A> ProjectLogSinkUpdateCall<'a, C, A> where C: BorrowMut::default(), None); -/// # let mut hub = Logging::new(hyper::Client::new(), auth); -/// // As the method needs a request, you would usually fill it with the desired information -/// // into the respective structure. Some of the parts shown here might not be applicable ! -/// // Values shown here are possibly random and not representative ! -/// let mut req = LogSink::default(); -/// -/// // You can configure optional parameters by calling 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().log_services_sinks_create(req, "projectsId", "logServicesId") -/// .doit(); -/// # } -/// ``` -pub struct ProjectLogServiceSinkCreateCall<'a, C, A> - where C: 'a, A: 'a { - - hub: &'a Logging, - _request: LogSink, - _projects_id: String, - _log_services_id: String, - _delegate: Option<&'a mut Delegate>, - _additional_params: HashMap, - _scopes: BTreeMap -} - -impl<'a, C, A> CallBuilder for ProjectLogServiceSinkCreateCall<'a, C, A> {} - -impl<'a, C, A> ProjectLogServiceSinkCreateCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { - - - /// Perform the operation you have build so far. - pub fn doit(mut self) -> Result<(hyper::client::Response, LogSink)> { - use std::io::{Read, Seek}; - use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; - let mut dd = DefaultDelegate; - let mut dlg: &mut Delegate = match self._delegate { - Some(d) => d, - None => &mut dd - }; - dlg.begin(MethodInfo { id: "logging.projects.logServices.sinks.create", - http_method: hyper::method::Method::Post }); - let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); - params.push(("projectsId", self._projects_id.to_string())); - params.push(("logServicesId", self._log_services_id.to_string())); - for &field in ["alt", "projectsId", "logServicesId"].iter() { - if self._additional_params.contains_key(field) { - dlg.finished(false); - return Err(Error::FieldClash(field)); - } - } - for (name, value) in self._additional_params.iter() { - params.push((&name, value.clone())); - } - - params.push(("alt", "json".to_string())); - - let mut url = "https://logging.googleapis.com/v1beta3/projects/{projectsId}/logServices/{logServicesId}/sinks".to_string(); - if self._scopes.len() == 0 { - self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); - } - - for &(find_this, param_name) in [("{projectsId}", "projectsId"), ("{logServicesId}", "logServicesId")].iter() { - let mut replace_with: Option<&str> = None; - for &(name, ref value) in params.iter() { - if name == param_name { - replace_with = Some(value); - break; - } - } - url = url.replace(find_this, replace_with.expect("to find substitution value in params")); - } - { - let mut indices_for_removal: Vec = Vec::with_capacity(2); - for param_name in ["logServicesId", "projectsId"].iter() { - if let Some(index) = params.iter().position(|t| &t.0 == param_name) { - indices_for_removal.push(index); - } - } - for &index in indices_for_removal.iter() { - params.remove(index); - } - } - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); - let mut request_value_reader = - { - let mut value = json::value::to_value(&self._request); - remove_json_null_values(&mut value); - let mut dst = io::Cursor::new(Vec::with_capacity(128)); - json::to_writer(&mut dst, &value).unwrap(); - dst - }; - let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); - request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_token }); - request_value_reader.seek(io::SeekFrom::Start(0)).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) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()) - .header(ContentType(json_mime_type.clone())) - .header(ContentLength(request_size as u64)) - .body(&mut request_value_reader); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = { - let mut json_response = String::new(); - res.read_to_string(&mut json_response).unwrap(); - match json::from_str(&json_response) { - Ok(decoded) => (res, decoded), - Err(err) => { - dlg.response_json_decode_error(&json_response, &err); - return Err(Error::JsonDecodeError(json_response, err)); - } - } - }; - - dlg.finished(true); - return Ok(result_value) - } - } - } - } - - - /// - /// Sets the *request* property to the given value. - /// - /// Even though the property as already been set when instantiating this call, - /// we provide this method for API completeness. - pub fn request(mut self, new_value: LogSink) -> ProjectLogServiceSinkCreateCall<'a, C, A> { - self._request = new_value; - self - } - /// Part of `serviceName`. The name of the service in which to create a sink. - /// - /// Sets the *projects id* path property to the given value. - /// - /// Even though the property as already been set when instantiating this call, - /// we provide this method for API completeness. - pub fn projects_id(mut self, new_value: &str) -> ProjectLogServiceSinkCreateCall<'a, C, A> { - self._projects_id = new_value.to_string(); - self - } - /// Part of `serviceName`. See documentation of `projectsId`. - /// - /// Sets the *log services id* path property to the given value. - /// - /// Even though the property as already been set when instantiating this call, - /// we provide this method for API completeness. - pub fn log_services_id(mut self, new_value: &str) -> ProjectLogServiceSinkCreateCall<'a, C, A> { - self._log_services_id = new_value.to_string(); - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectLogServiceSinkCreateCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *bearer_token* (query-string) - OAuth bearer token. - /// * *pp* (query-boolean) - Pretty-print response. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *access_token* (query-string) - OAuth access token. - /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. - /// * *callback* (query-string) - JSONP - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *alt* (query-string) - Data format for response. - /// * *$.xgafv* (query-string) - V1 error format. - pub fn param(mut self, name: T, value: T) -> ProjectLogServiceSinkCreateCall<'a, C, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::CloudPlatform`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be - /// sufficient, a read-write scope will do as well. - pub fn add_scope(mut self, scope: T) -> ProjectLogServiceSinkCreateCall<'a, C, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().to_string(), ()); - self - } -} - - -/// Deletes the specified log sink resource. -/// -/// A builder for the *logs.sinks.delete* method supported by a *project* resource. +/// A builder for the *metrics.delete* method supported by a *project* resource. /// It is not used directly, but through a `ProjectMethods` instance. /// /// # Example @@ -3669,25 +7175,24 @@ impl<'a, C, A> ProjectLogServiceSinkCreateCall<'a, C, A> where C: BorrowMut +pub struct ProjectMetricDeleteCall<'a, C, A> where C: 'a, A: 'a { hub: &'a Logging, _projects_id: String, - _logs_id: String, - _sinks_id: String, + _metrics_id: String, _delegate: Option<&'a mut Delegate>, _additional_params: HashMap, _scopes: BTreeMap } -impl<'a, C, A> CallBuilder for ProjectLogSinkDeleteCall<'a, C, A> {} +impl<'a, C, A> CallBuilder for ProjectMetricDeleteCall<'a, C, A> {} -impl<'a, C, A> ProjectLogSinkDeleteCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { +impl<'a, C, A> ProjectMetricDeleteCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { /// Perform the operation you have build so far. @@ -3699,13 +7204,12 @@ impl<'a, C, A> ProjectLogSinkDeleteCall<'a, C, A> where C: BorrowMut d, None => &mut dd }; - dlg.begin(MethodInfo { id: "logging.projects.logs.sinks.delete", + dlg.begin(MethodInfo { id: "logging.projects.metrics.delete", http_method: hyper::method::Method::Delete }); - let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); params.push(("projectsId", self._projects_id.to_string())); - params.push(("logsId", self._logs_id.to_string())); - params.push(("sinksId", self._sinks_id.to_string())); - for &field in ["alt", "projectsId", "logsId", "sinksId"].iter() { + params.push(("metricsId", self._metrics_id.to_string())); + for &field in ["alt", "projectsId", "metricsId"].iter() { if self._additional_params.contains_key(field) { dlg.finished(false); return Err(Error::FieldClash(field)); @@ -3717,12 +7221,12 @@ impl<'a, C, A> ProjectLogSinkDeleteCall<'a, C, A> where C: BorrowMut = None; for &(name, ref value) in params.iter() { if name == param_name { @@ -3733,8 +7237,8 @@ impl<'a, C, A> ProjectLogSinkDeleteCall<'a, C, A> where C: BorrowMut = Vec::with_capacity(3); - for param_name in ["sinksId", "logsId", "projectsId"].iter() { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["metricsId", "projectsId"].iter() { if let Some(index) = params.iter().position(|t| &t.0 == param_name) { indices_for_removal.push(index); } @@ -3821,34 +7325,24 @@ impl<'a, C, A> ProjectLogSinkDeleteCall<'a, C, A> where C: BorrowMut ProjectLogSinkDeleteCall<'a, C, A> { + pub fn projects_id(mut self, new_value: &str) -> ProjectMetricDeleteCall<'a, C, A> { self._projects_id = new_value.to_string(); self } - /// Part of `sinkName`. See documentation of `projectsId`. + /// Part of `metricName`. See documentation of `projectsId`. /// - /// Sets the *logs id* path property to the given value. + /// Sets the *metrics id* path property to the given value. /// /// Even though the property as already been set when instantiating this call, /// we provide this method for API completeness. - pub fn logs_id(mut self, new_value: &str) -> ProjectLogSinkDeleteCall<'a, C, A> { - self._logs_id = new_value.to_string(); - self - } - /// Part of `sinkName`. See documentation of `projectsId`. - /// - /// Sets the *sinks id* path property to the given value. - /// - /// Even though the property as already been set when instantiating this call, - /// we provide this method for API completeness. - pub fn sinks_id(mut self, new_value: &str) -> ProjectLogSinkDeleteCall<'a, C, A> { - self._sinks_id = new_value.to_string(); + pub fn metrics_id(mut self, new_value: &str) -> ProjectMetricDeleteCall<'a, C, A> { + self._metrics_id = new_value.to_string(); self } /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong @@ -3857,7 +7351,7 @@ impl<'a, C, A> ProjectLogSinkDeleteCall<'a, C, A> where C: BorrowMut ProjectLogSinkDeleteCall<'a, C, A> { + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectMetricDeleteCall<'a, C, A> { self._delegate = Some(new_value); self } @@ -3874,15 +7368,17 @@ impl<'a, C, A> ProjectLogSinkDeleteCall<'a, C, A> where C: BorrowMut(mut self, name: T, value: T) -> ProjectLogSinkDeleteCall<'a, C, A> + pub fn param(mut self, name: T, value: T) -> ProjectMetricDeleteCall<'a, C, A> where T: AsRef { self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); self @@ -3899,7 +7395,7 @@ impl<'a, C, A> ProjectLogSinkDeleteCall<'a, C, A> where C: BorrowMut(mut self, scope: T) -> ProjectLogSinkDeleteCall<'a, C, A> + pub fn add_scope(mut self, scope: T) -> ProjectMetricDeleteCall<'a, C, A> where T: AsRef { self._scopes.insert(scope.as_ref().to_string(), ()); self @@ -3907,554 +7403,7 @@ impl<'a, C, A> ProjectLogSinkDeleteCall<'a, C, A> where C: BorrowMut::default(), None); -/// # let mut hub = Logging::new(hyper::Client::new(), auth); -/// // As the method needs a request, you would usually fill it with the desired information -/// // into the respective structure. Some of the parts shown here might not be applicable ! -/// // Values shown here are possibly random and not representative ! -/// let mut req = LogSink::default(); -/// -/// // You can configure optional parameters by calling 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().logs_sinks_create(req, "projectsId", "logsId") -/// .doit(); -/// # } -/// ``` -pub struct ProjectLogSinkCreateCall<'a, C, A> - where C: 'a, A: 'a { - - hub: &'a Logging, - _request: LogSink, - _projects_id: String, - _logs_id: String, - _delegate: Option<&'a mut Delegate>, - _additional_params: HashMap, - _scopes: BTreeMap -} - -impl<'a, C, A> CallBuilder for ProjectLogSinkCreateCall<'a, C, A> {} - -impl<'a, C, A> ProjectLogSinkCreateCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { - - - /// Perform the operation you have build so far. - pub fn doit(mut self) -> Result<(hyper::client::Response, LogSink)> { - use std::io::{Read, Seek}; - use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; - let mut dd = DefaultDelegate; - let mut dlg: &mut Delegate = match self._delegate { - Some(d) => d, - None => &mut dd - }; - dlg.begin(MethodInfo { id: "logging.projects.logs.sinks.create", - http_method: hyper::method::Method::Post }); - let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); - params.push(("projectsId", self._projects_id.to_string())); - params.push(("logsId", self._logs_id.to_string())); - for &field in ["alt", "projectsId", "logsId"].iter() { - if self._additional_params.contains_key(field) { - dlg.finished(false); - return Err(Error::FieldClash(field)); - } - } - for (name, value) in self._additional_params.iter() { - params.push((&name, value.clone())); - } - - params.push(("alt", "json".to_string())); - - let mut url = "https://logging.googleapis.com/v1beta3/projects/{projectsId}/logs/{logsId}/sinks".to_string(); - if self._scopes.len() == 0 { - self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); - } - - for &(find_this, param_name) in [("{projectsId}", "projectsId"), ("{logsId}", "logsId")].iter() { - let mut replace_with: Option<&str> = None; - for &(name, ref value) in params.iter() { - if name == param_name { - replace_with = Some(value); - break; - } - } - url = url.replace(find_this, replace_with.expect("to find substitution value in params")); - } - { - let mut indices_for_removal: Vec = Vec::with_capacity(2); - for param_name in ["logsId", "projectsId"].iter() { - if let Some(index) = params.iter().position(|t| &t.0 == param_name) { - indices_for_removal.push(index); - } - } - for &index in indices_for_removal.iter() { - params.remove(index); - } - } - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); - let mut request_value_reader = - { - let mut value = json::value::to_value(&self._request); - remove_json_null_values(&mut value); - let mut dst = io::Cursor::new(Vec::with_capacity(128)); - json::to_writer(&mut dst, &value).unwrap(); - dst - }; - let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); - request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_token }); - request_value_reader.seek(io::SeekFrom::Start(0)).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) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()) - .header(ContentType(json_mime_type.clone())) - .header(ContentLength(request_size as u64)) - .body(&mut request_value_reader); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = { - let mut json_response = String::new(); - res.read_to_string(&mut json_response).unwrap(); - match json::from_str(&json_response) { - Ok(decoded) => (res, decoded), - Err(err) => { - dlg.response_json_decode_error(&json_response, &err); - return Err(Error::JsonDecodeError(json_response, err)); - } - } - }; - - dlg.finished(true); - return Ok(result_value) - } - } - } - } - - - /// - /// Sets the *request* property to the given value. - /// - /// Even though the property as already been set when instantiating this call, - /// we provide this method for API completeness. - pub fn request(mut self, new_value: LogSink) -> ProjectLogSinkCreateCall<'a, C, A> { - self._request = new_value; - self - } - /// Part of `logName`. The log in which to create a sink resource. - /// - /// Sets the *projects id* path property to the given value. - /// - /// Even though the property as already been set when instantiating this call, - /// we provide this method for API completeness. - pub fn projects_id(mut self, new_value: &str) -> ProjectLogSinkCreateCall<'a, C, A> { - self._projects_id = new_value.to_string(); - self - } - /// Part of `logName`. See documentation of `projectsId`. - /// - /// Sets the *logs id* path property to the given value. - /// - /// Even though the property as already been set when instantiating this call, - /// we provide this method for API completeness. - pub fn logs_id(mut self, new_value: &str) -> ProjectLogSinkCreateCall<'a, C, A> { - self._logs_id = new_value.to_string(); - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectLogSinkCreateCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *bearer_token* (query-string) - OAuth bearer token. - /// * *pp* (query-boolean) - Pretty-print response. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *access_token* (query-string) - OAuth access token. - /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. - /// * *callback* (query-string) - JSONP - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *alt* (query-string) - Data format for response. - /// * *$.xgafv* (query-string) - V1 error format. - pub fn param(mut self, name: T, value: T) -> ProjectLogSinkCreateCall<'a, C, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::CloudPlatform`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be - /// sufficient, a read-write scope will do as well. - pub fn add_scope(mut self, scope: T) -> ProjectLogSinkCreateCall<'a, C, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().to_string(), ()); - self - } -} - - -/// Gets the specified log service sink resource. -/// -/// A builder for the *logServices.sinks.get* method supported by a *project* resource. -/// It is not used directly, but through a `ProjectMethods` instance. -/// -/// # Example -/// -/// Instantiate a resource method builder -/// -/// ```test_harness,no_run -/// # extern crate hyper; -/// # extern crate yup_oauth2 as oauth2; -/// # extern crate google_logging1_beta3 as logging1_beta3; -/// # #[test] fn egal() { -/// # use std::default::Default; -/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; -/// # use logging1_beta3::Logging; -/// -/// # let secret: ApplicationSecret = Default::default(); -/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, -/// # hyper::Client::new(), -/// # ::default(), None); -/// # let mut hub = Logging::new(hyper::Client::new(), auth); -/// // You can configure optional parameters by calling 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().log_services_sinks_get("projectsId", "logServicesId", "sinksId") -/// .doit(); -/// # } -/// ``` -pub struct ProjectLogServiceSinkGetCall<'a, C, A> - where C: 'a, A: 'a { - - hub: &'a Logging, - _projects_id: String, - _log_services_id: String, - _sinks_id: String, - _delegate: Option<&'a mut Delegate>, - _additional_params: HashMap, - _scopes: BTreeMap -} - -impl<'a, C, A> CallBuilder for ProjectLogServiceSinkGetCall<'a, C, A> {} - -impl<'a, C, A> ProjectLogServiceSinkGetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { - - - /// Perform the operation you have build so far. - pub fn doit(mut self) -> Result<(hyper::client::Response, LogSink)> { - use std::io::{Read, Seek}; - use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; - let mut dd = DefaultDelegate; - let mut dlg: &mut Delegate = match self._delegate { - Some(d) => d, - None => &mut dd - }; - dlg.begin(MethodInfo { id: "logging.projects.logServices.sinks.get", - http_method: hyper::method::Method::Get }); - let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); - params.push(("projectsId", self._projects_id.to_string())); - params.push(("logServicesId", self._log_services_id.to_string())); - params.push(("sinksId", self._sinks_id.to_string())); - for &field in ["alt", "projectsId", "logServicesId", "sinksId"].iter() { - if self._additional_params.contains_key(field) { - dlg.finished(false); - return Err(Error::FieldClash(field)); - } - } - for (name, value) in self._additional_params.iter() { - params.push((&name, value.clone())); - } - - params.push(("alt", "json".to_string())); - - let mut url = "https://logging.googleapis.com/v1beta3/projects/{projectsId}/logServices/{logServicesId}/sinks/{sinksId}".to_string(); - if self._scopes.len() == 0 { - self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); - } - - for &(find_this, param_name) in [("{projectsId}", "projectsId"), ("{logServicesId}", "logServicesId"), ("{sinksId}", "sinksId")].iter() { - let mut replace_with: Option<&str> = None; - for &(name, ref value) in params.iter() { - if name == param_name { - replace_with = Some(value); - 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 ["sinksId", "logServicesId", "projectsId"].iter() { - if let Some(index) = params.iter().position(|t| &t.0 == param_name) { - indices_for_removal.push(index); - } - } - for &index in indices_for_removal.iter() { - params.remove(index); - } - } - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_token }); - let mut req_result = { - let mut client = &mut *self.hub.client.borrow_mut(); - let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = { - let mut json_response = String::new(); - res.read_to_string(&mut json_response).unwrap(); - match json::from_str(&json_response) { - Ok(decoded) => (res, decoded), - Err(err) => { - dlg.response_json_decode_error(&json_response, &err); - return Err(Error::JsonDecodeError(json_response, err)); - } - } - }; - - dlg.finished(true); - return Ok(result_value) - } - } - } - } - - - /// Part of `sinkName`. The name of the sink to return. - /// - /// Sets the *projects id* path property to the given value. - /// - /// Even though the property as already been set when instantiating this call, - /// we provide this method for API completeness. - pub fn projects_id(mut self, new_value: &str) -> ProjectLogServiceSinkGetCall<'a, C, A> { - self._projects_id = new_value.to_string(); - self - } - /// Part of `sinkName`. See documentation of `projectsId`. - /// - /// Sets the *log services id* path property to the given value. - /// - /// Even though the property as already been set when instantiating this call, - /// we provide this method for API completeness. - pub fn log_services_id(mut self, new_value: &str) -> ProjectLogServiceSinkGetCall<'a, C, A> { - self._log_services_id = new_value.to_string(); - self - } - /// Part of `sinkName`. See documentation of `projectsId`. - /// - /// Sets the *sinks id* path property to the given value. - /// - /// Even though the property as already been set when instantiating this call, - /// we provide this method for API completeness. - pub fn sinks_id(mut self, new_value: &str) -> ProjectLogServiceSinkGetCall<'a, C, A> { - self._sinks_id = new_value.to_string(); - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectLogServiceSinkGetCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *bearer_token* (query-string) - OAuth bearer token. - /// * *pp* (query-boolean) - Pretty-print response. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *access_token* (query-string) - OAuth access token. - /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. - /// * *callback* (query-string) - JSONP - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *alt* (query-string) - Data format for response. - /// * *$.xgafv* (query-string) - V1 error format. - pub fn param(mut self, name: T, value: T) -> ProjectLogServiceSinkGetCall<'a, C, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::CloudPlatform`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be - /// sufficient, a read-write scope will do as well. - pub fn add_scope(mut self, scope: T) -> ProjectLogServiceSinkGetCall<'a, C, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().to_string(), ()); - self - } -} - - -/// Lists log service sinks associated with the specified service. +/// Lists log service sinks associated with a log service. /// /// A builder for the *logServices.sinks.list* method supported by a *project* resource. /// It is not used directly, but through a `ProjectMethods` instance. @@ -4630,7 +7579,7 @@ impl<'a, C, A> ProjectLogServiceSinkListCall<'a, C, A> where C: BorrowMut ProjectLogServiceSinkListCall<'a, C, A> where C: BorrowMut(mut self, name: T, value: T) -> ProjectLogServiceSinkListCall<'a, C, A> @@ -4706,9 +7657,9 @@ impl<'a, C, A> ProjectLogServiceSinkListCall<'a, C, A> where C: BorrowMut ProjectLogServiceSinkListCall<'a, C, A> where C: BorrowMut +pub struct ProjectMetricListCall<'a, C, A> where C: 'a, A: 'a { hub: &'a Logging, _projects_id: String, - _logs_id: String, + _page_token: Option, + _page_size: Option, _delegate: Option<&'a mut Delegate>, _additional_params: HashMap, _scopes: BTreeMap } -impl<'a, C, A> CallBuilder for ProjectLogDeleteCall<'a, C, A> {} +impl<'a, C, A> CallBuilder for ProjectMetricListCall<'a, C, A> {} -impl<'a, C, A> ProjectLogDeleteCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { +impl<'a, C, A> ProjectMetricListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { /// Perform the operation you have build so far. - pub fn doit(mut self) -> Result<(hyper::client::Response, Empty)> { + pub fn doit(mut self) -> Result<(hyper::client::Response, ListLogMetricsResponse)> { use std::io::{Read, Seek}; use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; let mut dd = DefaultDelegate; @@ -4761,12 +7715,17 @@ impl<'a, C, A> ProjectLogDeleteCall<'a, C, A> where C: BorrowMut, Some(d) => d, None => &mut dd }; - dlg.begin(MethodInfo { id: "logging.projects.logs.delete", - http_method: hyper::method::Method::Delete }); - let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + dlg.begin(MethodInfo { id: "logging.projects.metrics.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); params.push(("projectsId", self._projects_id.to_string())); - params.push(("logsId", self._logs_id.to_string())); - for &field in ["alt", "projectsId", "logsId"].iter() { + 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())); + } + for &field in ["alt", "projectsId", "pageToken", "pageSize"].iter() { if self._additional_params.contains_key(field) { dlg.finished(false); return Err(Error::FieldClash(field)); @@ -4778,12 +7737,12 @@ impl<'a, C, A> ProjectLogDeleteCall<'a, C, A> where C: BorrowMut, params.push(("alt", "json".to_string())); - let mut url = "https://logging.googleapis.com/v1beta3/projects/{projectsId}/logs/{logsId}".to_string(); + let mut url = "https://logging.googleapis.com/v1beta3/projects/{projectsId}/metrics".to_string(); if self._scopes.len() == 0 { self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); } - for &(find_this, param_name) in [("{projectsId}", "projectsId"), ("{logsId}", "logsId")].iter() { + for &(find_this, param_name) in [("{projectsId}", "projectsId")].iter() { let mut replace_with: Option<&str> = None; for &(name, ref value) in params.iter() { if name == param_name { @@ -4794,8 +7753,8 @@ impl<'a, C, A> ProjectLogDeleteCall<'a, C, A> where C: BorrowMut, url = url.replace(find_this, replace_with.expect("to find substitution value in params")); } { - let mut indices_for_removal: Vec = Vec::with_capacity(2); - for param_name in ["logsId", "projectsId"].iter() { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["projectsId"].iter() { if let Some(index) = params.iter().position(|t| &t.0 == param_name) { indices_for_removal.push(index); } @@ -4829,7 +7788,7 @@ impl<'a, C, A> ProjectLogDeleteCall<'a, C, A> where C: BorrowMut, access_token: token.access_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) + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) .header(UserAgent(self.hub._user_agent.clone())) .header(auth_header.clone()); @@ -4882,24 +7841,28 @@ impl<'a, C, A> ProjectLogDeleteCall<'a, C, A> where C: BorrowMut, } - /// Part of `logName`. The log resource to delete. + /// Part of `projectName`. The resource name for the project whose metrics are wanted. /// /// Sets the *projects id* path property to the given value. /// /// Even though the property as already been set when instantiating this call, /// we provide this method for API completeness. - pub fn projects_id(mut self, new_value: &str) -> ProjectLogDeleteCall<'a, C, A> { + pub fn projects_id(mut self, new_value: &str) -> ProjectMetricListCall<'a, C, A> { self._projects_id = new_value.to_string(); self } - /// Part of `logName`. See documentation of `projectsId`. + /// An opaque token, returned as `nextPageToken` by a prior `ListLogMetrics` operation. If `pageToken` is supplied, then the other fields of this request are ignored, and instead the previous `ListLogMetrics` operation is continued. /// - /// Sets the *logs id* path property to the given value. + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> ProjectMetricListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// The maximum number of `LogMetric` objects to return in one operation. /// - /// Even though the property as already been set when instantiating this call, - /// we provide this method for API completeness. - pub fn logs_id(mut self, new_value: &str) -> ProjectLogDeleteCall<'a, C, A> { - self._logs_id = new_value.to_string(); + /// Sets the *page size* query property to the given value. + pub fn page_size(mut self, new_value: i32) -> ProjectMetricListCall<'a, C, A> { + self._page_size = Some(new_value); self } /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong @@ -4908,7 +7871,7 @@ impl<'a, C, A> ProjectLogDeleteCall<'a, C, A> where C: BorrowMut, /// It should be used to handle progress information, and to implement a certain level of resilience. /// /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectLogDeleteCall<'a, C, A> { + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectMetricListCall<'a, C, A> { self._delegate = Some(new_value); self } @@ -4925,15 +7888,17 @@ impl<'a, C, A> ProjectLogDeleteCall<'a, C, A> where C: BorrowMut, /// * *bearer_token* (query-string) - OAuth bearer token. /// * *pp* (query-boolean) - Pretty-print response. /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). /// * *access_token* (query-string) - OAuth access token. /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. /// * *callback* (query-string) - JSONP /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). /// * *alt* (query-string) - Data format for response. /// * *$.xgafv* (query-string) - V1 error format. - pub fn param(mut self, name: T, value: T) -> ProjectLogDeleteCall<'a, C, A> + pub fn param(mut self, name: T, value: T) -> ProjectMetricListCall<'a, C, A> where T: AsRef { self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); self @@ -4950,7 +7915,7 @@ impl<'a, C, A> ProjectLogDeleteCall<'a, C, A> where C: BorrowMut, /// Usually there is more than one suitable scope to authorize an operation, some of which may /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be /// sufficient, a read-write scope will do as well. - pub fn add_scope(mut self, scope: T) -> ProjectLogDeleteCall<'a, C, A> + pub fn add_scope(mut self, scope: T) -> ProjectMetricListCall<'a, C, A> where T: AsRef { self._scopes.insert(scope.as_ref().to_string(), ()); self diff --git a/gen/logging2_beta1-cli/Cargo.toml b/gen/logging2_beta1-cli/Cargo.toml new file mode 100644 index 0000000000..a458190317 --- /dev/null +++ b/gen/logging2_beta1-cli/Cargo.toml @@ -0,0 +1,35 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-logging2_beta1-cli" +version = "0.3.2+20151007" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with logging (protocol v2beta1)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/logging2_beta1-cli" +homepage = "https://cloud.google.com/logging/docs/" +documentation = "http://byron.github.io/google-apis-rs/google_logging2_beta1_cli" +license = "MIT" +keywords = ["logging", "google", "cli"] + +[[bin]] +name = "logging2-beta1" + +[dependencies] +hyper = ">= 0.6.8" +mime = "0.1.0" +serde = ">= 0.6.0" +serde_json = ">= 0.6.0" +yup-oauth2 = "*" +strsim = "*" +yup-hyper-mock = ">=1.0.0" +clap = ">= 1.0.3" + +[build-dependencies] +syntex = { version = "*" } +serde_codegen = { version = "*" } + + +[dependencies.google-logging2_beta1] +path = "../logging2_beta1" diff --git a/gen/logging2_beta1-cli/LICENSE.md b/gen/logging2_beta1-cli/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/logging2_beta1-cli/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/logging2_beta1-cli/README.md b/gen/logging2_beta1-cli/README.md new file mode 100644 index 0000000000..349cc69433 --- /dev/null +++ b/gen/logging2_beta1-cli/README.md @@ -0,0 +1,107 @@ + +The `logging2-beta1` command-line interface *(CLI)* allows to use most features of the *Google logging* service from the comfort of your terminal. + +By default all output is printed to standard out, but flags can be set to direct it into a file independent of your shell's +capabilities. Errors will be printed to standard error, and cause the program's exit code to be non-zero. + +If data-structures are requested, these will be returned as pretty-printed JSON, to be useful as input to other tools. + +Everything else about the *logging* API can be found at the +[official documentation site](https://cloud.google.com/logging/docs/). + +# Downloads + +You can download the pre-compiled 64bit binaries for the following platforms: + +* ![icon](http://megaicons.net/static/img/icons_sizes/6/140/16/ubuntu-icon.png) [ubuntu](http://dl.byronimo.de/google.rs/cli/0.3.2/ubuntu/logging2-beta1.tar.gz) +* ![icon](http://hydra-media.cursecdn.com/wow.gamepedia.com/a/a2/Apple-icon-16x16.png?version=25ddd67ac3dd3b634478e3978b76cb74) [osx](http://dl.byronimo.de/google.rs/cli/0.3.2/osx/logging2-beta1.tar.gz) + +Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/logging2_beta1-cli). + +# Usage + +This documentation was generated from the *logging* API at revision *20151007*. The CLI is at version *0.3.2*. + +```bash +logging2-beta1 [options] + logging2-beta1 --help + +Configuration: + --config-dir + A directory into which we will store our persistent data. Defaults to + a user-writable directory that we will create during the first invocation. + [default: ~/.google-service-cli] + --debug + Output all server communication to standard error. `tx` and `rx` are placed + into the same stream. + --debug-auth + Output all communication related to authentication to standard error. `tx` + and `rx` are placed into the same stream. + +``` + +# Configuration + +The program will store all persistent data in the `~/.google-service-cli` directory in *JSON* files prefixed with `logging2-beta1-`. You can change the directory used to store configuration with the `--config-dir` flag on a per-invocation basis. + +More information about the various kinds of persistent data are given in the following paragraphs. + +# Authentication + +Most APIs require a user to authenticate any request. If this is the case, the [scope][scopes] determines the +set of permissions granted. The granularity of these is usually no more than *read-only* or *full-access*. + +If not set, the system will automatically select the smallest feasible scope, e.g. when invoking a +method that is read-only, it will ask only for a read-only scope. +You may use the `--scope` flag to specify a scope directly. +All applicable scopes are documented in the respective method's CLI documentation. + +The first time a scope is used, the user is asked for permission. Follow the instructions given +by the CLI to grant permissions, or to decline. + +If a scope was authenticated by the user, the respective information will be stored as *JSON* in the configuration +directory, e.g. `~/.google-service-cli/logging2-beta1-token-.json`. No manual management of these tokens +is necessary. + +To revoke granted authentication, please refer to the [official documentation][revoke-access]. + +# Application Secrets + +In order to allow any application to use Google services, it will need to be registered using the +[Google Developer Console][google-dev-console]. APIs the application may use are then enabled for it +one by one. Most APIs can be used for free and have a daily quota. + +To allow more comfortable usage of the CLI without forcing anyone to register an own application, the CLI +comes with a default application secret that is configured accordingly. This also means that heavy usage +all around the world may deplete the daily quota. + +You can workaround this limitation by putting your own secrets file at this location: +`~/.google-service-cli/logging2-beta1-secret.json`, assuming that the required *logging* API +was enabled for it. Such a secret file can be downloaded in the *Google Developer Console* at +*APIs & auth -> Credentials -> Download JSON* and used as is. + +Learn more about how to setup Google projects and enable APIs using the [official documentation][google-project-new]. + + +# Debugging + +Even though the CLI does its best to provide usable error messages, sometimes it might be desirable to know +what exactly led to a particular issue. This is done by allowing all client-server communication to be +output to standard error *as-is*. + +The `--debug` flag will print all client-server communication to standard error, whereas the `--debug-auth` flag +will cause all communication related to authentication to standard error. +If the `--debug` flag is set, error-results will be debug-printed, possibly yielding more information about the +issue at hand. + +You may consider redirecting standard error into a file for ease of use, e.g. `logging2-beta1 --debug [options] 2>debug.txt`. + + +[scopes]: https://developers.google.com/+/api/oauth#scopes +[revoke-access]: http://webapps.stackexchange.com/a/30849 +[google-dev-console]: https://console.developers.google.com/ +[google-project-new]: https://developers.google.com/console/help/new/ \ No newline at end of file diff --git a/gen/logging2_beta1-cli/mkdocs.yml b/gen/logging2_beta1-cli/mkdocs.yml new file mode 100644 index 0000000000..2d5ccd7f6c --- /dev/null +++ b/gen/logging2_beta1-cli/mkdocs.yml @@ -0,0 +1,16 @@ +site_name: logging v0.3.2+20151007 +site_url: http://byron.github.io/google-apis-rs/google-logging2_beta1-cli +site_description: Write integrating applications with bcore + +repo_url: https://github.com/Byron/google-apis-rs/tree/master/gen/logging2_beta1-cli + +docs_dir: docs +site_dir: build_html + +pages: +- ['index.md', 'Home'] + +theme: readthedocs + +copyright: Copyright © 2015, `Sebastian Thiel` + diff --git a/gen/logging2_beta1-cli/src/cmn.rs b/gen/logging2_beta1-cli/src/cmn.rs new file mode 100644 index 0000000000..8358f156fa --- /dev/null +++ b/gen/logging2_beta1-cli/src/cmn.rs @@ -0,0 +1,721 @@ +// COPY OF 'src/rust/cli/cmn.rs' +// DO NOT EDIT +use oauth2::{ApplicationSecret, ConsoleApplicationSecret, TokenStorage, Token}; +use serde_json as json; +use serde_json::value::Value; +use mime::Mime; +use clap::{App, SubCommand}; +use strsim; + +use std::fs; +use std::env; +use std::io; +use std::fmt; +use std::path::{Path, PathBuf}; +use std::str::FromStr; +use std::string::ToString; +use std::io::{Write, Read, stdout}; + +use std::default::Default; + +const FIELD_SEP: char = '.'; + + +pub enum ComplexType { + Pod, + Vec, + Map, +} + + // Null, + // Bool(bool), + // I64(i64), + // U64(u64), + // F64(f64), + // String(String), + +pub enum JsonType { + Boolean, + Int, + Uint, + Float, + String, +} + +pub struct JsonTypeInfo { + pub jtype: JsonType, + pub ctype: ComplexType, +} + +// Based on @erickt user comment. Thanks for the idea ! +// Remove all keys whose values are null from given value (changed in place) +pub fn remove_json_null_values(value: &mut Value) { + match *value { + Value::Object(ref mut map) => { + let mut for_removal = Vec::new(); + + for (key, mut value) in map.iter_mut() { + if value.is_null() { + for_removal.push(key.clone()); + } else { + remove_json_null_values(&mut value); + } + } + + for key in &for_removal { + map.remove(key); + } + } + _ => {} + } +} + +fn did_you_mean<'a>(v: &str, possible_values: &[&'a str]) -> Option<&'a str> { + + let mut candidate: Option<(f64, &str)> = None; + for pv in possible_values { + let confidence = strsim::jaro_winkler(v, pv); + if confidence > 0.8 && (candidate.is_none() || (candidate.as_ref().unwrap().0 < confidence)) { + candidate = Some((confidence, pv)); + } + } + match candidate { + None => None, + Some((_, candidate)) => Some(candidate), + } +} + +pub enum CallType { + Upload(UploadProtocol), + Standard, +} + +arg_enum!{ + pub enum UploadProtocol { + Simple, + Resumable + } +} + +impl AsRef for UploadProtocol { + fn as_ref(&self) -> &str { + match *self { + UploadProtocol::Simple => "simple", + UploadProtocol::Resumable => "resumable" + } + } +} + +impl AsRef for CallType { + fn as_ref(&self) -> &str { + match *self { + CallType::Upload(ref proto) => proto.as_ref(), + CallType::Standard => "standard-request" + } + } +} + +#[derive(Clone, Default)] +pub struct FieldCursor(Vec); + +impl ToString for FieldCursor { + fn to_string(&self) -> String { + self.0.join(".") + } +} + +impl From<&'static str> for FieldCursor { + fn from(value: &'static str) -> FieldCursor { + let mut res = FieldCursor::default(); + res.set(value).unwrap(); + res + } +} + +impl FieldCursor { + pub fn set(&mut self, value: &str) -> Result<(), CLIError> { + if value.len() == 0 { + return Err(CLIError::Field(FieldError::Empty)) + } + + let mut first_is_field_sep = false; + let mut char_count: usize = 0; + let mut last_c = FIELD_SEP; + let mut num_conscutive_field_seps = 0; + + let mut field = String::new(); + let mut fields = self.0.clone(); + + let push_field = |fs: &mut Vec, f: &mut String| { + if f.len() > 0 { + fs.push(f.clone()); + f.truncate(0); + } + }; + + for (cid, c) in value.chars().enumerate() { + char_count += 1; + + if c == FIELD_SEP { + if cid == 0 { + first_is_field_sep = true; + } + num_conscutive_field_seps += 1; + if cid > 0 && last_c == FIELD_SEP { + if fields.pop().is_none() { + return Err(CLIError::Field(FieldError::PopOnEmpty(value.to_string()))) + } + } else { + push_field(&mut fields, &mut field); + } + } else { + num_conscutive_field_seps = 0; + if cid == 1 { + if first_is_field_sep { + fields.truncate(0); + } + } + field.push(c); + } + + last_c = c; + } + + push_field(&mut fields, &mut field); + + if char_count == 1 && first_is_field_sep { + fields.truncate(0); + } + if char_count > 1 && num_conscutive_field_seps == 1 { + return Err(CLIError::Field(FieldError::TrailingFieldSep(value.to_string()))) + } + + self.0 = fields; + Ok(()) + } + + pub fn did_you_mean(value: &str, possible_values: &[&str]) -> Option { + if value.len() == 0 { + return None + } + + let mut last_c = FIELD_SEP; + + let mut field = String::new(); + let mut output = String::new(); + + let push_field = |fs: &mut String, f: &mut String| { + if f.len() > 0 { + fs.push_str( + match did_you_mean(&f, possible_values) { + Some(candidate) => candidate, + None => &f, + }); + f.truncate(0); + } + }; + + for (cid, c) in value.chars().enumerate() { + if c == FIELD_SEP { + if last_c != FIELD_SEP { + push_field(&mut output, &mut field); + } + output.push(c); + } else { + field.push(c); + } + + last_c = c; + } + + push_field(&mut output, &mut field); + + if &output == value { + None + } else { + Some(output) + } + } + + pub fn set_json_value(&self, mut object: &mut Value, + value: &str, type_info: JsonTypeInfo, + err: &mut InvalidOptionsError, + orig_cursor: &FieldCursor) { + assert!(self.0.len() > 0); + + for field in &self.0[..self.0.len()-1] { + let tmp = object; + object = + match *tmp { + Value::Object(ref mut mapping) => { + mapping.entry(field.to_owned()).or_insert( + Value::Object(Default::default()) + ) + }, + _ => panic!("We don't expect non-object Values here ...") + }; + } + + match *object { + Value::Object(ref mut mapping) => { + let field = &self.0[self.0.len()-1]; + let to_jval = + |value: &str, jtype: JsonType, err: &mut InvalidOptionsError| + -> Value { + match jtype { + JsonType::Boolean => + Value::Bool(arg_from_str(value, err, &field, "boolean")), + JsonType::Int => + Value::I64(arg_from_str(value, err, &field, "int")), + JsonType::Uint => + Value::U64(arg_from_str(value, err, &field, "uint")), + JsonType::Float => + Value::F64(arg_from_str(value, err, &field, "float")), + JsonType::String => + Value::String(value.to_owned()), + } + }; + + match type_info.ctype { + ComplexType::Pod => { + if mapping.insert(field.to_owned(), to_jval(value, type_info.jtype, err)).is_some() { + err.issues.push(CLIError::Field(FieldError::Duplicate(orig_cursor.to_string()))); + } + }, + ComplexType::Vec => { + match *mapping.entry(field.to_owned()) + .or_insert(Value::Array(Default::default())) { + Value::Array(ref mut values) => values.push(to_jval(value, type_info.jtype, err)), + _ => unreachable!() + } + }, + ComplexType::Map => { + let (key, value) = parse_kv_arg(value, err, true); + let jval = to_jval(value.unwrap_or(""), type_info.jtype, err); + + match *mapping.entry(field.to_owned()) + .or_insert(Value::Object(Default::default())) { + Value::Object(ref mut value_map) => { + if value_map.insert(key.to_owned(), jval).is_some() { + err.issues.push(CLIError::Field(FieldError::Duplicate(orig_cursor.to_string()))); + } + } + _ => unreachable!() + } + } + } + }, + _ => unreachable!() + } + } + + pub fn num_fields(&self) -> usize { + self.0.len() + } +} + +pub fn parse_kv_arg<'a>(kv: &'a str, err: &mut InvalidOptionsError, for_hashmap: bool) + -> (&'a str, Option<&'a str>) { + let mut add_err = || err.issues.push(CLIError::InvalidKeyValueSyntax(kv.to_string(),for_hashmap)); + match kv.find('=') { + None => { + add_err(); + return (kv, None) + }, + Some(pos) => { + let key = &kv[..pos]; + if kv.len() <= pos + 1 { + add_err(); + return (key, Some("")) + } + (key, Some(&kv[pos+1..])) + } + } +} + +pub fn calltype_from_str(name: &str, valid_protocols: Vec, err: &mut InvalidOptionsError) -> CallType { + CallType::Upload( + match UploadProtocol::from_str(name) { + Ok(up) => up, + Err(msg) => { + err.issues.push(CLIError::InvalidUploadProtocol(name.to_string(), valid_protocols)); + UploadProtocol::Simple + } + }) +} + +pub fn input_file_from_opts(file_path: &str, err: &mut InvalidOptionsError) -> Option { + match fs::File::open(file_path) { + Ok(f) => Some(f), + Err(io_err) => { + err.issues.push(CLIError::Input(InputError::IOError((file_path.to_string(), io_err)))); + None + } + } +} + +pub fn input_mime_from_opts(mime: &str, err: &mut InvalidOptionsError) -> Option { + match mime.parse() { + Ok(m) => Some(m), + Err(_) => { + err.issues.push(CLIError::Input(InputError::Mime(mime.to_string()))); + None + } + } +} + +pub fn writer_from_opts(arg: Option<&str>) -> Result, io::Error> { + let f = arg.unwrap_or("-"); + match f { + "-" => Ok(Box::new(stdout())), + _ => match fs::OpenOptions::new().create(true).write(true).open(f) { + Ok(f) => Ok(Box::new(f)), + Err(io_err) => Err(io_err), + } + } +} + + +pub fn arg_from_str<'a, T>(arg: &str, err: &mut InvalidOptionsError, + arg_name: &'a str, + arg_type: &'a str) -> T + where T: FromStr + Default, + ::Err: fmt::Display { + match FromStr::from_str(arg) { + Err(perr) => { + err.issues.push( + CLIError::ParseError(arg_name.to_owned(), arg_type.to_owned(), arg.to_string(), format!("{}", perr)) + ); + Default::default() + }, + Ok(v) => v, + } +} + +pub struct JsonTokenStorage { + pub program_name: &'static str, + pub db_dir: String, +} + +impl JsonTokenStorage { + fn path(&self, scope_hash: u64) -> PathBuf { + Path::new(&self.db_dir).join(&format!("{}-token-{}.json", self.program_name, scope_hash)) + } +} + +impl TokenStorage for JsonTokenStorage { + type Error = json::Error; + + // NOTE: logging might be interesting, currently we swallow all errors + fn set(&mut self, scope_hash: u64, _: &Vec<&str>, token: Option) -> Result<(), json::Error> { + match token { + None => { + match fs::remove_file(self.path(scope_hash)) { + Err(err) => + match err.kind() { + io::ErrorKind::NotFound => Ok(()), + _ => Err(json::Error::IoError(err)) + }, + Ok(_) => Ok(()), + } + } + Some(token) => { + match fs::OpenOptions::new().create(true).write(true).open(&self.path(scope_hash)) { + Ok(mut f) => { + match json::to_writer_pretty(&mut f, &token) { + Ok(_) => Ok(()), + Err(serde_err) => Err(serde_err), + } + }, + Err(io_err) => Err(json::Error::IoError(io_err)) + } + } + } + } + + fn get(&self, scope_hash: u64, _: &Vec<&str>) -> Result, json::Error> { + match fs::File::open(&self.path(scope_hash)) { + Ok(mut f) => { + match json::de::from_reader(f) { + Ok(token) => Ok(Some(token)), + Err(err) => Err(err), + } + }, + Err(io_err) => { + match io_err.kind() { + io::ErrorKind::NotFound => Ok(None), + _ => Err(json::Error::IoError(io_err)) + } + } + } + } +} + + +#[derive(Debug)] +pub enum ApplicationSecretError { + DecoderError((String, json::Error)), + FormatError(String), +} + +impl fmt::Display for ApplicationSecretError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + ApplicationSecretError::DecoderError((ref path, ref err)) + => writeln!(f, "Could not decode file at '{}' with error: {}.", + path, err), + ApplicationSecretError::FormatError(ref path) + => writeln!(f, "'installed' field is unset in secret file at '{}'.", + path), + } + } +} + +#[derive(Debug)] +pub enum ConfigurationError { + DirectoryCreationFailed((String, io::Error)), + DirectoryUnset, + HomeExpansionFailed(String), + Secret(ApplicationSecretError), + IOError((String, io::Error)), +} + +impl fmt::Display for ConfigurationError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + ConfigurationError::DirectoryCreationFailed((ref dir, ref err)) + => writeln!(f, "Directory '{}' could not be created with error: {}.", dir, err), + ConfigurationError::DirectoryUnset + => writeln!(f, "--config-dir was unset or empty."), + ConfigurationError::HomeExpansionFailed(ref dir) + => writeln!(f, "Couldn't find HOME directory of current user, failed to expand '{}'.", dir), + ConfigurationError::Secret(ref err) + => writeln!(f, "Secret -> {}", err), + ConfigurationError::IOError((ref path, ref err)) + => writeln!(f, "IO operation failed on path '{}' with error: {}.", path, err), + } + } +} + +#[derive(Debug)] +pub enum InputError { + IOError((String, io::Error)), + Mime(String), +} + +impl fmt::Display for InputError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + InputError::IOError((ref file_path, ref io_err)) + => writeln!(f, "Failed to open '{}' for reading with error: {}.", file_path, io_err), + InputError::Mime(ref mime) + => writeln!(f, "'{}' is not a known mime-type.", mime), + } + } +} + +#[derive(Debug)] +pub enum FieldError { + PopOnEmpty(String), + TrailingFieldSep(String), + Unknown(String, Option, Option), + Duplicate(String), + Empty, +} + + +impl fmt::Display for FieldError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + FieldError::PopOnEmpty(ref field) + => writeln!(f, "'{}': Cannot move up on empty field cursor.", field), + FieldError::TrailingFieldSep(ref field) + => writeln!(f, "'{}': Single field separator may not be last character.", field), + FieldError::Unknown(ref field, ref suggestion, ref value) => { + let suffix = + match *suggestion { + Some(ref s) => { + let kv = + match *value { + Some(ref v) => format!("{}={}", s, v), + None => s.clone(), + }; + format!(" Did you mean '{}' ?", kv) + }, + None => String::new(), + }; + writeln!(f, "Field '{}' does not exist.{}", field, suffix) + }, + FieldError::Duplicate(ref cursor) + => writeln!(f, "Value at '{}' was already set", cursor), + FieldError::Empty + => writeln!(f, "Field names must not be empty."), + } + } +} + + +#[derive(Debug)] +pub enum CLIError { + Configuration(ConfigurationError), + ParseError(String, String, String, String), + UnknownParameter(String, Vec<&'static str>), + InvalidUploadProtocol(String, Vec), + InvalidKeyValueSyntax(String, bool), + Input(InputError), + Field(FieldError), + MissingCommandError, + MissingMethodError(String), +} + +impl fmt::Display for CLIError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + CLIError::Configuration(ref err) => write!(f, "Configuration -> {}", err), + CLIError::Input(ref err) => write!(f, "Input -> {}", err), + CLIError::Field(ref err) => write!(f, "Field -> {}", err), + CLIError::InvalidUploadProtocol(ref proto_name, ref valid_names) + => writeln!(f, "'{}' is not a valid upload protocol. Choose from one of {}.", proto_name, valid_names.join(", ")), + CLIError::ParseError(ref arg_name, ref type_name, ref value, ref err_desc) + => writeln!(f, "Failed to parse argument '{}' with value '{}' as {} with error: {}.", + arg_name, value, type_name, err_desc), + CLIError::UnknownParameter(ref param_name, ref possible_values) => { + let mut suffix = + match did_you_mean(param_name, &possible_values) { + Some(v) => format!(" Did you mean '{}' ?", v), + None => String::new(), + }; + write!(f, "Parameter '{}' is unknown.{}\n", param_name, suffix) + }, + CLIError::InvalidKeyValueSyntax(ref kv, is_hashmap) => { + let hashmap_info = if is_hashmap { "hashmap " } else { "" }; + writeln!(f, "'{}' does not match {}pattern =.", kv, hashmap_info) + }, + CLIError::MissingCommandError => writeln!(f, "Please specify the main sub-command."), + CLIError::MissingMethodError(ref cmd) => writeln!(f, "Please specify the method to call on the '{}' command.", cmd), + } + } +} + +#[derive(Debug)] +pub struct InvalidOptionsError { + pub issues: Vec, + pub exit_code: i32, +} + +impl fmt::Display for InvalidOptionsError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + for issue in &self.issues { + try!(issue.fmt(f)); + } + Ok(()) + } +} + +impl InvalidOptionsError { + pub fn single(err: CLIError, exit_code: i32) -> InvalidOptionsError { + InvalidOptionsError { + issues: vec![err], + exit_code: exit_code, + } + } + + pub fn new() -> InvalidOptionsError { + InvalidOptionsError { + issues: Vec::new(), + exit_code: 1, + } + } +} + +pub fn assure_config_dir_exists(dir: &str) -> Result { + let trdir = dir.trim(); + if trdir.len() == 0 { + return Err(CLIError::Configuration(ConfigurationError::DirectoryUnset)) + } + + let expanded_config_dir = + if trdir.as_bytes()[0] == b'~' { + match env::var("HOME").ok().or(env::var("UserProfile").ok()) { + None => return Err(CLIError::Configuration(ConfigurationError::HomeExpansionFailed(trdir.to_string()))), + Some(mut user) => { + user.push_str(&trdir[1..]); + user + } + } + } else { + trdir.to_string() + }; + + if let Err(err) = fs::create_dir(&expanded_config_dir) { + if err.kind() != io::ErrorKind::AlreadyExists { + return Err(CLIError::Configuration( + ConfigurationError::DirectoryCreationFailed((expanded_config_dir, err)))) + } + } + + Ok(expanded_config_dir) +} + +pub fn application_secret_from_directory(dir: &str, + secret_basename: &str, + json_console_secret: &str) + -> Result { + let secret_path = Path::new(dir).join(secret_basename); + let secret_str = || secret_path.as_path().to_str().unwrap().to_string(); + let secret_io_error = |io_err: io::Error| { + Err(CLIError::Configuration(ConfigurationError::IOError( + (secret_str(), io_err) + ))) + }; + + for _ in 0..2 { + match fs::File::open(&secret_path) { + Err(mut err) => { + if err.kind() == io::ErrorKind::NotFound { + // Write our built-in one - user may adjust the written file at will + + err = match fs::OpenOptions::new().create(true).write(true).open(&secret_path) { + Err(cfe) => cfe, + Ok(mut f) => { + // Assure we convert 'ugly' json string into pretty one + let console_secret: ConsoleApplicationSecret + = json::from_str(json_console_secret).unwrap(); + match json::to_writer_pretty(&mut f, &console_secret) { + Err(serde_err) => match serde_err { + json::Error::IoError(err) => err, + _ => panic!("Unexpected serde error: {:#?}", serde_err) + }, + Ok(_) => continue, + } + } + }; + // fall through to IO error handling + } + return secret_io_error(err) + }, + Ok(mut f) => { + match json::de::from_reader::<_, ConsoleApplicationSecret>(f) { + Err(json::Error::IoError(err)) => + return secret_io_error(err), + Err(json_err) => + return Err(CLIError::Configuration( + ConfigurationError::Secret( + ApplicationSecretError::DecoderError( + (secret_str(), json_err) + )))), + Ok(console_secret) => + match console_secret.installed { + Some(secret) => return Ok(secret), + None => return Err( + CLIError::Configuration( + ConfigurationError::Secret( + ApplicationSecretError::FormatError(secret_str()) + ))) + }, + } + } + } + } + unreachable!(); +} diff --git a/gen/logging2_beta1-cli/src/main.rs b/gen/logging2_beta1-cli/src/main.rs new file mode 100644 index 0000000000..9c3d85703b --- /dev/null +++ b/gen/logging2_beta1-cli/src/main.rs @@ -0,0 +1,231 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/cli/main.rs.mako' +// DO NOT EDIT ! +#![allow(unused_variables, unused_imports, dead_code, unused_mut)] + +#[macro_use] +extern crate clap; +extern crate yup_oauth2 as oauth2; +extern crate yup_hyper_mock as mock; +extern crate serde; +extern crate serde_json; +extern crate hyper; +extern crate mime; +extern crate strsim; +extern crate google_logging2_beta1 as api; + +use std::env; +use std::io::{self, Write}; +use clap::{App, SubCommand, Arg}; + +mod cmn; + +use cmn::{InvalidOptionsError, CLIError, JsonTokenStorage, arg_from_str, writer_from_opts, parse_kv_arg, + input_file_from_opts, input_mime_from_opts, FieldCursor, FieldError, CallType, UploadProtocol, + calltype_from_str, remove_json_null_values, ComplexType, JsonType, JsonTypeInfo}; + +use std::default::Default; +use std::str::FromStr; + +use oauth2::{Authenticator, DefaultAuthenticatorDelegate}; +use serde_json as json; +use clap::ArgMatches; + +enum DoitError { + IoError(String, io::Error), + ApiError(api::Error), +} + +struct Engine<'n, 'a> { + opt: ArgMatches<'n, 'a>, + hub: api::Logging>, + gp: Vec<&'static str>, + gpm: Vec<(&'static str, &'static str)>, +} + + +impl<'n, 'a> Engine<'n, 'a> { + fn _doit(&self, dry_run: bool) -> Result, Option> { + let mut err = InvalidOptionsError::new(); + let mut call_result: Result<(), DoitError> = Ok(()); + let mut err_opt: Option = None; + match self.opt.subcommand() { + _ => { + err.issues.push(CLIError::MissingCommandError); + writeln!(io::stderr(), "{}\n", self.opt.usage()).ok(); + } + } + + if dry_run { + if err.issues.len() > 0 { + err_opt = Some(err); + } + Err(err_opt) + } else { + Ok(call_result) + } + } + + // Please note that this call will fail if any part of the opt can't be handled + fn new(opt: ArgMatches<'a, 'n>) -> Result, InvalidOptionsError> { + let (config_dir, secret) = { + let config_dir = match cmn::assure_config_dir_exists(opt.value_of("folder").unwrap_or("~/.google-service-cli")) { + Err(e) => return Err(InvalidOptionsError::single(e, 3)), + Ok(p) => p, + }; + + match cmn::application_secret_from_directory(&config_dir, "logging2-beta1-secret.json", + "{\"installed\":{\"auth_uri\":\"https://accounts.google.com/o/oauth2/auth\",\"client_secret\":\"hCsslbCUyfehWMmbkG8vTYxG\",\"token_uri\":\"https://accounts.google.com/o/oauth2/token\",\"client_email\":\"\",\"redirect_uris\":[\"urn:ietf:wg:oauth:2.0:oob\",\"oob\"],\"client_x509_cert_url\":\"\",\"client_id\":\"620010449518-9ngf7o4dhs0dka470npqvor6dc5lqb9b.apps.googleusercontent.com\",\"auth_provider_x509_cert_url\":\"https://www.googleapis.com/oauth2/v1/certs\"}}") { + Ok(secret) => (config_dir, secret), + Err(e) => return Err(InvalidOptionsError::single(e, 4)) + } + }; + + let auth = Authenticator::new( &secret, DefaultAuthenticatorDelegate, + if opt.is_present("debug-auth") { + hyper::Client::with_connector(mock::TeeConnector { + connector: hyper::net::HttpsConnector::::default() + }) + } else { + hyper::Client::new() + }, + JsonTokenStorage { + program_name: "logging2-beta1", + db_dir: config_dir.clone(), + }, None); + + let client = + if opt.is_present("debug") { + hyper::Client::with_connector(mock::TeeConnector { + connector: hyper::net::HttpsConnector::::default() + }) + } else { + hyper::Client::new() + }; + let engine = Engine { + opt: opt, + hub: api::Logging::new(client, auth), + gp: vec!["$-xgafv", "access-token", "alt", "bearer-token", "callback", "fields", "key", "oauth-token", "pp", "pretty-print", "quota-user", "upload-type", "upload-protocol"], + gpm: vec![ + ("$-xgafv", "$.xgafv"), + ("access-token", "access_token"), + ("bearer-token", "bearer_token"), + ("oauth-token", "oauth_token"), + ("pretty-print", "prettyPrint"), + ("quota-user", "quotaUser"), + ("upload-type", "uploadType"), + ("upload-protocol", "upload_protocol"), + ] + }; + + match engine._doit(true) { + Err(Some(err)) => Err(err), + Err(None) => Ok(engine), + Ok(_) => unreachable!(), + } + } + + fn doit(&self) -> Result<(), DoitError> { + match self._doit(false) { + Ok(res) => res, + Err(_) => unreachable!(), + } + } +} + +fn main() { + let mut exit_status = 0i32; + let arg_data = [ + ]; + + let mut app = App::new("logging2-beta1") + .author("Sebastian Thiel ") + .version("0.3.2+20151007") + .about("Google Cloud Logging API lets you create logs, ingest log entries, and manage log sinks.") + .after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_logging2_beta1_cli") + .arg(Arg::with_name("folder") + .long("config-dir") + .help("A directory into which we will store our persistent data. Defaults to a user-writable directory that we will create during the first invocation.[default: ~/.google-service-cli") + .multiple(false) + .takes_value(true)) + .arg(Arg::with_name("debug") + .long("debug") + .help("Output all server communication to standard error. `tx` and `rx` are placed into the same stream.") + .multiple(false) + .takes_value(false)) + .arg(Arg::with_name("debug-auth") + .long("debug-auth") + .help("Output all communication related to authentication to standard error. `tx` and `rx` are placed into the same stream.") + .multiple(false) + .takes_value(false)); + + for &(main_command_name, ref about, ref subcommands) in arg_data.iter() { + let mut mcmd = SubCommand::with_name(main_command_name).about(about); + + for &(sub_command_name, ref desc, url_info, ref args) in subcommands { + let mut scmd = SubCommand::with_name(sub_command_name); + if let &Some(desc) = desc { + scmd = scmd.about(desc); + } + scmd = scmd.after_help(url_info); + + for &(ref arg_name, ref flag, ref desc, ref required, ref multi) in args { + let arg_name_str = + match (arg_name, flag) { + (&Some(an), _ ) => an, + (_ , &Some(f)) => f, + _ => unreachable!(), + }; + let mut arg = Arg::with_name(arg_name_str) + .empty_values(false); + if let &Some(short_flag) = flag { + arg = arg.short(short_flag); + } + if let &Some(desc) = desc { + arg = arg.help(desc); + } + if arg_name.is_some() && flag.is_some() { + arg = arg.takes_value(true); + } + if let &Some(required) = required { + arg = arg.required(required); + } + if let &Some(multi) = multi { + arg = arg.multiple(multi); + } + scmd = scmd.arg(arg); + } + mcmd = mcmd.subcommand(scmd); + } + app = app.subcommand(mcmd); + } + + let matches = app.get_matches(); + + let debug = matches.is_present("debug"); + match Engine::new(matches) { + Err(err) => { + exit_status = err.exit_code; + writeln!(io::stderr(), "{}", err).ok(); + }, + Ok(engine) => { + if let Err(doit_err) = engine.doit() { + exit_status = 1; + match doit_err { + DoitError::IoError(path, err) => { + writeln!(io::stderr(), "Failed to open output file '{}': {}", path, err).ok(); + }, + DoitError::ApiError(err) => { + if debug { + writeln!(io::stderr(), "{:#?}", err).ok(); + } else { + writeln!(io::stderr(), "{}", err).ok(); + } + } + } + } + } + } + + std::process::exit(exit_status); +} \ No newline at end of file diff --git a/gen/logging2_beta1/Cargo.toml b/gen/logging2_beta1/Cargo.toml new file mode 100644 index 0000000000..7b2d1ff3f6 --- /dev/null +++ b/gen/logging2_beta1/Cargo.toml @@ -0,0 +1,29 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-logging2_beta1" +version = "0.1.9+20151007" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with logging (protocol v2beta1)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/logging2_beta1" +homepage = "https://cloud.google.com/logging/docs/" +documentation = "http://byron.github.io/google-apis-rs/google_logging2_beta1" +license = "MIT" +keywords = ["logging", "google", "protocol", "web", "api"] +build = "src/build.rs" + + +[dependencies] +hyper = ">= 0.6.8" +mime = "0.1.0" +serde = ">= 0.6.0" +serde_json = ">= 0.6.0" +yup-oauth2 = "*" +url = "*" + +[build-dependencies] +syntex = { version = "*" } +serde_codegen = { version = "*" } + diff --git a/gen/logging2_beta1/LICENSE.md b/gen/logging2_beta1/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/logging2_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/logging2_beta1/README.md b/gen/logging2_beta1/README.md new file mode 100644 index 0000000000..a379542b56 --- /dev/null +++ b/gen/logging2_beta1/README.md @@ -0,0 +1,145 @@ + +The `google-logging2_beta1` library allows access to all features of the *Google logging* service. + +This documentation was generated from *logging* crate version *0.1.9+20151007*, where *20151007* is the exact revision of the *logging:v2beta1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. + +Everything else about the *logging* *v2_beta1* API can be found at the +[official documentation site](https://cloud.google.com/logging/docs/). +# 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_logging2_beta1/struct.Logging.html)** + * a central object to maintain state and allow accessing all *Activities* + * creates [*Method Builders*](http://byron.github.io/google-apis-rs/google_logging2_beta1/trait.MethodsBuilder.html) which in turn + allow access to individual [*Call Builders*](http://byron.github.io/google-apis-rs/google_logging2_beta1/trait.CallBuilder.html) +* **[Resources](http://byron.github.io/google-apis-rs/google_logging2_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_logging2_beta1/trait.Part.html)** + * a collection of properties + * never directly used in *Activities* +* **[Activities](http://byron.github.io/google-apis-rs/google_logging2_beta1/trait.CallBuilder.html)** + * operations to apply to *Resources* + +All *structures* are marked with applicable traits to further categorize them and ease browsing. + +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-logging2_beta1 = "*" +``` + +## A complete example + +```Rust +extern crate hyper; +extern crate yup_oauth2 as oauth2; +extern crate google_logging2_beta1 as logging2_beta1; + +use std::default::Default; +use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +use logging2_beta1::Logging; + +// 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 = Logging::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_logging2_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_logging2_beta1/trait.Delegate.html), or the [Authenticator Delegate](http://byron.github.io/google-apis-rs/google_logging2_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 Downloads +If a method supports downloads, the response body, which is part of the [Result](http://byron.github.io/google-apis-rs/google_logging2_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_logging2_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_logging2_beta1/trait.Delegate.html) to the +[Method Builder](http://byron.github.io/google-apis-rs/google_logging2_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_logging2_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_logging2_beta1/trait.RequestValue.html) and +[decodable](http://byron.github.io/google-apis-rs/google_logging2_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_logging2_beta1/trait.Part.html) which are identifiable 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_logging2_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_logging2_beta1/trait.RequestValue.html) are moved + +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 **logging2_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/logging2_beta1/src/build.rs b/gen/logging2_beta1/src/build.rs new file mode 100644 index 0000000000..d993da1571 --- /dev/null +++ b/gen/logging2_beta1/src/build.rs @@ -0,0 +1,16 @@ +extern crate syntex; +extern crate serde_codegen; + +use std::env; +use std::path::Path; + +pub fn main() { + let out_dir = env::var_os("OUT_DIR").unwrap(); + + let src = Path::new("src/lib.rs.in"); + let dst = Path::new(&out_dir).join("lib.rs"); + + let mut registry = syntex::Registry::new(); + serde_codegen::register(&mut registry); + registry.expand("google-logging2_beta1", &src, &dst).unwrap(); +} diff --git a/gen/logging2_beta1/src/cmn.rs b/gen/logging2_beta1/src/cmn.rs new file mode 100644 index 0000000000..0e31353ba3 --- /dev/null +++ b/gen/logging2_beta1/src/cmn.rs @@ -0,0 +1,762 @@ +// COPY OF 'src/rust/api/cmn.rs' +// DO NOT EDIT +use std::io::{self, Read, Seek, Cursor, Write, SeekFrom}; +use std; +use std::fmt::{self, Display}; +use std::str::FromStr; +use std::error; +use std::thread::sleep_ms; + +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::h1::LINE_ENDING; +use hyper::method::Method; +use hyper::status::StatusCode; + +use serde_json as json; + +/// 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 {} + +/// Identifies types for building methods of a particular resource type +pub trait MethodsBuilder {} + +/// Identifies types which represent builders for a particular resource method +pub trait CallBuilder {} + +/// Identifies types which can be inserted and deleted. +/// Types with this trait are most commonly used by clients of this API. +pub trait Resource {} + +/// Identifies types which are used in API responses. +pub trait ResponseResult {} + +/// Identifies types which are used in API requests. +pub trait RequestValue {} + +/// Identifies types which are not actually used by the API +/// This might be a bug within the google API schema. +pub trait UnusedType {} + +/// Identifies types which are only used as part of other types, which +/// usually are carrying the `Resource` trait. +pub trait Part {} + +/// 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 {} + +/// 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 +} + +/// A utility to represent detailed errors we might see in case there are BadRequests. +/// The latter happen if the sent parameters or request structures are unsound +#[derive(Deserialize, Serialize, Debug)] +pub struct ErrorResponse { + error: ServerError, +} + +#[derive(Deserialize, Serialize, Debug)] +pub struct ServerError { + errors: Vec, + code: u16, + message: String, +} + +#[derive(Deserialize, Serialize, Debug)] +pub struct ServerMessage { + domain: String, + reason: String, + message: String, + #[serde(rename="locationType")] + location_type: Option, + location: 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 successful. That way, the delegate 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. + /// + /// If you choose to retry after a duration, the duration should be chosen using the + /// [exponential backoff algorithm](http://en.wikipedia.org/wiki/Exponential_backoff). + /// + /// Return retry information. + fn http_error(&mut self, &hyper::Error) -> 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 it as a general information about the + /// impending failure. + /// The given Error provides information about why the token couldn't be acquired in the + /// first place + fn token(&mut self, err: &error::Error) -> Option { + let _ = err; + 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/canceled, 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()`. + /// It will also be called with None after a successful upload, which allows the delegate + /// to forget the URL. That way, we will not attempt to resume an upload that has already + /// finished. + fn store_upload_url(&mut self, url: Option<&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: &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. + /// + /// If you choose to retry after a duration, the duration should be chosen using the + /// [exponential backoff algorithm](http://en.wikipedia.org/wiki/Exponential_backoff). + fn http_failure(&mut self, _: &hyper::client::Response, Option, _: 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 {} + + +#[derive(Debug)] +pub enum Error { + /// The http connection failed + HttpError(hyper::Error), + + /// 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), + + /// Represents information about a request that was not understood by the server. + /// Details are included. + BadRequest(ErrorResponse), + + /// 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(Box), + + /// 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(String, json::Error), + + /// Indicates an HTTP repsonse with a non-success status code + Failure(hyper::client::Response), +} + + +impl Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + Error::HttpError(ref err) => err.fmt(f), + Error::UploadSizeLimitExceeded(ref resource_size, ref max_size) => + writeln!(f, "The media size {} exceeds the maximum allowed upload size of {}" + , resource_size, max_size), + Error::MissingAPIKey => { + (writeln!(f, "The application's API key was not found in the configuration")).ok(); + writeln!(f, "It is used as there are no Scopes defined for this method.") + }, + Error::BadRequest(ref err) => { + try!(writeln!(f, "Bad Requst ({}): {}", err.error.code, err.error.message)); + for err in err.error.errors.iter() { + try!(writeln!(f, " {}: {}, {}{}", + err.domain, + err.message, + err.reason, + match &err.location { + &Some(ref loc) => format!("@{}", loc), + &None => String::new(), + })); + } + Ok(()) + }, + Error::MissingToken(ref err) => + writeln!(f, "Token retrieval failed with error: {}", err), + Error::Cancelled => + writeln!(f, "Operation cancelled by delegate"), + Error::FieldClash(field) => + writeln!(f, "The custom parameter '{}' is already provided natively by the CallBuilder.", field), + Error::JsonDecodeError(ref json_str, ref err) + => writeln!(f, "{}: {}", err, json_str), + Error::Failure(ref response) => + writeln!(f, "Http status indicates failure: {:?}", response), + } + } +} + +impl error::Error for Error { + fn description(&self) -> &str { + match *self { + Error::HttpError(ref err) => err.description(), + Error::JsonDecodeError(_, ref err) => err.description(), + _ => "NO DESCRIPTION POSSIBLE - use `Display.fmt()` instead" + } + } + + fn cause(&self) -> Option<&error::Error> { + match *self { + Error::HttpError(ref err) => err.cause(), + Error::JsonDecodeError(_, ref err) => err.cause(), + _ => None + } + } +} + +/// A universal result type used as return for all calls. +pub type Result = std::result::Result; + +/// 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 + 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 following macro invocation needs to be expanded, as `include!` +// doens't support external macros +// header!{ +// #[doc="The `X-Upload-Content-Type` header."] +// (XUploadContentType, "X-Upload-Content-Type") => [Mime] + +// xupload_content_type { +// test_header!( +// test1, +// vec![b"text/plain"], +// Some(HeaderField( +// vec![Mime(TopLevel::Text, SubLevel::Plain, Vec::new())] +// ))); + +// } +// } + +/// The `X-Upload-Content-Type` header. +/// +/// Generated via rustc --pretty expanded -Z unstable-options, and manually +/// processed to be more readable. +#[derive(PartialEq, Debug, Clone)] +pub struct XUploadContentType(pub Mime); + +impl ::std::ops::Deref for XUploadContentType { + type Target = Mime; + fn deref<'a>(&'a self) -> &'a Mime { &self.0 } +} +impl ::std::ops::DerefMut for XUploadContentType { + fn deref_mut<'a>(&'a mut self) -> &'a mut Mime { &mut self.0 } +} +impl Header for XUploadContentType { + fn header_name() -> &'static str { "X-Upload-Content-Type" } + fn parse_header(raw: &[Vec]) -> hyper::error::Result { + hyper::header::parsing::from_one_raw_str(raw).map(XUploadContentType) + } +} +impl HeaderFormat for XUploadContentType { + fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { + Display::fmt(&**self, f) + } +} +impl Display for XUploadContentType { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Display::fmt(&**self, f) + } +} + +#[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]) -> hyper::error::Result { + Err(hyper::error::Error::Method) + } +} + + +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]) -> hyper::error::Result { + if raw.len() > 0 { + let v = &raw[0]; + if let Ok(s) = std::str::from_utf8(v) { + const PREFIX: &'static str = "bytes "; + if s.starts_with(PREFIX) { + if let Ok(c) = ::from_str(&s[PREFIX.len()..]) { + return Ok(RangeResponseHeader(c)) + } + } + } + } + Err(hyper::error::Error::Method) + } +} + +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, 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, A> ResumableUploadHelper<'a, A> + where A: oauth2::GetToken { + + fn query_transfer_status(&mut self) -> std::result::Result> { + 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, None) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + return Err(Ok(r)) + } + }; + return Ok(h.0.last) + } + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + return Err(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() { + Ok(s) => s, + Err(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 + }; + + self.reader.seek(SeekFrom::Start(start)).unwrap(); + loop { + let request_size = match self.content_length - start { + rs if rs > chunk_size => chunk_size, + rs => rs + }; + + 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 + } + // workaround https://github.com/rust-lang/rust/issues/22252 + let res = 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(); + match res { + 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, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + } + return Some(Ok(res)) + }, + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + return Some(Err(err)) + } + } + } + } +} + +// Copy of src/rust/cli/cmn.rs +// TODO(ST): Allow sharing common code between program types +pub fn remove_json_null_values(value: &mut json::value::Value) { + match *value { + json::value::Value::Object(ref mut map) => { + let mut for_removal = Vec::new(); + + for (key, mut value) in map.iter_mut() { + if value.is_null() { + for_removal.push(key.clone()); + } else { + remove_json_null_values(&mut value); + } + } + + for key in &for_removal { + map.remove(key); + } + } + _ => {} + } +} diff --git a/gen/logging2_beta1/src/lib.rs b/gen/logging2_beta1/src/lib.rs new file mode 100644 index 0000000000..d893c92480 --- /dev/null +++ b/gen/logging2_beta1/src/lib.rs @@ -0,0 +1,149 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/api/lib.rs.mako' +// DO NOT EDIT ! + +//! This documentation was generated from *logging* crate version *0.1.9+20151007*, where *20151007* is the exact revision of the *logging:v2beta1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +//! +//! Everything else about the *logging* *v2_beta1* API can be found at the +//! [official documentation site](https://cloud.google.com/logging/docs/). +//! The original source code is [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/logging2_beta1). +//! # 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.Logging.html)** +//! * a central object to maintain state and allow accessing all *Activities* +//! * creates [*Method Builders*](trait.MethodsBuilder.html) which in turn +//! allow access to individual [*Call Builders*](trait.CallBuilder.html) +//! * **[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* +//! +//! All *structures* are marked with applicable traits to further categorize them and ease browsing. +//! +//! 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-logging2_beta1 = "*" +//! ``` +//! +//! ## A complete example +//! +//! ```test_harness,no_run +//! extern crate hyper; +//! extern crate yup_oauth2 as oauth2; +//! extern crate google_logging2_beta1 as logging2_beta1; +//! +//! # #[test] fn egal() { +//! use std::default::Default; +//! use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +//! use logging2_beta1::Logging; +//! +//! // 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 = Logging::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 Downloads +//! 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 identifiable 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 moved +//! +//! 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 +//! +//! + +// 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)] + +include!(concat!(env!("OUT_DIR"), "/lib.rs")); \ No newline at end of file diff --git a/gen/logging2_beta1/src/lib.rs.in b/gen/logging2_beta1/src/lib.rs.in new file mode 100644 index 0000000000..8a0c9d9ad6 --- /dev/null +++ b/gen/logging2_beta1/src/lib.rs.in @@ -0,0 +1,116 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/api/lib.rs.in.mako' +// DO NOT EDIT ! + +extern crate hyper; +extern crate serde; +extern crate serde_json; +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 serde_json as json; +use std::io; +use std::fs; +use std::thread::sleep_ms; + +pub use cmn::{MultiPartReader, ToParts, MethodInfo, Result, Error, CallBuilder, Hub, ReadSeek, Part, + ResponseResult, RequestValue, NestedType, Delegate, DefaultDelegate, MethodsBuilder, + Resource, ErrorResponse, remove_json_null_values}; + + +// ############## +// UTILITIES ### +// ############ + + + + +// ######## +// HUB ### +// ###### + +/// Central instance to access all Logging related resource activities +/// +/// # Examples +/// +/// Instantiate a new hub +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate yup_oauth2 as oauth2; +/// extern crate google_logging2_beta1 as logging2_beta1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use logging2_beta1::Logging; +/// +/// // 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 = Logging::new(hyper::Client::new(), auth); +/// # } +/// ``` +/// +pub struct Logging { + client: RefCell, + auth: RefCell, + _user_agent: String, +} + +impl<'a, C, A> Hub for Logging {} + +impl<'a, C, A> Logging + where C: BorrowMut, A: oauth2::GetToken { + + pub fn new(client: C, authenticator: A) -> Logging { + Logging { + client: RefCell::new(client), + auth: RefCell::new(authenticator), + _user_agent: "google-api-rust-client/0.1.9".to_string(), + } + } + + + /// Set the user-agent header field to use in all requests to the server. + /// It defaults to `google-api-rust-client/0.1.9`. + /// + /// 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 ### +// ########## + +// ################### +// MethodBuilders ### +// ################# + + + +// ################### +// CallBuilders ### +// ################# + diff --git a/gen/manager1_beta2/src/lib.rs.in b/gen/manager1_beta2/src/lib.rs.in index 7f18037eff..b80f4524e1 100644 --- a/gen/manager1_beta2/src/lib.rs.in +++ b/gen/manager1_beta2/src/lib.rs.in @@ -47,6 +47,9 @@ pub enum Scope { /// View and manage your Google Cloud Platform management resources and deployment status information NdevCloudman, + /// View your data across Google Cloud Platform services + CloudPlatformReadOnly, + /// Manage your data in Google Cloud Storage DevstorageReadWrite, @@ -61,6 +64,7 @@ impl AsRef for Scope { Scope::AppengineAdmin => "https://www.googleapis.com/auth/appengine.admin", Scope::NdevCloudmanReadonly => "https://www.googleapis.com/auth/ndev.cloudman.readonly", Scope::NdevCloudman => "https://www.googleapis.com/auth/ndev.cloudman", + Scope::CloudPlatformReadOnly => "https://www.googleapis.com/auth/cloud-platform.read-only", Scope::DevstorageReadWrite => "https://www.googleapis.com/auth/devstorage.read_write", Scope::CloudPlatform => "https://www.googleapis.com/auth/cloud-platform", } diff --git a/gen/mapsengine1/src/lib.rs.in b/gen/mapsengine1/src/lib.rs.in index c89e5395a5..6ee15c10ab 100644 --- a/gen/mapsengine1/src/lib.rs.in +++ b/gen/mapsengine1/src/lib.rs.in @@ -9177,10 +9177,10 @@ impl<'a, C, A> RasterFileInsertCall<'a, C, A> where C: BorrowMut, self.doit(stream, mime_type, "simple") } /// Upload media in a resumable fashion. - /// Even if the upload fails or is interrupted, it can be resumed for a + /// Even if the upload fails or is interrupted, it can be resumed for a /// certain amount of time as the server maintains state temporarily. /// - /// The delegate will be asked for an `upload_url()`, and if not provided, will be asked to store an upload URL + /// The delegate will be asked for an `upload_url()`, and if not provided, will be asked to store an upload URL /// that was provided by the server, using `store_upload_url(...)`. The upload will be done in chunks, the delegate /// may specify the `chunk_size()` and may cancel the operation before each chunk is uploaded, using /// `cancel_chunk_upload(...)`. @@ -12164,10 +12164,10 @@ impl<'a, C, A> TableFileInsertCall<'a, C, A> where C: BorrowMut, self.doit(stream, mime_type, "simple") } /// Upload media in a resumable fashion. - /// Even if the upload fails or is interrupted, it can be resumed for a + /// Even if the upload fails or is interrupted, it can be resumed for a /// certain amount of time as the server maintains state temporarily. /// - /// The delegate will be asked for an `upload_url()`, and if not provided, will be asked to store an upload URL + /// The delegate will be asked for an `upload_url()`, and if not provided, will be asked to store an upload URL /// that was provided by the server, using `store_upload_url(...)`. The upload will be done in chunks, the delegate /// may specify the `chunk_size()` and may cancel the operation before each chunk is uploaded, using /// `cancel_chunk_upload(...)`. @@ -23591,10 +23591,10 @@ impl<'a, C, A> ProjectIconCreateCall<'a, C, A> where C: BorrowMut self.doit(stream, mime_type, "simple") } /// Upload media in a resumable fashion. - /// Even if the upload fails or is interrupted, it can be resumed for a + /// Even if the upload fails or is interrupted, it can be resumed for a /// certain amount of time as the server maintains state temporarily. /// - /// The delegate will be asked for an `upload_url()`, and if not provided, will be asked to store an upload URL + /// The delegate will be asked for an `upload_url()`, and if not provided, will be asked to store an upload URL /// that was provided by the server, using `store_upload_url(...)`. The upload will be done in chunks, the delegate /// may specify the `chunk_size()` and may cancel the operation before each chunk is uploaded, using /// `cancel_chunk_upload(...)`. diff --git a/gen/mirror1-cli/Cargo.toml b/gen/mirror1-cli/Cargo.toml index 20e7cee6fc..50a6c1e583 100644 --- a/gen/mirror1-cli/Cargo.toml +++ b/gen/mirror1-cli/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-mirror1-cli" -version = "0.3.2+20150326" +version = "0.3.2+20150720" authors = ["Sebastian Thiel "] description = "A complete library to interact with mirror (protocol v1)" repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/mirror1-cli" diff --git a/gen/mirror1-cli/README.md b/gen/mirror1-cli/README.md index 9df2d54aad..54c89d5a0e 100644 --- a/gen/mirror1-cli/README.md +++ b/gen/mirror1-cli/README.md @@ -24,7 +24,7 @@ Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/ma # Usage -This documentation was generated from the *mirror* API at revision *20150326*. The CLI is at version *0.3.2*. +This documentation was generated from the *mirror* API at revision *20150720*. The CLI is at version *0.3.2*. ```bash mirror1 [options] diff --git a/gen/mirror1-cli/mkdocs.yml b/gen/mirror1-cli/mkdocs.yml index 028e4417df..1fb50f7c09 100644 --- a/gen/mirror1-cli/mkdocs.yml +++ b/gen/mirror1-cli/mkdocs.yml @@ -1,4 +1,4 @@ -site_name: mirror v0.3.2+20150326 +site_name: mirror v0.3.2+20150720 site_url: http://byron.github.io/google-apis-rs/google-mirror1-cli site_description: Write integrating applications with bcore diff --git a/gen/mirror1-cli/src/main.rs b/gen/mirror1-cli/src/main.rs index 638471640a..bc9ce6137b 100644 --- a/gen/mirror1-cli/src/main.rs +++ b/gen/mirror1-cli/src/main.rs @@ -2563,7 +2563,7 @@ fn main() { let mut app = App::new("mirror1") .author("Sebastian Thiel ") - .version("0.3.2+20150326") + .version("0.3.2+20150720") .about("API for interacting with Glass users via the timeline.") .after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_mirror1_cli") .arg(Arg::with_name("url") diff --git a/gen/mirror1/Cargo.toml b/gen/mirror1/Cargo.toml index f13b4e5b1d..348c8e2fe5 100644 --- a/gen/mirror1/Cargo.toml +++ b/gen/mirror1/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-mirror1" -version = "0.1.9+20150326" +version = "0.1.9+20150720" authors = ["Sebastian Thiel "] description = "A complete library to interact with mirror (protocol v1)" repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/mirror1" diff --git a/gen/mirror1/README.md b/gen/mirror1/README.md index d10957de74..9921b9aea2 100644 --- a/gen/mirror1/README.md +++ b/gen/mirror1/README.md @@ -5,7 +5,7 @@ DO NOT EDIT ! --> The `google-mirror1` library allows access to all features of the *Google mirror* service. -This documentation was generated from *mirror* crate version *0.1.9+20150326*, where *20150326* is the exact revision of the *mirror:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +This documentation was generated from *mirror* crate version *0.1.9+20150720*, where *20150720* is the exact revision of the *mirror:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. Everything else about the *mirror* *v1* API can be found at the [official documentation site](https://developers.google.com/glass). diff --git a/gen/mirror1/src/lib.rs b/gen/mirror1/src/lib.rs index 1e9b00e096..6009cf52e4 100644 --- a/gen/mirror1/src/lib.rs +++ b/gen/mirror1/src/lib.rs @@ -2,7 +2,7 @@ // This file was generated automatically from 'src/mako/api/lib.rs.mako' // DO NOT EDIT ! -//! This documentation was generated from *mirror* crate version *0.1.9+20150326*, where *20150326* is the exact revision of the *mirror:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +//! This documentation was generated from *mirror* crate version *0.1.9+20150720*, where *20150720* is the exact revision of the *mirror:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. //! //! Everything else about the *mirror* *v1* API can be found at the //! [official documentation site](https://developers.google.com/glass). diff --git a/gen/mirror1/src/lib.rs.in b/gen/mirror1/src/lib.rs.in index d29062faa5..e4c843cee3 100644 --- a/gen/mirror1/src/lib.rs.in +++ b/gen/mirror1/src/lib.rs.in @@ -2908,10 +2908,10 @@ impl<'a, C, A> TimelineInsertCall<'a, C, A> where C: BorrowMut, A self.doit(stream, mime_type, "simple") } /// Upload media in a resumable fashion. - /// Even if the upload fails or is interrupted, it can be resumed for a + /// Even if the upload fails or is interrupted, it can be resumed for a /// certain amount of time as the server maintains state temporarily. /// - /// The delegate will be asked for an `upload_url()`, and if not provided, will be asked to store an upload URL + /// The delegate will be asked for an `upload_url()`, and if not provided, will be asked to store an upload URL /// that was provided by the server, using `store_upload_url(...)`. The upload will be done in chunks, the delegate /// may specify the `chunk_size()` and may cancel the operation before each chunk is uploaded, using /// `cancel_chunk_upload(...)`. @@ -3806,10 +3806,10 @@ impl<'a, C, A> TimelineAttachmentInsertCall<'a, C, A> where C: BorrowMut TimelineUpdateCall<'a, C, A> where C: BorrowMut, A self.doit(stream, mime_type, "simple") } /// Upload media in a resumable fashion. - /// Even if the upload fails or is interrupted, it can be resumed for a + /// Even if the upload fails or is interrupted, it can be resumed for a /// certain amount of time as the server maintains state temporarily. /// - /// The delegate will be asked for an `upload_url()`, and if not provided, will be asked to store an upload URL + /// The delegate will be asked for an `upload_url()`, and if not provided, will be asked to store an upload URL /// that was provided by the server, using `store_upload_url(...)`. The upload will be done in chunks, the delegate /// may specify the `chunk_size()` and may cancel the operation before each chunk is uploaded, using /// `cancel_chunk_upload(...)`. diff --git a/gen/oauth2_v2-cli/Cargo.toml b/gen/oauth2_v2-cli/Cargo.toml index c2ce1f0822..7953098244 100644 --- a/gen/oauth2_v2-cli/Cargo.toml +++ b/gen/oauth2_v2-cli/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-oauth2_v2-cli" -version = "0.3.2+20150714" +version = "0.3.2+20151002" authors = ["Sebastian Thiel "] description = "A complete library to interact with oauth2 (protocol v2)" repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/oauth2_v2-cli" diff --git a/gen/oauth2_v2-cli/README.md b/gen/oauth2_v2-cli/README.md index ae91f60e1e..a63661871d 100644 --- a/gen/oauth2_v2-cli/README.md +++ b/gen/oauth2_v2-cli/README.md @@ -24,7 +24,7 @@ Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/ma # Usage -This documentation was generated from the *oauth2* API at revision *20150714*. The CLI is at version *0.3.2*. +This documentation was generated from the *oauth2* API at revision *20151002*. The CLI is at version *0.3.2*. ```bash oauth2-v2 [options] diff --git a/gen/oauth2_v2-cli/mkdocs.yml b/gen/oauth2_v2-cli/mkdocs.yml index f9bd091ee4..3a5c2ecb5e 100644 --- a/gen/oauth2_v2-cli/mkdocs.yml +++ b/gen/oauth2_v2-cli/mkdocs.yml @@ -1,4 +1,4 @@ -site_name: oauth2 v0.3.2+20150714 +site_name: oauth2 v0.3.2+20151002 site_url: http://byron.github.io/google-apis-rs/google-oauth2_v2-cli site_description: Write integrating applications with bcore diff --git a/gen/oauth2_v2-cli/src/main.rs b/gen/oauth2_v2-cli/src/main.rs index 3a4ca78c4e..9e4d983e28 100644 --- a/gen/oauth2_v2-cli/src/main.rs +++ b/gen/oauth2_v2-cli/src/main.rs @@ -446,7 +446,7 @@ fn main() { let mut app = App::new("oauth2-v2") .author("Sebastian Thiel ") - .version("0.3.2+20150714") + .version("0.3.2+20151002") .about("Lets you access OAuth2 protocol related APIs.") .after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_oauth2_v2_cli") .arg(Arg::with_name("url") diff --git a/gen/oauth2_v2/Cargo.toml b/gen/oauth2_v2/Cargo.toml index 5fa3334c97..171da6a66b 100644 --- a/gen/oauth2_v2/Cargo.toml +++ b/gen/oauth2_v2/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-oauth2_v2" -version = "0.1.9+20150714" +version = "0.1.9+20151002" authors = ["Sebastian Thiel "] description = "A complete library to interact with oauth2 (protocol v2)" repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/oauth2_v2" diff --git a/gen/oauth2_v2/README.md b/gen/oauth2_v2/README.md index 9d00d4a60b..2b0aa7a704 100644 --- a/gen/oauth2_v2/README.md +++ b/gen/oauth2_v2/README.md @@ -5,7 +5,7 @@ DO NOT EDIT ! --> The `google-oauth2_v2` library allows access to all features of the *Google oauth2* service. -This documentation was generated from *oauth2* crate version *0.1.9+20150714*, where *20150714* is the exact revision of the *oauth2:v2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +This documentation was generated from *oauth2* crate version *0.1.9+20151002*, where *20151002* is the exact revision of the *oauth2:v2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. Everything else about the *oauth2* *v2* API can be found at the [official documentation site](https://developers.google.com/accounts/docs/OAuth2). diff --git a/gen/oauth2_v2/src/lib.rs b/gen/oauth2_v2/src/lib.rs index d0fd91fec8..ac341f0833 100644 --- a/gen/oauth2_v2/src/lib.rs +++ b/gen/oauth2_v2/src/lib.rs @@ -2,7 +2,7 @@ // This file was generated automatically from 'src/mako/api/lib.rs.mako' // DO NOT EDIT ! -//! This documentation was generated from *oauth2* crate version *0.1.9+20150714*, where *20150714* is the exact revision of the *oauth2:v2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +//! This documentation was generated from *oauth2* crate version *0.1.9+20151002*, where *20151002* is the exact revision of the *oauth2:v2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. //! //! Everything else about the *oauth2* *v2* API can be found at the //! [official documentation site](https://developers.google.com/accounts/docs/OAuth2). diff --git a/gen/partners2-cli/Cargo.toml b/gen/partners2-cli/Cargo.toml new file mode 100644 index 0000000000..1a9ef590d7 --- /dev/null +++ b/gen/partners2-cli/Cargo.toml @@ -0,0 +1,35 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-partners2-cli" +version = "0.3.2+20151009" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with partners (protocol v2)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/partners2-cli" +homepage = "https://developers.google.com/partners/" +documentation = "http://byron.github.io/google-apis-rs/google_partners2_cli" +license = "MIT" +keywords = ["partners", "google", "cli"] + +[[bin]] +name = "partners2" + +[dependencies] +hyper = ">= 0.6.8" +mime = "0.1.0" +serde = ">= 0.6.0" +serde_json = ">= 0.6.0" +yup-oauth2 = "*" +strsim = "*" +yup-hyper-mock = ">=1.0.0" +clap = ">= 1.0.3" + +[build-dependencies] +syntex = { version = "*" } +serde_codegen = { version = "*" } + + +[dependencies.google-partners2] +path = "../partners2" diff --git a/gen/partners2-cli/LICENSE.md b/gen/partners2-cli/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/partners2-cli/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/partners2-cli/README.md b/gen/partners2-cli/README.md new file mode 100644 index 0000000000..a176580b1a --- /dev/null +++ b/gen/partners2-cli/README.md @@ -0,0 +1,117 @@ + +The `partners2` command-line interface *(CLI)* allows to use most features of the *Google partners* service from the comfort of your terminal. + +By default all output is printed to standard out, but flags can be set to direct it into a file independent of your shell's +capabilities. Errors will be printed to standard error, and cause the program's exit code to be non-zero. + +If data-structures are requested, these will be returned as pretty-printed JSON, to be useful as input to other tools. + +Everything else about the *partners* API can be found at the +[official documentation site](https://developers.google.com/partners/). + +# Downloads + +You can download the pre-compiled 64bit binaries for the following platforms: + +* ![icon](http://megaicons.net/static/img/icons_sizes/6/140/16/ubuntu-icon.png) [ubuntu](http://dl.byronimo.de/google.rs/cli/0.3.2/ubuntu/partners2.tar.gz) +* ![icon](http://hydra-media.cursecdn.com/wow.gamepedia.com/a/a2/Apple-icon-16x16.png?version=25ddd67ac3dd3b634478e3978b76cb74) [osx](http://dl.byronimo.de/google.rs/cli/0.3.2/osx/partners2.tar.gz) + +Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/partners2-cli). + +# Usage + +This documentation was generated from the *partners* API at revision *20151009*. The CLI is at version *0.3.2*. + +```bash +partners2 [options] + client-messages + log (-r )... [-p ]... [-o ] + companies + get [-p ]... [-o ] + leads-create (-r )... [-p ]... [-o ] + list [-p ]... [-o ] + user-events + log (-r )... [-p ]... [-o ] + user-states + list [-p ]... [-o ] + partners2 --help + +Configuration: + --config-dir + A directory into which we will store our persistent data. Defaults to + a user-writable directory that we will create during the first invocation. + [default: ~/.google-service-cli] + --debug + Output all server communication to standard error. `tx` and `rx` are placed + into the same stream. + --debug-auth + Output all communication related to authentication to standard error. `tx` + and `rx` are placed into the same stream. + +``` + +# Configuration + +The program will store all persistent data in the `~/.google-service-cli` directory in *JSON* files prefixed with `partners2-`. You can change the directory used to store configuration with the `--config-dir` flag on a per-invocation basis. + +More information about the various kinds of persistent data are given in the following paragraphs. + +# Authentication + +Most APIs require a user to authenticate any request. If this is the case, the [scope][scopes] determines the +set of permissions granted. The granularity of these is usually no more than *read-only* or *full-access*. + +If not set, the system will automatically select the smallest feasible scope, e.g. when invoking a +method that is read-only, it will ask only for a read-only scope. +You may use the `--scope` flag to specify a scope directly. +All applicable scopes are documented in the respective method's CLI documentation. + +The first time a scope is used, the user is asked for permission. Follow the instructions given +by the CLI to grant permissions, or to decline. + +If a scope was authenticated by the user, the respective information will be stored as *JSON* in the configuration +directory, e.g. `~/.google-service-cli/partners2-token-.json`. No manual management of these tokens +is necessary. + +To revoke granted authentication, please refer to the [official documentation][revoke-access]. + +# Application Secrets + +In order to allow any application to use Google services, it will need to be registered using the +[Google Developer Console][google-dev-console]. APIs the application may use are then enabled for it +one by one. Most APIs can be used for free and have a daily quota. + +To allow more comfortable usage of the CLI without forcing anyone to register an own application, the CLI +comes with a default application secret that is configured accordingly. This also means that heavy usage +all around the world may deplete the daily quota. + +You can workaround this limitation by putting your own secrets file at this location: +`~/.google-service-cli/partners2-secret.json`, assuming that the required *partners* API +was enabled for it. Such a secret file can be downloaded in the *Google Developer Console* at +*APIs & auth -> Credentials -> Download JSON* and used as is. + +Learn more about how to setup Google projects and enable APIs using the [official documentation][google-project-new]. + + +# Debugging + +Even though the CLI does its best to provide usable error messages, sometimes it might be desirable to know +what exactly led to a particular issue. This is done by allowing all client-server communication to be +output to standard error *as-is*. + +The `--debug` flag will print all client-server communication to standard error, whereas the `--debug-auth` flag +will cause all communication related to authentication to standard error. +If the `--debug` flag is set, error-results will be debug-printed, possibly yielding more information about the +issue at hand. + +You may consider redirecting standard error into a file for ease of use, e.g. `partners2 --debug [options] 2>debug.txt`. + + +[scopes]: https://developers.google.com/+/api/oauth#scopes +[revoke-access]: http://webapps.stackexchange.com/a/30849 +[google-dev-console]: https://console.developers.google.com/ +[google-project-new]: https://developers.google.com/console/help/new/ \ No newline at end of file diff --git a/gen/partners2-cli/mkdocs.yml b/gen/partners2-cli/mkdocs.yml new file mode 100644 index 0000000000..09f4c785db --- /dev/null +++ b/gen/partners2-cli/mkdocs.yml @@ -0,0 +1,22 @@ +site_name: partners v0.3.2+20151009 +site_url: http://byron.github.io/google-apis-rs/google-partners2-cli +site_description: Write integrating applications with bcore + +repo_url: https://github.com/Byron/google-apis-rs/tree/master/gen/partners2-cli + +docs_dir: docs +site_dir: build_html + +pages: +- ['index.md', 'Home'] +- ['client-messages_log.md', 'Client Messages', 'Log'] +- ['companies_get.md', 'Companies', 'Get'] +- ['companies_leads-create.md', 'Companies', 'Leads Create'] +- ['companies_list.md', 'Companies', 'List'] +- ['user-events_log.md', 'User Events', 'Log'] +- ['user-states_list.md', 'User States', 'List'] + +theme: readthedocs + +copyright: Copyright © 2015, `Sebastian Thiel` + diff --git a/gen/partners2-cli/src/cmn.rs b/gen/partners2-cli/src/cmn.rs new file mode 100644 index 0000000000..8358f156fa --- /dev/null +++ b/gen/partners2-cli/src/cmn.rs @@ -0,0 +1,721 @@ +// COPY OF 'src/rust/cli/cmn.rs' +// DO NOT EDIT +use oauth2::{ApplicationSecret, ConsoleApplicationSecret, TokenStorage, Token}; +use serde_json as json; +use serde_json::value::Value; +use mime::Mime; +use clap::{App, SubCommand}; +use strsim; + +use std::fs; +use std::env; +use std::io; +use std::fmt; +use std::path::{Path, PathBuf}; +use std::str::FromStr; +use std::string::ToString; +use std::io::{Write, Read, stdout}; + +use std::default::Default; + +const FIELD_SEP: char = '.'; + + +pub enum ComplexType { + Pod, + Vec, + Map, +} + + // Null, + // Bool(bool), + // I64(i64), + // U64(u64), + // F64(f64), + // String(String), + +pub enum JsonType { + Boolean, + Int, + Uint, + Float, + String, +} + +pub struct JsonTypeInfo { + pub jtype: JsonType, + pub ctype: ComplexType, +} + +// Based on @erickt user comment. Thanks for the idea ! +// Remove all keys whose values are null from given value (changed in place) +pub fn remove_json_null_values(value: &mut Value) { + match *value { + Value::Object(ref mut map) => { + let mut for_removal = Vec::new(); + + for (key, mut value) in map.iter_mut() { + if value.is_null() { + for_removal.push(key.clone()); + } else { + remove_json_null_values(&mut value); + } + } + + for key in &for_removal { + map.remove(key); + } + } + _ => {} + } +} + +fn did_you_mean<'a>(v: &str, possible_values: &[&'a str]) -> Option<&'a str> { + + let mut candidate: Option<(f64, &str)> = None; + for pv in possible_values { + let confidence = strsim::jaro_winkler(v, pv); + if confidence > 0.8 && (candidate.is_none() || (candidate.as_ref().unwrap().0 < confidence)) { + candidate = Some((confidence, pv)); + } + } + match candidate { + None => None, + Some((_, candidate)) => Some(candidate), + } +} + +pub enum CallType { + Upload(UploadProtocol), + Standard, +} + +arg_enum!{ + pub enum UploadProtocol { + Simple, + Resumable + } +} + +impl AsRef for UploadProtocol { + fn as_ref(&self) -> &str { + match *self { + UploadProtocol::Simple => "simple", + UploadProtocol::Resumable => "resumable" + } + } +} + +impl AsRef for CallType { + fn as_ref(&self) -> &str { + match *self { + CallType::Upload(ref proto) => proto.as_ref(), + CallType::Standard => "standard-request" + } + } +} + +#[derive(Clone, Default)] +pub struct FieldCursor(Vec); + +impl ToString for FieldCursor { + fn to_string(&self) -> String { + self.0.join(".") + } +} + +impl From<&'static str> for FieldCursor { + fn from(value: &'static str) -> FieldCursor { + let mut res = FieldCursor::default(); + res.set(value).unwrap(); + res + } +} + +impl FieldCursor { + pub fn set(&mut self, value: &str) -> Result<(), CLIError> { + if value.len() == 0 { + return Err(CLIError::Field(FieldError::Empty)) + } + + let mut first_is_field_sep = false; + let mut char_count: usize = 0; + let mut last_c = FIELD_SEP; + let mut num_conscutive_field_seps = 0; + + let mut field = String::new(); + let mut fields = self.0.clone(); + + let push_field = |fs: &mut Vec, f: &mut String| { + if f.len() > 0 { + fs.push(f.clone()); + f.truncate(0); + } + }; + + for (cid, c) in value.chars().enumerate() { + char_count += 1; + + if c == FIELD_SEP { + if cid == 0 { + first_is_field_sep = true; + } + num_conscutive_field_seps += 1; + if cid > 0 && last_c == FIELD_SEP { + if fields.pop().is_none() { + return Err(CLIError::Field(FieldError::PopOnEmpty(value.to_string()))) + } + } else { + push_field(&mut fields, &mut field); + } + } else { + num_conscutive_field_seps = 0; + if cid == 1 { + if first_is_field_sep { + fields.truncate(0); + } + } + field.push(c); + } + + last_c = c; + } + + push_field(&mut fields, &mut field); + + if char_count == 1 && first_is_field_sep { + fields.truncate(0); + } + if char_count > 1 && num_conscutive_field_seps == 1 { + return Err(CLIError::Field(FieldError::TrailingFieldSep(value.to_string()))) + } + + self.0 = fields; + Ok(()) + } + + pub fn did_you_mean(value: &str, possible_values: &[&str]) -> Option { + if value.len() == 0 { + return None + } + + let mut last_c = FIELD_SEP; + + let mut field = String::new(); + let mut output = String::new(); + + let push_field = |fs: &mut String, f: &mut String| { + if f.len() > 0 { + fs.push_str( + match did_you_mean(&f, possible_values) { + Some(candidate) => candidate, + None => &f, + }); + f.truncate(0); + } + }; + + for (cid, c) in value.chars().enumerate() { + if c == FIELD_SEP { + if last_c != FIELD_SEP { + push_field(&mut output, &mut field); + } + output.push(c); + } else { + field.push(c); + } + + last_c = c; + } + + push_field(&mut output, &mut field); + + if &output == value { + None + } else { + Some(output) + } + } + + pub fn set_json_value(&self, mut object: &mut Value, + value: &str, type_info: JsonTypeInfo, + err: &mut InvalidOptionsError, + orig_cursor: &FieldCursor) { + assert!(self.0.len() > 0); + + for field in &self.0[..self.0.len()-1] { + let tmp = object; + object = + match *tmp { + Value::Object(ref mut mapping) => { + mapping.entry(field.to_owned()).or_insert( + Value::Object(Default::default()) + ) + }, + _ => panic!("We don't expect non-object Values here ...") + }; + } + + match *object { + Value::Object(ref mut mapping) => { + let field = &self.0[self.0.len()-1]; + let to_jval = + |value: &str, jtype: JsonType, err: &mut InvalidOptionsError| + -> Value { + match jtype { + JsonType::Boolean => + Value::Bool(arg_from_str(value, err, &field, "boolean")), + JsonType::Int => + Value::I64(arg_from_str(value, err, &field, "int")), + JsonType::Uint => + Value::U64(arg_from_str(value, err, &field, "uint")), + JsonType::Float => + Value::F64(arg_from_str(value, err, &field, "float")), + JsonType::String => + Value::String(value.to_owned()), + } + }; + + match type_info.ctype { + ComplexType::Pod => { + if mapping.insert(field.to_owned(), to_jval(value, type_info.jtype, err)).is_some() { + err.issues.push(CLIError::Field(FieldError::Duplicate(orig_cursor.to_string()))); + } + }, + ComplexType::Vec => { + match *mapping.entry(field.to_owned()) + .or_insert(Value::Array(Default::default())) { + Value::Array(ref mut values) => values.push(to_jval(value, type_info.jtype, err)), + _ => unreachable!() + } + }, + ComplexType::Map => { + let (key, value) = parse_kv_arg(value, err, true); + let jval = to_jval(value.unwrap_or(""), type_info.jtype, err); + + match *mapping.entry(field.to_owned()) + .or_insert(Value::Object(Default::default())) { + Value::Object(ref mut value_map) => { + if value_map.insert(key.to_owned(), jval).is_some() { + err.issues.push(CLIError::Field(FieldError::Duplicate(orig_cursor.to_string()))); + } + } + _ => unreachable!() + } + } + } + }, + _ => unreachable!() + } + } + + pub fn num_fields(&self) -> usize { + self.0.len() + } +} + +pub fn parse_kv_arg<'a>(kv: &'a str, err: &mut InvalidOptionsError, for_hashmap: bool) + -> (&'a str, Option<&'a str>) { + let mut add_err = || err.issues.push(CLIError::InvalidKeyValueSyntax(kv.to_string(),for_hashmap)); + match kv.find('=') { + None => { + add_err(); + return (kv, None) + }, + Some(pos) => { + let key = &kv[..pos]; + if kv.len() <= pos + 1 { + add_err(); + return (key, Some("")) + } + (key, Some(&kv[pos+1..])) + } + } +} + +pub fn calltype_from_str(name: &str, valid_protocols: Vec, err: &mut InvalidOptionsError) -> CallType { + CallType::Upload( + match UploadProtocol::from_str(name) { + Ok(up) => up, + Err(msg) => { + err.issues.push(CLIError::InvalidUploadProtocol(name.to_string(), valid_protocols)); + UploadProtocol::Simple + } + }) +} + +pub fn input_file_from_opts(file_path: &str, err: &mut InvalidOptionsError) -> Option { + match fs::File::open(file_path) { + Ok(f) => Some(f), + Err(io_err) => { + err.issues.push(CLIError::Input(InputError::IOError((file_path.to_string(), io_err)))); + None + } + } +} + +pub fn input_mime_from_opts(mime: &str, err: &mut InvalidOptionsError) -> Option { + match mime.parse() { + Ok(m) => Some(m), + Err(_) => { + err.issues.push(CLIError::Input(InputError::Mime(mime.to_string()))); + None + } + } +} + +pub fn writer_from_opts(arg: Option<&str>) -> Result, io::Error> { + let f = arg.unwrap_or("-"); + match f { + "-" => Ok(Box::new(stdout())), + _ => match fs::OpenOptions::new().create(true).write(true).open(f) { + Ok(f) => Ok(Box::new(f)), + Err(io_err) => Err(io_err), + } + } +} + + +pub fn arg_from_str<'a, T>(arg: &str, err: &mut InvalidOptionsError, + arg_name: &'a str, + arg_type: &'a str) -> T + where T: FromStr + Default, + ::Err: fmt::Display { + match FromStr::from_str(arg) { + Err(perr) => { + err.issues.push( + CLIError::ParseError(arg_name.to_owned(), arg_type.to_owned(), arg.to_string(), format!("{}", perr)) + ); + Default::default() + }, + Ok(v) => v, + } +} + +pub struct JsonTokenStorage { + pub program_name: &'static str, + pub db_dir: String, +} + +impl JsonTokenStorage { + fn path(&self, scope_hash: u64) -> PathBuf { + Path::new(&self.db_dir).join(&format!("{}-token-{}.json", self.program_name, scope_hash)) + } +} + +impl TokenStorage for JsonTokenStorage { + type Error = json::Error; + + // NOTE: logging might be interesting, currently we swallow all errors + fn set(&mut self, scope_hash: u64, _: &Vec<&str>, token: Option) -> Result<(), json::Error> { + match token { + None => { + match fs::remove_file(self.path(scope_hash)) { + Err(err) => + match err.kind() { + io::ErrorKind::NotFound => Ok(()), + _ => Err(json::Error::IoError(err)) + }, + Ok(_) => Ok(()), + } + } + Some(token) => { + match fs::OpenOptions::new().create(true).write(true).open(&self.path(scope_hash)) { + Ok(mut f) => { + match json::to_writer_pretty(&mut f, &token) { + Ok(_) => Ok(()), + Err(serde_err) => Err(serde_err), + } + }, + Err(io_err) => Err(json::Error::IoError(io_err)) + } + } + } + } + + fn get(&self, scope_hash: u64, _: &Vec<&str>) -> Result, json::Error> { + match fs::File::open(&self.path(scope_hash)) { + Ok(mut f) => { + match json::de::from_reader(f) { + Ok(token) => Ok(Some(token)), + Err(err) => Err(err), + } + }, + Err(io_err) => { + match io_err.kind() { + io::ErrorKind::NotFound => Ok(None), + _ => Err(json::Error::IoError(io_err)) + } + } + } + } +} + + +#[derive(Debug)] +pub enum ApplicationSecretError { + DecoderError((String, json::Error)), + FormatError(String), +} + +impl fmt::Display for ApplicationSecretError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + ApplicationSecretError::DecoderError((ref path, ref err)) + => writeln!(f, "Could not decode file at '{}' with error: {}.", + path, err), + ApplicationSecretError::FormatError(ref path) + => writeln!(f, "'installed' field is unset in secret file at '{}'.", + path), + } + } +} + +#[derive(Debug)] +pub enum ConfigurationError { + DirectoryCreationFailed((String, io::Error)), + DirectoryUnset, + HomeExpansionFailed(String), + Secret(ApplicationSecretError), + IOError((String, io::Error)), +} + +impl fmt::Display for ConfigurationError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + ConfigurationError::DirectoryCreationFailed((ref dir, ref err)) + => writeln!(f, "Directory '{}' could not be created with error: {}.", dir, err), + ConfigurationError::DirectoryUnset + => writeln!(f, "--config-dir was unset or empty."), + ConfigurationError::HomeExpansionFailed(ref dir) + => writeln!(f, "Couldn't find HOME directory of current user, failed to expand '{}'.", dir), + ConfigurationError::Secret(ref err) + => writeln!(f, "Secret -> {}", err), + ConfigurationError::IOError((ref path, ref err)) + => writeln!(f, "IO operation failed on path '{}' with error: {}.", path, err), + } + } +} + +#[derive(Debug)] +pub enum InputError { + IOError((String, io::Error)), + Mime(String), +} + +impl fmt::Display for InputError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + InputError::IOError((ref file_path, ref io_err)) + => writeln!(f, "Failed to open '{}' for reading with error: {}.", file_path, io_err), + InputError::Mime(ref mime) + => writeln!(f, "'{}' is not a known mime-type.", mime), + } + } +} + +#[derive(Debug)] +pub enum FieldError { + PopOnEmpty(String), + TrailingFieldSep(String), + Unknown(String, Option, Option), + Duplicate(String), + Empty, +} + + +impl fmt::Display for FieldError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + FieldError::PopOnEmpty(ref field) + => writeln!(f, "'{}': Cannot move up on empty field cursor.", field), + FieldError::TrailingFieldSep(ref field) + => writeln!(f, "'{}': Single field separator may not be last character.", field), + FieldError::Unknown(ref field, ref suggestion, ref value) => { + let suffix = + match *suggestion { + Some(ref s) => { + let kv = + match *value { + Some(ref v) => format!("{}={}", s, v), + None => s.clone(), + }; + format!(" Did you mean '{}' ?", kv) + }, + None => String::new(), + }; + writeln!(f, "Field '{}' does not exist.{}", field, suffix) + }, + FieldError::Duplicate(ref cursor) + => writeln!(f, "Value at '{}' was already set", cursor), + FieldError::Empty + => writeln!(f, "Field names must not be empty."), + } + } +} + + +#[derive(Debug)] +pub enum CLIError { + Configuration(ConfigurationError), + ParseError(String, String, String, String), + UnknownParameter(String, Vec<&'static str>), + InvalidUploadProtocol(String, Vec), + InvalidKeyValueSyntax(String, bool), + Input(InputError), + Field(FieldError), + MissingCommandError, + MissingMethodError(String), +} + +impl fmt::Display for CLIError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + CLIError::Configuration(ref err) => write!(f, "Configuration -> {}", err), + CLIError::Input(ref err) => write!(f, "Input -> {}", err), + CLIError::Field(ref err) => write!(f, "Field -> {}", err), + CLIError::InvalidUploadProtocol(ref proto_name, ref valid_names) + => writeln!(f, "'{}' is not a valid upload protocol. Choose from one of {}.", proto_name, valid_names.join(", ")), + CLIError::ParseError(ref arg_name, ref type_name, ref value, ref err_desc) + => writeln!(f, "Failed to parse argument '{}' with value '{}' as {} with error: {}.", + arg_name, value, type_name, err_desc), + CLIError::UnknownParameter(ref param_name, ref possible_values) => { + let mut suffix = + match did_you_mean(param_name, &possible_values) { + Some(v) => format!(" Did you mean '{}' ?", v), + None => String::new(), + }; + write!(f, "Parameter '{}' is unknown.{}\n", param_name, suffix) + }, + CLIError::InvalidKeyValueSyntax(ref kv, is_hashmap) => { + let hashmap_info = if is_hashmap { "hashmap " } else { "" }; + writeln!(f, "'{}' does not match {}pattern =.", kv, hashmap_info) + }, + CLIError::MissingCommandError => writeln!(f, "Please specify the main sub-command."), + CLIError::MissingMethodError(ref cmd) => writeln!(f, "Please specify the method to call on the '{}' command.", cmd), + } + } +} + +#[derive(Debug)] +pub struct InvalidOptionsError { + pub issues: Vec, + pub exit_code: i32, +} + +impl fmt::Display for InvalidOptionsError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + for issue in &self.issues { + try!(issue.fmt(f)); + } + Ok(()) + } +} + +impl InvalidOptionsError { + pub fn single(err: CLIError, exit_code: i32) -> InvalidOptionsError { + InvalidOptionsError { + issues: vec![err], + exit_code: exit_code, + } + } + + pub fn new() -> InvalidOptionsError { + InvalidOptionsError { + issues: Vec::new(), + exit_code: 1, + } + } +} + +pub fn assure_config_dir_exists(dir: &str) -> Result { + let trdir = dir.trim(); + if trdir.len() == 0 { + return Err(CLIError::Configuration(ConfigurationError::DirectoryUnset)) + } + + let expanded_config_dir = + if trdir.as_bytes()[0] == b'~' { + match env::var("HOME").ok().or(env::var("UserProfile").ok()) { + None => return Err(CLIError::Configuration(ConfigurationError::HomeExpansionFailed(trdir.to_string()))), + Some(mut user) => { + user.push_str(&trdir[1..]); + user + } + } + } else { + trdir.to_string() + }; + + if let Err(err) = fs::create_dir(&expanded_config_dir) { + if err.kind() != io::ErrorKind::AlreadyExists { + return Err(CLIError::Configuration( + ConfigurationError::DirectoryCreationFailed((expanded_config_dir, err)))) + } + } + + Ok(expanded_config_dir) +} + +pub fn application_secret_from_directory(dir: &str, + secret_basename: &str, + json_console_secret: &str) + -> Result { + let secret_path = Path::new(dir).join(secret_basename); + let secret_str = || secret_path.as_path().to_str().unwrap().to_string(); + let secret_io_error = |io_err: io::Error| { + Err(CLIError::Configuration(ConfigurationError::IOError( + (secret_str(), io_err) + ))) + }; + + for _ in 0..2 { + match fs::File::open(&secret_path) { + Err(mut err) => { + if err.kind() == io::ErrorKind::NotFound { + // Write our built-in one - user may adjust the written file at will + + err = match fs::OpenOptions::new().create(true).write(true).open(&secret_path) { + Err(cfe) => cfe, + Ok(mut f) => { + // Assure we convert 'ugly' json string into pretty one + let console_secret: ConsoleApplicationSecret + = json::from_str(json_console_secret).unwrap(); + match json::to_writer_pretty(&mut f, &console_secret) { + Err(serde_err) => match serde_err { + json::Error::IoError(err) => err, + _ => panic!("Unexpected serde error: {:#?}", serde_err) + }, + Ok(_) => continue, + } + } + }; + // fall through to IO error handling + } + return secret_io_error(err) + }, + Ok(mut f) => { + match json::de::from_reader::<_, ConsoleApplicationSecret>(f) { + Err(json::Error::IoError(err)) => + return secret_io_error(err), + Err(json_err) => + return Err(CLIError::Configuration( + ConfigurationError::Secret( + ApplicationSecretError::DecoderError( + (secret_str(), json_err) + )))), + Ok(console_secret) => + match console_secret.installed { + Some(secret) => return Ok(secret), + None => return Err( + CLIError::Configuration( + ConfigurationError::Secret( + ApplicationSecretError::FormatError(secret_str()) + ))) + }, + } + } + } + } + unreachable!(); +} diff --git a/gen/partners2-cli/src/main.rs b/gen/partners2-cli/src/main.rs new file mode 100644 index 0000000000..3850025cfb --- /dev/null +++ b/gen/partners2-cli/src/main.rs @@ -0,0 +1,992 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/cli/main.rs.mako' +// DO NOT EDIT ! +#![allow(unused_variables, unused_imports, dead_code, unused_mut)] + +#[macro_use] +extern crate clap; +extern crate yup_oauth2 as oauth2; +extern crate yup_hyper_mock as mock; +extern crate serde; +extern crate serde_json; +extern crate hyper; +extern crate mime; +extern crate strsim; +extern crate google_partners2 as api; + +use std::env; +use std::io::{self, Write}; +use clap::{App, SubCommand, Arg}; + +mod cmn; + +use cmn::{InvalidOptionsError, CLIError, JsonTokenStorage, arg_from_str, writer_from_opts, parse_kv_arg, + input_file_from_opts, input_mime_from_opts, FieldCursor, FieldError, CallType, UploadProtocol, + calltype_from_str, remove_json_null_values, ComplexType, JsonType, JsonTypeInfo}; + +use std::default::Default; +use std::str::FromStr; + +use oauth2::{Authenticator, DefaultAuthenticatorDelegate}; +use serde_json as json; +use clap::ArgMatches; + +enum DoitError { + IoError(String, io::Error), + ApiError(api::Error), +} + +struct Engine<'n, 'a> { + opt: ArgMatches<'n, 'a>, + hub: api::Partners>, + gp: Vec<&'static str>, + gpm: Vec<(&'static str, &'static str)>, +} + + +impl<'n, 'a> Engine<'n, 'a> { + fn _client_messages_log(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "client-info" => Some(("clientInfo", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Map })), + "request-metadata.locale" => Some(("requestMetadata.locale", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "request-metadata.partners-session-id" => Some(("requestMetadata.partnersSessionId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "request-metadata.traffic-source.traffic-sub-id" => Some(("requestMetadata.trafficSource.trafficSubId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "request-metadata.traffic-source.traffic-source-id" => Some(("requestMetadata.trafficSource.trafficSourceId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "request-metadata.user-overrides.user-id" => Some(("requestMetadata.userOverrides.userId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "request-metadata.user-overrides.ip-address" => Some(("requestMetadata.userOverrides.ipAddress", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "request-metadata.experiment-ids" => Some(("requestMetadata.experimentIds", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "details" => Some(("details", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "level" => Some(("level", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["client-info", "details", "experiment-ids", "ip-address", "level", "locale", "partners-session-id", "request-metadata", "traffic-source", "traffic-source-id", "traffic-sub-id", "user-id", "user-overrides"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::LogMessageRequest = json::value::from_value(object).unwrap(); + let mut call = self.hub.client_messages().log(request); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _companies_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.companies().get(opt.value_of("company-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "view" => { + call = call.view(value.unwrap_or("")); + }, + "request-metadata-user-overrides-user-id" => { + call = call.request_metadata_user_overrides_user_id(value.unwrap_or("")); + }, + "request-metadata-user-overrides-ip-address" => { + call = call.request_metadata_user_overrides_ip_address(value.unwrap_or("")); + }, + "request-metadata-traffic-source-traffic-sub-id" => { + call = call.request_metadata_traffic_source_traffic_sub_id(value.unwrap_or("")); + }, + "request-metadata-traffic-source-traffic-source-id" => { + call = call.request_metadata_traffic_source_traffic_source_id(value.unwrap_or("")); + }, + "request-metadata-partners-session-id" => { + call = call.request_metadata_partners_session_id(value.unwrap_or("")); + }, + "request-metadata-locale" => { + call = call.request_metadata_locale(value.unwrap_or("")); + }, + "request-metadata-experiment-ids" => { + call = call.add_request_metadata_experiment_ids(value.unwrap_or("")); + }, + "order-by" => { + call = call.order_by(value.unwrap_or("")); + }, + "currency-code" => { + call = call.currency_code(value.unwrap_or("")); + }, + "address" => { + call = call.address(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["order-by", "request-metadata-locale", "request-metadata-user-overrides-ip-address", "request-metadata-partners-session-id", "request-metadata-traffic-source-traffic-sub-id", "request-metadata-user-overrides-user-id", "address", "request-metadata-experiment-ids", "currency-code", "request-metadata-traffic-source-traffic-source-id", "view"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _companies_leads_create(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "request-metadata.locale" => Some(("requestMetadata.locale", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "request-metadata.partners-session-id" => Some(("requestMetadata.partnersSessionId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "request-metadata.traffic-source.traffic-sub-id" => Some(("requestMetadata.trafficSource.trafficSubId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "request-metadata.traffic-source.traffic-source-id" => Some(("requestMetadata.trafficSource.trafficSourceId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "request-metadata.user-overrides.user-id" => Some(("requestMetadata.userOverrides.userId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "request-metadata.user-overrides.ip-address" => Some(("requestMetadata.userOverrides.ipAddress", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "request-metadata.experiment-ids" => Some(("requestMetadata.experimentIds", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "recaptcha-challenge.id" => Some(("recaptchaChallenge.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "recaptcha-challenge.response" => Some(("recaptchaChallenge.response", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "lead.gps-motivations" => Some(("lead.gpsMotivations", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "lead.family-name" => Some(("lead.familyName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "lead.min-monthly-budget.units" => Some(("lead.minMonthlyBudget.units", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "lead.min-monthly-budget.nanos" => Some(("lead.minMonthlyBudget.nanos", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "lead.min-monthly-budget.currency-code" => Some(("lead.minMonthlyBudget.currencyCode", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "lead.comments" => Some(("lead.comments", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "lead.email" => Some(("lead.email", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "lead.website-url" => Some(("lead.websiteUrl", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "lead.phone-number" => Some(("lead.phoneNumber", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "lead.given-name" => Some(("lead.givenName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "lead.type" => Some(("lead.type", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "lead.id" => Some(("lead.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["comments", "currency-code", "email", "experiment-ids", "family-name", "given-name", "gps-motivations", "id", "ip-address", "lead", "locale", "min-monthly-budget", "nanos", "partners-session-id", "phone-number", "recaptcha-challenge", "request-metadata", "response", "traffic-source", "traffic-source-id", "traffic-sub-id", "type", "units", "user-id", "user-overrides", "website-url"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::CreateLeadRequest = json::value::from_value(object).unwrap(); + let mut call = self.hub.companies().leads_create(request, opt.value_of("company-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _companies_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.companies().list(); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "website-url" => { + call = call.website_url(value.unwrap_or("")); + }, + "view" => { + call = call.view(value.unwrap_or("")); + }, + "services" => { + call = call.add_services(value.unwrap_or("")); + }, + "request-metadata-user-overrides-user-id" => { + call = call.request_metadata_user_overrides_user_id(value.unwrap_or("")); + }, + "request-metadata-user-overrides-ip-address" => { + call = call.request_metadata_user_overrides_ip_address(value.unwrap_or("")); + }, + "request-metadata-traffic-source-traffic-sub-id" => { + call = call.request_metadata_traffic_source_traffic_sub_id(value.unwrap_or("")); + }, + "request-metadata-traffic-source-traffic-source-id" => { + call = call.request_metadata_traffic_source_traffic_source_id(value.unwrap_or("")); + }, + "request-metadata-partners-session-id" => { + call = call.request_metadata_partners_session_id(value.unwrap_or("")); + }, + "request-metadata-locale" => { + call = call.request_metadata_locale(value.unwrap_or("")); + }, + "request-metadata-experiment-ids" => { + call = call.add_request_metadata_experiment_ids(value.unwrap_or("")); + }, + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "page-size" => { + call = call.page_size(arg_from_str(value.unwrap_or("-0"), err, "page-size", "integer")); + }, + "order-by" => { + call = call.order_by(value.unwrap_or("")); + }, + "min-monthly-budget-units" => { + call = call.min_monthly_budget_units(value.unwrap_or("")); + }, + "min-monthly-budget-nanos" => { + call = call.min_monthly_budget_nanos(arg_from_str(value.unwrap_or("-0"), err, "min-monthly-budget-nanos", "integer")); + }, + "min-monthly-budget-currency-code" => { + call = call.min_monthly_budget_currency_code(value.unwrap_or("")); + }, + "max-monthly-budget-units" => { + call = call.max_monthly_budget_units(value.unwrap_or("")); + }, + "max-monthly-budget-nanos" => { + call = call.max_monthly_budget_nanos(arg_from_str(value.unwrap_or("-0"), err, "max-monthly-budget-nanos", "integer")); + }, + "max-monthly-budget-currency-code" => { + call = call.max_monthly_budget_currency_code(value.unwrap_or("")); + }, + "language-codes" => { + call = call.add_language_codes(value.unwrap_or("")); + }, + "industries" => { + call = call.add_industries(value.unwrap_or("")); + }, + "gps-motivations" => { + call = call.add_gps_motivations(value.unwrap_or("")); + }, + "company-name" => { + call = call.company_name(value.unwrap_or("")); + }, + "address" => { + call = call.address(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["order-by", "page-size", "request-metadata-partners-session-id", "max-monthly-budget-currency-code", "max-monthly-budget-nanos", "language-codes", "min-monthly-budget-nanos", "request-metadata-traffic-source-traffic-sub-id", "industries", "min-monthly-budget-currency-code", "min-monthly-budget-units", "page-token", "request-metadata-locale", "request-metadata-traffic-source-traffic-source-id", "company-name", "address", "services", "request-metadata-experiment-ids", "gps-motivations", "request-metadata-user-overrides-ip-address", "website-url", "request-metadata-user-overrides-user-id", "view", "max-monthly-budget-units"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _user_events_log(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "lead.gps-motivations" => Some(("lead.gpsMotivations", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "lead.family-name" => Some(("lead.familyName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "lead.min-monthly-budget.units" => Some(("lead.minMonthlyBudget.units", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "lead.min-monthly-budget.nanos" => Some(("lead.minMonthlyBudget.nanos", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "lead.min-monthly-budget.currency-code" => Some(("lead.minMonthlyBudget.currencyCode", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "lead.comments" => Some(("lead.comments", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "lead.email" => Some(("lead.email", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "lead.website-url" => Some(("lead.websiteUrl", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "lead.phone-number" => Some(("lead.phoneNumber", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "lead.given-name" => Some(("lead.givenName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "lead.type" => Some(("lead.type", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "lead.id" => Some(("lead.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "url" => Some(("url", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "event-action" => Some(("eventAction", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "event-category" => Some(("eventCategory", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "request-metadata.locale" => Some(("requestMetadata.locale", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "request-metadata.partners-session-id" => Some(("requestMetadata.partnersSessionId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "request-metadata.traffic-source.traffic-sub-id" => Some(("requestMetadata.trafficSource.trafficSubId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "request-metadata.traffic-source.traffic-source-id" => Some(("requestMetadata.trafficSource.trafficSourceId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "request-metadata.user-overrides.user-id" => Some(("requestMetadata.userOverrides.userId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "request-metadata.user-overrides.ip-address" => Some(("requestMetadata.userOverrides.ipAddress", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "request-metadata.experiment-ids" => Some(("requestMetadata.experimentIds", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "event-scope" => Some(("eventScope", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["comments", "currency-code", "email", "event-action", "event-category", "event-scope", "experiment-ids", "family-name", "given-name", "gps-motivations", "id", "ip-address", "lead", "locale", "min-monthly-budget", "nanos", "partners-session-id", "phone-number", "request-metadata", "traffic-source", "traffic-source-id", "traffic-sub-id", "type", "units", "url", "user-id", "user-overrides", "website-url"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::LogUserEventRequest = json::value::from_value(object).unwrap(); + let mut call = self.hub.user_events().log(request); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _user_states_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.user_states().list(); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "request-metadata-user-overrides-user-id" => { + call = call.request_metadata_user_overrides_user_id(value.unwrap_or("")); + }, + "request-metadata-user-overrides-ip-address" => { + call = call.request_metadata_user_overrides_ip_address(value.unwrap_or("")); + }, + "request-metadata-traffic-source-traffic-sub-id" => { + call = call.request_metadata_traffic_source_traffic_sub_id(value.unwrap_or("")); + }, + "request-metadata-traffic-source-traffic-source-id" => { + call = call.request_metadata_traffic_source_traffic_source_id(value.unwrap_or("")); + }, + "request-metadata-partners-session-id" => { + call = call.request_metadata_partners_session_id(value.unwrap_or("")); + }, + "request-metadata-locale" => { + call = call.request_metadata_locale(value.unwrap_or("")); + }, + "request-metadata-experiment-ids" => { + call = call.add_request_metadata_experiment_ids(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["request-metadata-user-overrides-user-id", "request-metadata-user-overrides-ip-address", "request-metadata-partners-session-id", "request-metadata-traffic-source-traffic-sub-id", "request-metadata-locale", "request-metadata-experiment-ids", "request-metadata-traffic-source-traffic-source-id"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _doit(&self, dry_run: bool) -> Result, Option> { + let mut err = InvalidOptionsError::new(); + let mut call_result: Result<(), DoitError> = Ok(()); + let mut err_opt: Option = None; + match self.opt.subcommand() { + ("client-messages", Some(opt)) => { + match opt.subcommand() { + ("log", Some(opt)) => { + call_result = self._client_messages_log(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("client-messages".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("companies", Some(opt)) => { + match opt.subcommand() { + ("get", Some(opt)) => { + call_result = self._companies_get(opt, dry_run, &mut err); + }, + ("leads-create", Some(opt)) => { + call_result = self._companies_leads_create(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._companies_list(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("companies".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("user-events", Some(opt)) => { + match opt.subcommand() { + ("log", Some(opt)) => { + call_result = self._user_events_log(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("user-events".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("user-states", Some(opt)) => { + match opt.subcommand() { + ("list", Some(opt)) => { + call_result = self._user_states_list(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("user-states".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + _ => { + err.issues.push(CLIError::MissingCommandError); + writeln!(io::stderr(), "{}\n", self.opt.usage()).ok(); + } + } + + if dry_run { + if err.issues.len() > 0 { + err_opt = Some(err); + } + Err(err_opt) + } else { + Ok(call_result) + } + } + + // Please note that this call will fail if any part of the opt can't be handled + fn new(opt: ArgMatches<'a, 'n>) -> Result, InvalidOptionsError> { + let (config_dir, secret) = { + let config_dir = match cmn::assure_config_dir_exists(opt.value_of("folder").unwrap_or("~/.google-service-cli")) { + Err(e) => return Err(InvalidOptionsError::single(e, 3)), + Ok(p) => p, + }; + + match cmn::application_secret_from_directory(&config_dir, "partners2-secret.json", + "{\"installed\":{\"auth_uri\":\"https://accounts.google.com/o/oauth2/auth\",\"client_secret\":\"hCsslbCUyfehWMmbkG8vTYxG\",\"token_uri\":\"https://accounts.google.com/o/oauth2/token\",\"client_email\":\"\",\"redirect_uris\":[\"urn:ietf:wg:oauth:2.0:oob\",\"oob\"],\"client_x509_cert_url\":\"\",\"client_id\":\"620010449518-9ngf7o4dhs0dka470npqvor6dc5lqb9b.apps.googleusercontent.com\",\"auth_provider_x509_cert_url\":\"https://www.googleapis.com/oauth2/v1/certs\"}}") { + Ok(secret) => (config_dir, secret), + Err(e) => return Err(InvalidOptionsError::single(e, 4)) + } + }; + + let auth = Authenticator::new( &secret, DefaultAuthenticatorDelegate, + if opt.is_present("debug-auth") { + hyper::Client::with_connector(mock::TeeConnector { + connector: hyper::net::HttpsConnector::::default() + }) + } else { + hyper::Client::new() + }, + JsonTokenStorage { + program_name: "partners2", + db_dir: config_dir.clone(), + }, None); + + let client = + if opt.is_present("debug") { + hyper::Client::with_connector(mock::TeeConnector { + connector: hyper::net::HttpsConnector::::default() + }) + } else { + hyper::Client::new() + }; + let engine = Engine { + opt: opt, + hub: api::Partners::new(client, auth), + gp: vec!["$-xgafv", "access-token", "alt", "bearer-token", "callback", "fields", "key", "oauth-token", "pp", "pretty-print", "quota-user", "upload-type", "upload-protocol"], + gpm: vec![ + ("$-xgafv", "$.xgafv"), + ("access-token", "access_token"), + ("bearer-token", "bearer_token"), + ("oauth-token", "oauth_token"), + ("pretty-print", "prettyPrint"), + ("quota-user", "quotaUser"), + ("upload-type", "uploadType"), + ("upload-protocol", "upload_protocol"), + ] + }; + + match engine._doit(true) { + Err(Some(err)) => Err(err), + Err(None) => Ok(engine), + Ok(_) => unreachable!(), + } + } + + fn doit(&self) -> Result<(), DoitError> { + match self._doit(false) { + Ok(res) => res, + Err(_) => unreachable!(), + } + } +} + +fn main() { + let mut exit_status = 0i32; + let arg_data = [ + ("client-messages", "methods: 'log'", vec![ + ("log", + Some(r##"Logs a generic message from the client, such as `Failed to render component`, `Profile page is running slow`, `More than 500 users have accessed this result.`, etc."##), + "Details at http://byron.github.io/google-apis-rs/google_partners2_cli/client-messages_log", + vec![ + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("companies", "methods: 'get', 'leads-create' and 'list'", vec![ + ("get", + Some(r##"Gets a company."##), + "Details at http://byron.github.io/google-apis-rs/google_partners2_cli/companies_get", + vec![ + (Some(r##"company-id"##), + None, + Some(r##"The ID of the company to retrieve."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("leads-create", + Some(r##"Creates an advertiser lead for the given company ID."##), + "Details at http://byron.github.io/google-apis-rs/google_partners2_cli/companies_leads-create", + vec![ + (Some(r##"company-id"##), + None, + Some(r##"The ID of the company to contact."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Lists companies."##), + "Details at http://byron.github.io/google-apis-rs/google_partners2_cli/companies_list", + vec![ + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("user-events", "methods: 'log'", vec![ + ("log", + Some(r##"Logs a user event."##), + "Details at http://byron.github.io/google-apis-rs/google_partners2_cli/user-events_log", + vec![ + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("user-states", "methods: 'list'", vec![ + ("list", + Some(r##"Lists states for current user."##), + "Details at http://byron.github.io/google-apis-rs/google_partners2_cli/user-states_list", + vec![ + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ]; + + let mut app = App::new("partners2") + .author("Sebastian Thiel ") + .version("0.3.2+20151009") + .about("Lets advertisers search certified companies and create contact leads with them, and also audits the usage of clients.") + .after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_partners2_cli") + .arg(Arg::with_name("folder") + .long("config-dir") + .help("A directory into which we will store our persistent data. Defaults to a user-writable directory that we will create during the first invocation.[default: ~/.google-service-cli") + .multiple(false) + .takes_value(true)) + .arg(Arg::with_name("debug") + .long("debug") + .help("Output all server communication to standard error. `tx` and `rx` are placed into the same stream.") + .multiple(false) + .takes_value(false)) + .arg(Arg::with_name("debug-auth") + .long("debug-auth") + .help("Output all communication related to authentication to standard error. `tx` and `rx` are placed into the same stream.") + .multiple(false) + .takes_value(false)); + + for &(main_command_name, ref about, ref subcommands) in arg_data.iter() { + let mut mcmd = SubCommand::with_name(main_command_name).about(about); + + for &(sub_command_name, ref desc, url_info, ref args) in subcommands { + let mut scmd = SubCommand::with_name(sub_command_name); + if let &Some(desc) = desc { + scmd = scmd.about(desc); + } + scmd = scmd.after_help(url_info); + + for &(ref arg_name, ref flag, ref desc, ref required, ref multi) in args { + let arg_name_str = + match (arg_name, flag) { + (&Some(an), _ ) => an, + (_ , &Some(f)) => f, + _ => unreachable!(), + }; + let mut arg = Arg::with_name(arg_name_str) + .empty_values(false); + if let &Some(short_flag) = flag { + arg = arg.short(short_flag); + } + if let &Some(desc) = desc { + arg = arg.help(desc); + } + if arg_name.is_some() && flag.is_some() { + arg = arg.takes_value(true); + } + if let &Some(required) = required { + arg = arg.required(required); + } + if let &Some(multi) = multi { + arg = arg.multiple(multi); + } + scmd = scmd.arg(arg); + } + mcmd = mcmd.subcommand(scmd); + } + app = app.subcommand(mcmd); + } + + let matches = app.get_matches(); + + let debug = matches.is_present("debug"); + match Engine::new(matches) { + Err(err) => { + exit_status = err.exit_code; + writeln!(io::stderr(), "{}", err).ok(); + }, + Ok(engine) => { + if let Err(doit_err) = engine.doit() { + exit_status = 1; + match doit_err { + DoitError::IoError(path, err) => { + writeln!(io::stderr(), "Failed to open output file '{}': {}", path, err).ok(); + }, + DoitError::ApiError(err) => { + if debug { + writeln!(io::stderr(), "{:#?}", err).ok(); + } else { + writeln!(io::stderr(), "{}", err).ok(); + } + } + } + } + } + } + + std::process::exit(exit_status); +} \ No newline at end of file diff --git a/gen/partners2/Cargo.toml b/gen/partners2/Cargo.toml new file mode 100644 index 0000000000..44a9ec13da --- /dev/null +++ b/gen/partners2/Cargo.toml @@ -0,0 +1,29 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-partners2" +version = "0.1.9+20151009" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with partners (protocol v2)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/partners2" +homepage = "https://developers.google.com/partners/" +documentation = "http://byron.github.io/google-apis-rs/google_partners2" +license = "MIT" +keywords = ["partners", "google", "protocol", "web", "api"] +build = "src/build.rs" + + +[dependencies] +hyper = ">= 0.6.8" +mime = "0.1.0" +serde = ">= 0.6.0" +serde_json = ">= 0.6.0" +yup-oauth2 = "*" +url = "*" + +[build-dependencies] +syntex = { version = "*" } +serde_codegen = { version = "*" } + diff --git a/gen/partners2/LICENSE.md b/gen/partners2/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/partners2/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/partners2/README.md b/gen/partners2/README.md new file mode 100644 index 0000000000..6d60f8791c --- /dev/null +++ b/gen/partners2/README.md @@ -0,0 +1,185 @@ + +The `google-partners2` library allows access to all features of the *Google partners* service. + +This documentation was generated from *partners* crate version *0.1.9+20151009*, where *20151009* is the exact revision of the *partners:v2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. + +Everything else about the *partners* *v2* API can be found at the +[official documentation site](https://developers.google.com/partners/). +# Features + +Handle the following *Resources* with ease from the central [hub](http://byron.github.io/google-apis-rs/google_partners2/struct.Partners.html) ... + +* client messages + * [*log*](http://byron.github.io/google-apis-rs/google_partners2/struct.ClientMessageLogCall.html) +* [companies](http://byron.github.io/google-apis-rs/google_partners2/struct.Company.html) + * [*get*](http://byron.github.io/google-apis-rs/google_partners2/struct.CompanyGetCall.html), [*leads create*](http://byron.github.io/google-apis-rs/google_partners2/struct.CompanyLeadCreateCall.html) and [*list*](http://byron.github.io/google-apis-rs/google_partners2/struct.CompanyListCall.html) +* user events + * [*log*](http://byron.github.io/google-apis-rs/google_partners2/struct.UserEventLogCall.html) +* user states + * [*list*](http://byron.github.io/google-apis-rs/google_partners2/struct.UserStateListCall.html) + + + + +# Structure of this Library + +The API is structured into the following primary items: + +* **[Hub](http://byron.github.io/google-apis-rs/google_partners2/struct.Partners.html)** + * a central object to maintain state and allow accessing all *Activities* + * creates [*Method Builders*](http://byron.github.io/google-apis-rs/google_partners2/trait.MethodsBuilder.html) which in turn + allow access to individual [*Call Builders*](http://byron.github.io/google-apis-rs/google_partners2/trait.CallBuilder.html) +* **[Resources](http://byron.github.io/google-apis-rs/google_partners2/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_partners2/trait.Part.html)** + * a collection of properties + * never directly used in *Activities* +* **[Activities](http://byron.github.io/google-apis-rs/google_partners2/trait.CallBuilder.html)** + * operations to apply to *Resources* + +All *structures* are marked with applicable traits to further categorize them and ease browsing. + +Generally speaking, you can invoke *Activities* like this: + +```Rust,ignore +let r = hub.resource().activity(...).doit() +``` + +Or specifically ... + +```ignore +let r = hub.user_events().log(...).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-partners2 = "*" +``` + +## A complete example + +```Rust +extern crate hyper; +extern crate yup_oauth2 as oauth2; +extern crate google_partners2 as partners2; +use partners2::LogUserEventRequest; +use partners2::{Result, Error}; +use std::default::Default; +use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +use partners2::Partners; + +// 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 = Partners::new(hyper::Client::new(), auth); +// As the method needs a request, you would usually fill it with the desired information +// into the respective structure. Some of the parts shown here might not be applicable ! +// Values shown here are possibly random and not representative ! +let mut req = LogUserEventRequest::default(); + +// You can configure optional parameters by calling 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_events().log(req) + .doit(); + +match result { + Err(e) => match e { + // The Error enum provides details about what exactly happened. + // You can also just use its `Debug`, `Display` or `Error` traits + Error::HttpError(_) + |Error::MissingAPIKey + |Error::MissingToken(_) + |Error::Cancelled + |Error::UploadSizeLimitExceeded(_, _) + |Error::Failure(_) + |Error::BadRequest(_) + |Error::FieldClash(_) + |Error::JsonDecodeError(_, _) => println!("{}", e), + }, + Ok(res) => println!("Success: {:?}", res), +} + +``` +## Handling Errors + +All errors produced by the system are provided either as [Result](http://byron.github.io/google-apis-rs/google_partners2/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_partners2/trait.Delegate.html), or the [Authenticator Delegate](http://byron.github.io/google-apis-rs/google_partners2/../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 Downloads +If a method supports downloads, the response body, which is part of the [Result](http://byron.github.io/google-apis-rs/google_partners2/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_partners2/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_partners2/trait.Delegate.html) to the +[Method Builder](http://byron.github.io/google-apis-rs/google_partners2/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_partners2/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_partners2/trait.RequestValue.html) and +[decodable](http://byron.github.io/google-apis-rs/google_partners2/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_partners2/trait.Part.html) which are identifiable 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_partners2/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_partners2/trait.RequestValue.html) are moved + +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 **partners2** 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/partners2/src/build.rs b/gen/partners2/src/build.rs new file mode 100644 index 0000000000..406272c4a4 --- /dev/null +++ b/gen/partners2/src/build.rs @@ -0,0 +1,16 @@ +extern crate syntex; +extern crate serde_codegen; + +use std::env; +use std::path::Path; + +pub fn main() { + let out_dir = env::var_os("OUT_DIR").unwrap(); + + let src = Path::new("src/lib.rs.in"); + let dst = Path::new(&out_dir).join("lib.rs"); + + let mut registry = syntex::Registry::new(); + serde_codegen::register(&mut registry); + registry.expand("google-partners2", &src, &dst).unwrap(); +} diff --git a/gen/partners2/src/cmn.rs b/gen/partners2/src/cmn.rs new file mode 100644 index 0000000000..0e31353ba3 --- /dev/null +++ b/gen/partners2/src/cmn.rs @@ -0,0 +1,762 @@ +// COPY OF 'src/rust/api/cmn.rs' +// DO NOT EDIT +use std::io::{self, Read, Seek, Cursor, Write, SeekFrom}; +use std; +use std::fmt::{self, Display}; +use std::str::FromStr; +use std::error; +use std::thread::sleep_ms; + +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::h1::LINE_ENDING; +use hyper::method::Method; +use hyper::status::StatusCode; + +use serde_json as json; + +/// 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 {} + +/// Identifies types for building methods of a particular resource type +pub trait MethodsBuilder {} + +/// Identifies types which represent builders for a particular resource method +pub trait CallBuilder {} + +/// Identifies types which can be inserted and deleted. +/// Types with this trait are most commonly used by clients of this API. +pub trait Resource {} + +/// Identifies types which are used in API responses. +pub trait ResponseResult {} + +/// Identifies types which are used in API requests. +pub trait RequestValue {} + +/// Identifies types which are not actually used by the API +/// This might be a bug within the google API schema. +pub trait UnusedType {} + +/// Identifies types which are only used as part of other types, which +/// usually are carrying the `Resource` trait. +pub trait Part {} + +/// 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 {} + +/// 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 +} + +/// A utility to represent detailed errors we might see in case there are BadRequests. +/// The latter happen if the sent parameters or request structures are unsound +#[derive(Deserialize, Serialize, Debug)] +pub struct ErrorResponse { + error: ServerError, +} + +#[derive(Deserialize, Serialize, Debug)] +pub struct ServerError { + errors: Vec, + code: u16, + message: String, +} + +#[derive(Deserialize, Serialize, Debug)] +pub struct ServerMessage { + domain: String, + reason: String, + message: String, + #[serde(rename="locationType")] + location_type: Option, + location: 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 successful. That way, the delegate 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. + /// + /// If you choose to retry after a duration, the duration should be chosen using the + /// [exponential backoff algorithm](http://en.wikipedia.org/wiki/Exponential_backoff). + /// + /// Return retry information. + fn http_error(&mut self, &hyper::Error) -> 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 it as a general information about the + /// impending failure. + /// The given Error provides information about why the token couldn't be acquired in the + /// first place + fn token(&mut self, err: &error::Error) -> Option { + let _ = err; + 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/canceled, 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()`. + /// It will also be called with None after a successful upload, which allows the delegate + /// to forget the URL. That way, we will not attempt to resume an upload that has already + /// finished. + fn store_upload_url(&mut self, url: Option<&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: &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. + /// + /// If you choose to retry after a duration, the duration should be chosen using the + /// [exponential backoff algorithm](http://en.wikipedia.org/wiki/Exponential_backoff). + fn http_failure(&mut self, _: &hyper::client::Response, Option, _: 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 {} + + +#[derive(Debug)] +pub enum Error { + /// The http connection failed + HttpError(hyper::Error), + + /// 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), + + /// Represents information about a request that was not understood by the server. + /// Details are included. + BadRequest(ErrorResponse), + + /// 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(Box), + + /// 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(String, json::Error), + + /// Indicates an HTTP repsonse with a non-success status code + Failure(hyper::client::Response), +} + + +impl Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + Error::HttpError(ref err) => err.fmt(f), + Error::UploadSizeLimitExceeded(ref resource_size, ref max_size) => + writeln!(f, "The media size {} exceeds the maximum allowed upload size of {}" + , resource_size, max_size), + Error::MissingAPIKey => { + (writeln!(f, "The application's API key was not found in the configuration")).ok(); + writeln!(f, "It is used as there are no Scopes defined for this method.") + }, + Error::BadRequest(ref err) => { + try!(writeln!(f, "Bad Requst ({}): {}", err.error.code, err.error.message)); + for err in err.error.errors.iter() { + try!(writeln!(f, " {}: {}, {}{}", + err.domain, + err.message, + err.reason, + match &err.location { + &Some(ref loc) => format!("@{}", loc), + &None => String::new(), + })); + } + Ok(()) + }, + Error::MissingToken(ref err) => + writeln!(f, "Token retrieval failed with error: {}", err), + Error::Cancelled => + writeln!(f, "Operation cancelled by delegate"), + Error::FieldClash(field) => + writeln!(f, "The custom parameter '{}' is already provided natively by the CallBuilder.", field), + Error::JsonDecodeError(ref json_str, ref err) + => writeln!(f, "{}: {}", err, json_str), + Error::Failure(ref response) => + writeln!(f, "Http status indicates failure: {:?}", response), + } + } +} + +impl error::Error for Error { + fn description(&self) -> &str { + match *self { + Error::HttpError(ref err) => err.description(), + Error::JsonDecodeError(_, ref err) => err.description(), + _ => "NO DESCRIPTION POSSIBLE - use `Display.fmt()` instead" + } + } + + fn cause(&self) -> Option<&error::Error> { + match *self { + Error::HttpError(ref err) => err.cause(), + Error::JsonDecodeError(_, ref err) => err.cause(), + _ => None + } + } +} + +/// A universal result type used as return for all calls. +pub type Result = std::result::Result; + +/// 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 + 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 following macro invocation needs to be expanded, as `include!` +// doens't support external macros +// header!{ +// #[doc="The `X-Upload-Content-Type` header."] +// (XUploadContentType, "X-Upload-Content-Type") => [Mime] + +// xupload_content_type { +// test_header!( +// test1, +// vec![b"text/plain"], +// Some(HeaderField( +// vec![Mime(TopLevel::Text, SubLevel::Plain, Vec::new())] +// ))); + +// } +// } + +/// The `X-Upload-Content-Type` header. +/// +/// Generated via rustc --pretty expanded -Z unstable-options, and manually +/// processed to be more readable. +#[derive(PartialEq, Debug, Clone)] +pub struct XUploadContentType(pub Mime); + +impl ::std::ops::Deref for XUploadContentType { + type Target = Mime; + fn deref<'a>(&'a self) -> &'a Mime { &self.0 } +} +impl ::std::ops::DerefMut for XUploadContentType { + fn deref_mut<'a>(&'a mut self) -> &'a mut Mime { &mut self.0 } +} +impl Header for XUploadContentType { + fn header_name() -> &'static str { "X-Upload-Content-Type" } + fn parse_header(raw: &[Vec]) -> hyper::error::Result { + hyper::header::parsing::from_one_raw_str(raw).map(XUploadContentType) + } +} +impl HeaderFormat for XUploadContentType { + fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { + Display::fmt(&**self, f) + } +} +impl Display for XUploadContentType { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Display::fmt(&**self, f) + } +} + +#[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]) -> hyper::error::Result { + Err(hyper::error::Error::Method) + } +} + + +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]) -> hyper::error::Result { + if raw.len() > 0 { + let v = &raw[0]; + if let Ok(s) = std::str::from_utf8(v) { + const PREFIX: &'static str = "bytes "; + if s.starts_with(PREFIX) { + if let Ok(c) = ::from_str(&s[PREFIX.len()..]) { + return Ok(RangeResponseHeader(c)) + } + } + } + } + Err(hyper::error::Error::Method) + } +} + +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, 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, A> ResumableUploadHelper<'a, A> + where A: oauth2::GetToken { + + fn query_transfer_status(&mut self) -> std::result::Result> { + 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, None) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + return Err(Ok(r)) + } + }; + return Ok(h.0.last) + } + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + return Err(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() { + Ok(s) => s, + Err(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 + }; + + self.reader.seek(SeekFrom::Start(start)).unwrap(); + loop { + let request_size = match self.content_length - start { + rs if rs > chunk_size => chunk_size, + rs => rs + }; + + 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 + } + // workaround https://github.com/rust-lang/rust/issues/22252 + let res = 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(); + match res { + 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, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + } + return Some(Ok(res)) + }, + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + return Some(Err(err)) + } + } + } + } +} + +// Copy of src/rust/cli/cmn.rs +// TODO(ST): Allow sharing common code between program types +pub fn remove_json_null_values(value: &mut json::value::Value) { + match *value { + json::value::Value::Object(ref mut map) => { + let mut for_removal = Vec::new(); + + for (key, mut value) in map.iter_mut() { + if value.is_null() { + for_removal.push(key.clone()); + } else { + remove_json_null_values(&mut value); + } + } + + for key in &for_removal { + map.remove(key); + } + } + _ => {} + } +} diff --git a/gen/partners2/src/lib.rs b/gen/partners2/src/lib.rs new file mode 100644 index 0000000000..1884647878 --- /dev/null +++ b/gen/partners2/src/lib.rs @@ -0,0 +1,189 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/api/lib.rs.mako' +// DO NOT EDIT ! + +//! This documentation was generated from *partners* crate version *0.1.9+20151009*, where *20151009* is the exact revision of the *partners:v2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +//! +//! Everything else about the *partners* *v2* API can be found at the +//! [official documentation site](https://developers.google.com/partners/). +//! The original source code is [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/partners2). +//! # Features +//! +//! Handle the following *Resources* with ease from the central [hub](struct.Partners.html) ... +//! +//! * client messages +//! * [*log*](struct.ClientMessageLogCall.html) +//! * [companies](struct.Company.html) +//! * [*get*](struct.CompanyGetCall.html), [*leads create*](struct.CompanyLeadCreateCall.html) and [*list*](struct.CompanyListCall.html) +//! * user events +//! * [*log*](struct.UserEventLogCall.html) +//! * user states +//! * [*list*](struct.UserStateListCall.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.Partners.html)** +//! * a central object to maintain state and allow accessing all *Activities* +//! * creates [*Method Builders*](trait.MethodsBuilder.html) which in turn +//! allow access to individual [*Call Builders*](trait.CallBuilder.html) +//! * **[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* +//! +//! All *structures* are marked with applicable traits to further categorize them and ease browsing. +//! +//! Generally speaking, you can invoke *Activities* like this: +//! +//! ```Rust,ignore +//! let r = hub.resource().activity(...).doit() +//! ``` +//! +//! Or specifically ... +//! +//! ```ignore +//! let r = hub.user_events().log(...).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-partners2 = "*" +//! ``` +//! +//! ## A complete example +//! +//! ```test_harness,no_run +//! extern crate hyper; +//! extern crate yup_oauth2 as oauth2; +//! extern crate google_partners2 as partners2; +//! use partners2::LogUserEventRequest; +//! use partners2::{Result, Error}; +//! # #[test] fn egal() { +//! use std::default::Default; +//! use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +//! use partners2::Partners; +//! +//! // 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 = Partners::new(hyper::Client::new(), auth); +//! // As the method needs a request, you would usually fill it with the desired information +//! // into the respective structure. Some of the parts shown here might not be applicable ! +//! // Values shown here are possibly random and not representative ! +//! let mut req = LogUserEventRequest::default(); +//! +//! // You can configure optional parameters by calling 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_events().log(req) +//! .doit(); +//! +//! match result { +//! Err(e) => match e { +//! // The Error enum provides details about what exactly happened. +//! // You can also just use its `Debug`, `Display` or `Error` traits +//! Error::HttpError(_) +//! |Error::MissingAPIKey +//! |Error::MissingToken(_) +//! |Error::Cancelled +//! |Error::UploadSizeLimitExceeded(_, _) +//! |Error::Failure(_) +//! |Error::BadRequest(_) +//! |Error::FieldClash(_) +//! |Error::JsonDecodeError(_, _) => println!("{}", e), +//! }, +//! Ok(res) => println!("Success: {:?}", res), +//! } +//! # } +//! ``` +//! ## 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 Downloads +//! 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 identifiable 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 moved +//! +//! 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 +//! +//! + +// 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)] + +include!(concat!(env!("OUT_DIR"), "/lib.rs")); \ No newline at end of file diff --git a/gen/partners2/src/lib.rs.in b/gen/partners2/src/lib.rs.in new file mode 100644 index 0000000000..f08264695a --- /dev/null +++ b/gen/partners2/src/lib.rs.in @@ -0,0 +1,2824 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/api/lib.rs.in.mako' +// DO NOT EDIT ! + +extern crate hyper; +extern crate serde; +extern crate serde_json; +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 serde_json as json; +use std::io; +use std::fs; +use std::thread::sleep_ms; + +pub use cmn::{MultiPartReader, ToParts, MethodInfo, Result, Error, CallBuilder, Hub, ReadSeek, Part, + ResponseResult, RequestValue, NestedType, Delegate, DefaultDelegate, MethodsBuilder, + Resource, ErrorResponse, remove_json_null_values}; + + +// ############## +// UTILITIES ### +// ############ + + + + +// ######## +// HUB ### +// ###### + +/// Central instance to access all Partners related resource activities +/// +/// # Examples +/// +/// Instantiate a new hub +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate yup_oauth2 as oauth2; +/// extern crate google_partners2 as partners2; +/// use partners2::LogUserEventRequest; +/// use partners2::{Result, Error}; +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use partners2::Partners; +/// +/// // 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 = Partners::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req = LogUserEventRequest::default(); +/// +/// // You can configure optional parameters by calling 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_events().log(req) +/// .doit(); +/// +/// match result { +/// Err(e) => match e { +/// // The Error enum provides details about what exactly happened. +/// // You can also just use its `Debug`, `Display` or `Error` traits +/// Error::HttpError(_) +/// |Error::MissingAPIKey +/// |Error::MissingToken(_) +/// |Error::Cancelled +/// |Error::UploadSizeLimitExceeded(_, _) +/// |Error::Failure(_) +/// |Error::BadRequest(_) +/// |Error::FieldClash(_) +/// |Error::JsonDecodeError(_, _) => println!("{}", e), +/// }, +/// Ok(res) => println!("Success: {:?}", res), +/// } +/// # } +/// ``` +pub struct Partners { + client: RefCell, + auth: RefCell, + _user_agent: String, +} + +impl<'a, C, A> Hub for Partners {} + +impl<'a, C, A> Partners + where C: BorrowMut, A: oauth2::GetToken { + + pub fn new(client: C, authenticator: A) -> Partners { + Partners { + client: RefCell::new(client), + auth: RefCell::new(authenticator), + _user_agent: "google-api-rust-client/0.1.9".to_string(), + } + } + + pub fn client_messages(&'a self) -> ClientMessageMethods<'a, C, A> { + ClientMessageMethods { hub: &self } + } + pub fn companies(&'a self) -> CompanyMethods<'a, C, A> { + CompanyMethods { hub: &self } + } + pub fn user_events(&'a self) -> UserEventMethods<'a, C, A> { + UserEventMethods { hub: &self } + } + pub fn user_states(&'a self) -> UserStateMethods<'a, C, A> { + UserStateMethods { 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.9`. + /// + /// 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 message for LogUserEvent. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [log user events](struct.UserEventLogCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct LogUserEventResponse { + /// Current response metadata. + #[serde(rename="responseMetadata")] + pub response_metadata: Option, +} + +impl ResponseResult for LogUserEventResponse {} + + +/// Source of traffic for the current request. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct TrafficSource { + /// Second level identifier to indicate where the traffic comes from. An identifier has multiple letters created by a team which redirected the traffic to us. + #[serde(rename="trafficSubId")] + pub traffic_sub_id: Option, + /// Identifier to indicate where the traffic comes from. An identifier has multiple letters created by a team which redirected the traffic to us. + #[serde(rename="trafficSourceId")] + pub traffic_source_id: Option, +} + +impl Part for TrafficSource {} + + +/// Google Partners certification status. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct CertificationStatus { + /// The type of the certification. + #[serde(rename="type")] + pub type_: Option, + /// Whether certification is passing. + #[serde(rename="isCertified")] + pub is_certified: Option, + /// List of certification exam statuses. + #[serde(rename="examStatuses")] + pub exam_statuses: Option>, +} + +impl Part for CertificationStatus {} + + +/// Response message for LogClientMessage. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [log client messages](struct.ClientMessageLogCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct LogMessageResponse { + /// Current response metadata. + #[serde(rename="responseMetadata")] + pub response_metadata: Option, +} + +impl ResponseResult for LogMessageResponse {} + + +/// Values to use instead of the user's respective defaults. These are only honored by whitelisted products. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct UserOverrides { + /// IP address to use instead of the user's geo-located IP address. + #[serde(rename="ipAddress")] + pub ip_address: Option, + /// Logged-in user ID to impersonate instead of the user's ID. + #[serde(rename="userId")] + pub user_id: Option, +} + +impl Part for UserOverrides {} + + +/// A lead resource that represents an advertiser contact for a `Company`. These are usually generated via Google Partner Search (the advertiser portal). +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Lead { + /// List of reasons for using Google Partner Search and creating a lead. + #[serde(rename="gpsMotivations")] + pub gps_motivations: Option>, + /// Last name of lead source. + #[serde(rename="familyName")] + pub family_name: Option, + /// The minimum monthly budget lead source is willing to spend. + #[serde(rename="minMonthlyBudget")] + pub min_monthly_budget: Option, + /// Comments lead source gave. + pub comments: Option, + /// ID of the lead. + pub id: Option, + /// Website URL of lead source. + #[serde(rename="websiteUrl")] + pub website_url: Option, + /// Phone number of lead source. + #[serde(rename="phoneNumber")] + pub phone_number: Option, + /// First name of lead source. + #[serde(rename="givenName")] + pub given_name: Option, + /// Type of lead. + #[serde(rename="type")] + pub type_: Option, + /// Email address of lead source. + pub email: Option, +} + +impl Part for Lead {} + + +/// Debug information about this request. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct DebugInfo { + /// Server-side debug stack trace. + #[serde(rename="serverTraceInfo")] + pub server_trace_info: Option, + /// URL of the service that handled this request. + #[serde(rename="serviceUrl")] + pub service_url: Option, + /// Info about the server that serviced this request. + #[serde(rename="serverInfo")] + pub server_info: Option, +} + +impl Part for DebugInfo {} + + +/// Request message for LogUserEvent. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [log user events](struct.UserEventLogCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct LogUserEventRequest { + /// Current request metadata. + #[serde(rename="requestMetadata")] + pub request_metadata: Option, + /// Advertiser lead information. + pub lead: Option, + /// The URL where the event occurred. + pub url: Option, + /// List of event data for the event. + #[serde(rename="eventDatas")] + pub event_datas: Option>, + /// The action that occurred. + #[serde(rename="eventAction")] + pub event_action: Option, + /// The scope of the event. + #[serde(rename="eventScope")] + pub event_scope: Option, + /// The category the action belongs to. + #[serde(rename="eventCategory")] + pub event_category: Option, +} + +impl RequestValue for LogUserEventRequest {} + + +/// The localized company 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 LocalizedCompanyInfo { + /// List of country codes for the localized company info. + #[serde(rename="countryCodes")] + pub country_codes: Option>, + /// Language code of the localized company info, as defined by BCP 47 (IETF BCP 47, "Tags for Identifying Languages"). + #[serde(rename="languageCode")] + pub language_code: Option, + /// Localized display name. + #[serde(rename="displayName")] + pub display_name: Option, + /// Localized brief description that the company uses to advertise themselves. + pub overview: Option, +} + +impl Part for LocalizedCompanyInfo {} + + +/// A location with address and geographic coordinates. +/// +/// 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 { + /// The latitude and longitude of the location, in degrees. + #[serde(rename="latLng")] + pub lat_lng: Option, + /// The complete address of the location. + pub address: Option, +} + +impl Part for Location {} + + +/// Response message for ListCompanies. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where 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 companies](struct.CompanyListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ListCompaniesResponse { + /// A token to retrieve next page of results. Pass this value in the `ListCompaniesRequest.page_token` field in the subsequent call to ListCompanies to retrieve the next page of results. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// The list of companies. + pub companies: Option>, + /// Current response metadata. + #[serde(rename="responseMetadata")] + pub response_metadata: Option, +} + +impl ResponseResult for ListCompaniesResponse {} + + +/// reCaptcha challenge info. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct RecaptchaChallenge { + /// The ID of the reCaptcha challenge. + pub id: Option, + /// The response to the reCaptcha challenge. + pub response: Option, +} + +impl Part for RecaptchaChallenge {} + + +/// Status for a Google Partners certification exam. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct CertificationExamStatus { + /// The number of people who have passed the certification exam. + #[serde(rename="numberUsersPass")] + pub number_users_pass: Option, + /// The type of certification exam. + #[serde(rename="type")] + pub type_: Option, +} + +impl Part for CertificationExamStatus {} + + +/// Response message for CreateLead. Debug information about this 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*). +/// +/// * [leads create companies](struct.CompanyLeadCreateCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct CreateLeadResponse { + /// Lead that was created depending on the outcome of reCaptcha validation. + pub lead: Option, + /// The outcome of reCaptcha validation. + #[serde(rename="recaptchaStatus")] + pub recaptcha_status: Option, + /// Current response metadata. + #[serde(rename="responseMetadata")] + pub response_metadata: Option, +} + +impl ResponseResult for CreateLeadResponse {} + + +/// Represents an amount of money with its currency 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 Money { + /// The whole units of the amount. For example if `currencyCode` is `"USD"`, then 1 unit is one US dollar. + pub units: Option, + /// Number of nano (10^-9) units of the amount. The value must be between -999,999,999 and +999,999,999 inclusive. If `units` is positive, `nanos` must be positive or zero. If `units` is zero, `nanos` can be positive, zero, or negative. If `units` is negative, `nanos` must be negative or zero. For example $-1.75 is represented as `units`=-1 and `nanos`=-750,000,000. + pub nanos: Option, + /// The 3-letter currency code defined in ISO 4217. + #[serde(rename="currencyCode")] + pub currency_code: Option, +} + +impl Part for Money {} + + +/// A company resource in the Google Partners API. Once certified, it qualifies for being searched by advertisers. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Company { + /// Industries the company can help with. + pub industries: Option>, + /// The unconverted minimum monthly budget that the company accepts for partner business. + #[serde(rename="originalMinMonthlyBudget")] + pub original_min_monthly_budget: Option, + /// The minimum monthly budget that the company accepts for partner business, converted to the requested currency code. + #[serde(rename="convertedMinMonthlyBudget")] + pub converted_min_monthly_budget: Option, + /// The name of the company. + pub name: Option, + /// The list of localized info for the company. + #[serde(rename="localizedInfos")] + pub localized_infos: Option>, + /// The list of company locations. + pub locations: Option>, + /// URL of the company's website. + #[serde(rename="websiteUrl")] + pub website_url: Option, + /// Information related to the ranking of the company within the list of companies. + pub ranks: Option>, + /// Services the company can help with. + pub services: Option>, + /// The list of Google Partners certification statuses for the company. + #[serde(rename="certificationStatuses")] + pub certification_statuses: Option>, + /// Basic information from the company's public profile. + #[serde(rename="publicProfile")] + pub public_profile: Option, + /// The ID of the company. + pub id: Option, +} + +impl Part for Company {} + + +/// Request message for LogClientMessage. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [log client messages](struct.ClientMessageLogCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct LogMessageRequest { + /// Current request metadata. + #[serde(rename="requestMetadata")] + pub request_metadata: Option, + /// Map of client info, such as URL, browser navigator, browser platform, etc. + #[serde(rename="clientInfo")] + pub client_info: Option>, + /// Details about the client message. + pub details: Option, + /// Message level of client message. + pub level: Option, +} + +impl RequestValue for LogMessageRequest {} + + +/// Response message for GetCompany. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where 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 companies](struct.CompanyGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct GetCompanyResponse { + /// The company. + pub company: Option, + /// Current response metadata. + #[serde(rename="responseMetadata")] + pub response_metadata: Option, +} + +impl ResponseResult for GetCompanyResponse {} + + +/// Information related to ranking of results. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Rank { + /// The type of rank. + #[serde(rename="type")] + pub type_: Option, + /// The numerical value of the rank. + pub value: Option, +} + +impl Part for Rank {} + + +/// Request message for CreateLead. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [leads create companies](struct.CompanyLeadCreateCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct CreateLeadRequest { + /// Current request metadata. + #[serde(rename="requestMetadata")] + pub request_metadata: Option, + /// reCaptcha challenge info. + #[serde(rename="recaptchaChallenge")] + pub recaptcha_challenge: Option, + /// The lead resource. The `LeadType` must not be `LEAD_TYPE_UNSPECIFIED` and either `email` or `phone_number` must be provided. + pub lead: Option, +} + +impl RequestValue for CreateLeadRequest {} + + +/// Common data that is in each API request. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct RequestMetadata { + /// Locale to use for the current request. + pub locale: Option, + /// Google Partners session ID. + #[serde(rename="partnersSessionId")] + pub partners_session_id: Option, + /// Experiment IDs the current request belongs to. + #[serde(rename="experimentIds")] + pub experiment_ids: Option>, + /// Values to use instead of the user's respective defaults for the current request. These are only honored by whitelisted products. + #[serde(rename="userOverrides")] + pub user_overrides: Option, + /// Source of traffic for the current request. + #[serde(rename="trafficSource")] + pub traffic_source: Option, +} + +impl Part for RequestMetadata {} + + +/// Response message for ListUserStates. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where 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 states](struct.UserStateListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ListUserStatesResponse { + /// User's states. + #[serde(rename="userStates")] + pub user_states: Option>, + /// Current response metadata. + #[serde(rename="responseMetadata")] + pub response_metadata: Option, +} + +impl ResponseResult for ListUserStatesResponse {} + + +/// Common data that is in each API response. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ResponseMetadata { + /// Debug information about this request. + #[serde(rename="debugInfo")] + pub debug_info: Option, +} + +impl Part for ResponseMetadata {} + + +/// Key value data pair for 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 EventData { + /// Data values. + pub values: Option>, + /// Data type. + pub key: Option, +} + +impl Part for EventData {} + + +/// Basic information from a public 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 PublicProfile { + /// The URL of the public profile. + pub url: Option, + /// The URL to the main display image of the public profile. + #[serde(rename="displayImageUrl")] + pub display_image_url: Option, + /// The display name of the public profile. + #[serde(rename="displayName")] + pub display_name: Option, + /// The ID which can be used to retrieve more details about the public profile. + pub id: Option, +} + +impl Part for PublicProfile {} + + +/// An object representing a latitude/longitude pair. This is expressed as a pair of doubles representing degrees latitude and degrees longitude. Unless specified otherwise, this must conform to the WGS84 standard. Values must be within normalized ranges. Example of normalization code in Python: def NormalizeLongitude(longitude): """Wrapsdecimal degrees longitude to [-180.0, 180.0].""" q, r = divmod(longitude, 360.0) if r > 180.0 or (r == 180.0 and q <= -1.0): return r - 360.0 return r def NormalizeLatLng(latitude, longitude): """Wraps decimal degrees latitude and longitude to [-180.0, 180.0] and [-90.0, 90.0], respectively.""" r = latitude % 360.0 if r = 270.0: return r - 360, NormalizeLongitude(longitude) else: return 180 - r, NormalizeLongitude(longitude + 180.0) assert 180.0 == NormalizeLongitude(180.0) assert -180.0 == NormalizeLongitude(-180.0) assert -179.0 == NormalizeLongitude(181.0) assert (0.0, 0.0) == NormalizeLatLng(360.0, 0.0) assert (0.0, 0.0) == NormalizeLatLng(-360.0, 0.0) assert (85.0, 180.0) == NormalizeLatLng(95.0, 0.0) assert (-85.0, -170.0) == NormalizeLatLng(-95.0, 10.0) assert (90.0, 10.0) == NormalizeLatLng(90.0, 10.0) assert (-90.0, -10.0) == NormalizeLatLng(-90.0, -10.0) assert (0.0, -170.0) == NormalizeLatLng(-180.0, 10.0) assert (0.0, -170.0) == NormalizeLatLng(180.0, 10.0) assert (-90.0, 10.0) == NormalizeLatLng(270.0, 10.0) assert (90.0, 10.0) == NormalizeLatLng(-270.0, 10.0) +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct LatLng { + /// The latitude in degrees. It must be in the range [-90.0, +90.0]. + pub latitude: Option, + /// The longitude in degrees. It must be in the range [-180.0, +180.0]. + pub longitude: Option, +} + +impl Part for LatLng {} + + + +// ################### +// MethodBuilders ### +// ################# + +/// A builder providing access to all methods supported on *userEvent* resources. +/// It is not used directly, but through the `Partners` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate yup_oauth2 as oauth2; +/// extern crate google_partners2 as partners2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use partners2::Partners; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Partners::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `log(...)` +/// // to build up your call. +/// let rb = hub.user_events(); +/// # } +/// ``` +pub struct UserEventMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Partners, +} + +impl<'a, C, A> MethodsBuilder for UserEventMethods<'a, C, A> {} + +impl<'a, C, A> UserEventMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Logs a user event. + /// + /// # Arguments + /// + /// * `request` - No description provided. + pub fn log(&self, request: LogUserEventRequest) -> UserEventLogCall<'a, C, A> { + UserEventLogCall { + hub: self.hub, + _request: request, + _delegate: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *clientMessage* resources. +/// It is not used directly, but through the `Partners` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate yup_oauth2 as oauth2; +/// extern crate google_partners2 as partners2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use partners2::Partners; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Partners::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `log(...)` +/// // to build up your call. +/// let rb = hub.client_messages(); +/// # } +/// ``` +pub struct ClientMessageMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Partners, +} + +impl<'a, C, A> MethodsBuilder for ClientMessageMethods<'a, C, A> {} + +impl<'a, C, A> ClientMessageMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Logs a generic message from the client, such as `Failed to render component`, `Profile page is running slow`, `More than 500 users have accessed this result.`, etc. + /// + /// # Arguments + /// + /// * `request` - No description provided. + pub fn log(&self, request: LogMessageRequest) -> ClientMessageLogCall<'a, C, A> { + ClientMessageLogCall { + hub: self.hub, + _request: request, + _delegate: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *company* resources. +/// It is not used directly, but through the `Partners` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate yup_oauth2 as oauth2; +/// extern crate google_partners2 as partners2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use partners2::Partners; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Partners::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get(...)`, `leads_create(...)` and `list(...)` +/// // to build up your call. +/// let rb = hub.companies(); +/// # } +/// ``` +pub struct CompanyMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Partners, +} + +impl<'a, C, A> MethodsBuilder for CompanyMethods<'a, C, A> {} + +impl<'a, C, A> CompanyMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Gets a company. + /// + /// # Arguments + /// + /// * `companyId` - The ID of the company to retrieve. + pub fn get(&self, company_id: &str) -> CompanyGetCall<'a, C, A> { + CompanyGetCall { + hub: self.hub, + _company_id: company_id.to_string(), + _view: Default::default(), + _request_metadata_user_overrides_user_id: Default::default(), + _request_metadata_user_overrides_ip_address: Default::default(), + _request_metadata_traffic_source_traffic_sub_id: Default::default(), + _request_metadata_traffic_source_traffic_source_id: Default::default(), + _request_metadata_partners_session_id: Default::default(), + _request_metadata_locale: Default::default(), + _request_metadata_experiment_ids: Default::default(), + _order_by: Default::default(), + _currency_code: Default::default(), + _address: Default::default(), + _delegate: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Creates an advertiser lead for the given company ID. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `companyId` - The ID of the company to contact. + pub fn leads_create(&self, request: CreateLeadRequest, company_id: &str) -> CompanyLeadCreateCall<'a, C, A> { + CompanyLeadCreateCall { + hub: self.hub, + _request: request, + _company_id: company_id.to_string(), + _delegate: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Lists companies. + pub fn list(&self) -> CompanyListCall<'a, C, A> { + CompanyListCall { + hub: self.hub, + _website_url: Default::default(), + _view: Default::default(), + _services: Default::default(), + _request_metadata_user_overrides_user_id: Default::default(), + _request_metadata_user_overrides_ip_address: Default::default(), + _request_metadata_traffic_source_traffic_sub_id: Default::default(), + _request_metadata_traffic_source_traffic_source_id: Default::default(), + _request_metadata_partners_session_id: Default::default(), + _request_metadata_locale: Default::default(), + _request_metadata_experiment_ids: Default::default(), + _page_token: Default::default(), + _page_size: Default::default(), + _order_by: Default::default(), + _min_monthly_budget_units: Default::default(), + _min_monthly_budget_nanos: Default::default(), + _min_monthly_budget_currency_code: Default::default(), + _max_monthly_budget_units: Default::default(), + _max_monthly_budget_nanos: Default::default(), + _max_monthly_budget_currency_code: Default::default(), + _language_codes: Default::default(), + _industries: Default::default(), + _gps_motivations: Default::default(), + _company_name: Default::default(), + _address: Default::default(), + _delegate: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *userState* resources. +/// It is not used directly, but through the `Partners` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate yup_oauth2 as oauth2; +/// extern crate google_partners2 as partners2; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use partners2::Partners; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Partners::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.user_states(); +/// # } +/// ``` +pub struct UserStateMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Partners, +} + +impl<'a, C, A> MethodsBuilder for UserStateMethods<'a, C, A> {} + +impl<'a, C, A> UserStateMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Lists states for current user. + pub fn list(&self) -> UserStateListCall<'a, C, A> { + UserStateListCall { + hub: self.hub, + _request_metadata_user_overrides_user_id: Default::default(), + _request_metadata_user_overrides_ip_address: Default::default(), + _request_metadata_traffic_source_traffic_sub_id: Default::default(), + _request_metadata_traffic_source_traffic_source_id: Default::default(), + _request_metadata_partners_session_id: Default::default(), + _request_metadata_locale: Default::default(), + _request_metadata_experiment_ids: Default::default(), + _delegate: Default::default(), + _additional_params: Default::default(), + } + } +} + + + + + +// ################### +// CallBuilders ### +// ################# + +/// Logs a user event. +/// +/// A builder for the *log* method supported by a *userEvent* resource. +/// It is not used directly, but through a `UserEventMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_partners2 as partners2; +/// use partners2::LogUserEventRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use partners2::Partners; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Partners::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req = LogUserEventRequest::default(); +/// +/// // You can configure optional parameters by calling 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_events().log(req) +/// .doit(); +/// # } +/// ``` +pub struct UserEventLogCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Partners, + _request: LogUserEventRequest, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, +} + +impl<'a, C, A> CallBuilder for UserEventLogCall<'a, C, A> {} + +impl<'a, C, A> UserEventLogCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, LogUserEventResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "partners.userEvents.log", + 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 Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://partners.googleapis.com/v2/userEvents:log".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 Err(Error::MissingAPIKey) + } + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + 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) + .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_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: LogUserEventRequest) -> UserEventLogCall<'a, C, A> { + self._request = new_value; + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserEventLogCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> UserEventLogCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + +} + + +/// Logs a generic message from the client, such as `Failed to render component`, `Profile page is running slow`, `More than 500 users have accessed this result.`, etc. +/// +/// A builder for the *log* method supported by a *clientMessage* resource. +/// It is not used directly, but through a `ClientMessageMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_partners2 as partners2; +/// use partners2::LogMessageRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use partners2::Partners; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Partners::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req = LogMessageRequest::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.client_messages().log(req) +/// .doit(); +/// # } +/// ``` +pub struct ClientMessageLogCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Partners, + _request: LogMessageRequest, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, +} + +impl<'a, C, A> CallBuilder for ClientMessageLogCall<'a, C, A> {} + +impl<'a, C, A> ClientMessageLogCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, LogMessageResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "partners.clientMessages.log", + 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 Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://partners.googleapis.com/v2/clientMessages:log".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 Err(Error::MissingAPIKey) + } + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + 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) + .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_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: LogMessageRequest) -> ClientMessageLogCall<'a, C, A> { + self._request = new_value; + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ClientMessageLogCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> ClientMessageLogCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + +} + + +/// Gets a company. +/// +/// A builder for the *get* method supported by a *company* resource. +/// It is not used directly, but through a `CompanyMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_partners2 as partners2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use partners2::Partners; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Partners::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.companies().get("companyId") +/// .view("sit") +/// .request_metadata_user_overrides_user_id("Stet") +/// .request_metadata_user_overrides_ip_address("sed") +/// .request_metadata_traffic_source_traffic_sub_id("et") +/// .request_metadata_traffic_source_traffic_source_id("dolores") +/// .request_metadata_partners_session_id("kasd") +/// .request_metadata_locale("accusam") +/// .add_request_metadata_experiment_ids("takimata") +/// .order_by("justo") +/// .currency_code("amet.") +/// .address("erat") +/// .doit(); +/// # } +/// ``` +pub struct CompanyGetCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Partners, + _company_id: String, + _view: Option, + _request_metadata_user_overrides_user_id: Option, + _request_metadata_user_overrides_ip_address: Option, + _request_metadata_traffic_source_traffic_sub_id: Option, + _request_metadata_traffic_source_traffic_source_id: Option, + _request_metadata_partners_session_id: Option, + _request_metadata_locale: Option, + _request_metadata_experiment_ids: Vec, + _order_by: Option, + _currency_code: Option, + _address: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, +} + +impl<'a, C, A> CallBuilder for CompanyGetCall<'a, C, A> {} + +impl<'a, C, A> CompanyGetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, GetCompanyResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "partners.companies.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((14 + self._additional_params.len())); + params.push(("companyId", self._company_id.to_string())); + if let Some(value) = self._view { + params.push(("view", value.to_string())); + } + if let Some(value) = self._request_metadata_user_overrides_user_id { + params.push(("requestMetadata.userOverrides.userId", value.to_string())); + } + if let Some(value) = self._request_metadata_user_overrides_ip_address { + params.push(("requestMetadata.userOverrides.ipAddress", value.to_string())); + } + if let Some(value) = self._request_metadata_traffic_source_traffic_sub_id { + params.push(("requestMetadata.trafficSource.trafficSubId", value.to_string())); + } + if let Some(value) = self._request_metadata_traffic_source_traffic_source_id { + params.push(("requestMetadata.trafficSource.trafficSourceId", value.to_string())); + } + if let Some(value) = self._request_metadata_partners_session_id { + params.push(("requestMetadata.partnersSessionId", value.to_string())); + } + if let Some(value) = self._request_metadata_locale { + params.push(("requestMetadata.locale", value.to_string())); + } + if self._request_metadata_experiment_ids.len() > 0 { + let mut s = String::new(); + for f in self._request_metadata_experiment_ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("requestMetadata.experimentIds", s)); + } + if let Some(value) = self._order_by { + params.push(("orderBy", value.to_string())); + } + if let Some(value) = self._currency_code { + params.push(("currencyCode", value.to_string())); + } + if let Some(value) = self._address { + params.push(("address", value.to_string())); + } + for &field in ["alt", "companyId", "view", "requestMetadata.userOverrides.userId", "requestMetadata.userOverrides.ipAddress", "requestMetadata.trafficSource.trafficSubId", "requestMetadata.trafficSource.trafficSourceId", "requestMetadata.partnersSessionId", "requestMetadata.locale", "requestMetadata.experimentIds", "orderBy", "currencyCode", "address"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://partners.googleapis.com/v2/companies/{companyId}".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 Err(Error::MissingAPIKey) + } + } + + for &(find_this, param_name) in [("{companyId}", "companyId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["companyId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + 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) + .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_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The ID of the company to retrieve. + /// + /// Sets the *company id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn company_id(mut self, new_value: &str) -> CompanyGetCall<'a, C, A> { + self._company_id = new_value.to_string(); + self + } + /// The view of `Company` resource to be returned. This must not be `COMPANY_VIEW_UNSPECIFIED`. + /// + /// Sets the *view* query property to the given value. + pub fn view(mut self, new_value: &str) -> CompanyGetCall<'a, C, A> { + self._view = Some(new_value.to_string()); + self + } + /// Logged-in user ID to impersonate instead of the user's ID. + /// + /// Sets the *request metadata.user overrides.user id* query property to the given value. + pub fn request_metadata_user_overrides_user_id(mut self, new_value: &str) -> CompanyGetCall<'a, C, A> { + self._request_metadata_user_overrides_user_id = Some(new_value.to_string()); + self + } + /// IP address to use instead of the user's geo-located IP address. + /// + /// Sets the *request metadata.user overrides.ip address* query property to the given value. + pub fn request_metadata_user_overrides_ip_address(mut self, new_value: &str) -> CompanyGetCall<'a, C, A> { + self._request_metadata_user_overrides_ip_address = Some(new_value.to_string()); + self + } + /// Second level identifier to indicate where the traffic comes from. An identifier has multiple letters created by a team which redirected the traffic to us. + /// + /// Sets the *request metadata.traffic source.traffic sub id* query property to the given value. + pub fn request_metadata_traffic_source_traffic_sub_id(mut self, new_value: &str) -> CompanyGetCall<'a, C, A> { + self._request_metadata_traffic_source_traffic_sub_id = Some(new_value.to_string()); + self + } + /// Identifier to indicate where the traffic comes from. An identifier has multiple letters created by a team which redirected the traffic to us. + /// + /// Sets the *request metadata.traffic source.traffic source id* query property to the given value. + pub fn request_metadata_traffic_source_traffic_source_id(mut self, new_value: &str) -> CompanyGetCall<'a, C, A> { + self._request_metadata_traffic_source_traffic_source_id = Some(new_value.to_string()); + self + } + /// Google Partners session ID. + /// + /// Sets the *request metadata.partners session id* query property to the given value. + pub fn request_metadata_partners_session_id(mut self, new_value: &str) -> CompanyGetCall<'a, C, A> { + self._request_metadata_partners_session_id = Some(new_value.to_string()); + self + } + /// Locale to use for the current request. + /// + /// Sets the *request metadata.locale* query property to the given value. + pub fn request_metadata_locale(mut self, new_value: &str) -> CompanyGetCall<'a, C, A> { + self._request_metadata_locale = Some(new_value.to_string()); + self + } + /// Experiment IDs the current request belongs to. + /// + /// Append the given value to the *request metadata.experiment ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + pub fn add_request_metadata_experiment_ids(mut self, new_value: &str) -> CompanyGetCall<'a, C, A> { + self._request_metadata_experiment_ids.push(new_value.to_string()); + self + } + /// How to order addresses within the returned company. Currently, only `address` and `address desc` is supported which will sorted by closest to farthest in distance from given address and farthest to closest distance from given address respectively. + /// + /// Sets the *order by* query property to the given value. + pub fn order_by(mut self, new_value: &str) -> CompanyGetCall<'a, C, A> { + self._order_by = Some(new_value.to_string()); + self + } + /// If the company's budget is in a different currency code than this one, then the converted budget is converted to this currency code. + /// + /// Sets the *currency code* query property to the given value. + pub fn currency_code(mut self, new_value: &str) -> CompanyGetCall<'a, C, A> { + self._currency_code = Some(new_value.to_string()); + self + } + /// The address to use for sorting the company's addresses by proximity. If not given, the geo-located address of the request is used. Used when order_by is set. + /// + /// Sets the *address* query property to the given value. + pub fn address(mut self, new_value: &str) -> CompanyGetCall<'a, C, A> { + self._address = Some(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CompanyGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> CompanyGetCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + +} + + +/// Creates an advertiser lead for the given company ID. +/// +/// A builder for the *leads.create* method supported by a *company* resource. +/// It is not used directly, but through a `CompanyMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_partners2 as partners2; +/// use partners2::CreateLeadRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use partners2::Partners; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Partners::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req = CreateLeadRequest::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.companies().leads_create(req, "companyId") +/// .doit(); +/// # } +/// ``` +pub struct CompanyLeadCreateCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Partners, + _request: CreateLeadRequest, + _company_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, +} + +impl<'a, C, A> CallBuilder for CompanyLeadCreateCall<'a, C, A> {} + +impl<'a, C, A> CompanyLeadCreateCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, CreateLeadResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "partners.companies.leads.create", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("companyId", self._company_id.to_string())); + for &field in ["alt", "companyId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://partners.googleapis.com/v2/companies/{companyId}/leads".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 Err(Error::MissingAPIKey) + } + } + + for &(find_this, param_name) in [("{companyId}", "companyId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["companyId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + 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) + .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_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: CreateLeadRequest) -> CompanyLeadCreateCall<'a, C, A> { + self._request = new_value; + self + } + /// The ID of the company to contact. + /// + /// Sets the *company id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn company_id(mut self, new_value: &str) -> CompanyLeadCreateCall<'a, C, A> { + self._company_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CompanyLeadCreateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> CompanyLeadCreateCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + +} + + +/// Lists companies. +/// +/// A builder for the *list* method supported by a *company* resource. +/// It is not used directly, but through a `CompanyMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_partners2 as partners2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use partners2::Partners; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Partners::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.companies().list() +/// .website_url("sea") +/// .view("nonumy") +/// .add_services("dolores") +/// .request_metadata_user_overrides_user_id("gubergren") +/// .request_metadata_user_overrides_ip_address("sadipscing") +/// .request_metadata_traffic_source_traffic_sub_id("aliquyam") +/// .request_metadata_traffic_source_traffic_source_id("ea") +/// .request_metadata_partners_session_id("no") +/// .request_metadata_locale("justo") +/// .add_request_metadata_experiment_ids("justo") +/// .page_token("et") +/// .page_size(-17) +/// .order_by("diam") +/// .min_monthly_budget_units("ipsum") +/// .min_monthly_budget_nanos(-5) +/// .min_monthly_budget_currency_code("et") +/// .max_monthly_budget_units("duo") +/// .max_monthly_budget_nanos(-32) +/// .max_monthly_budget_currency_code("sea") +/// .add_language_codes("Lorem") +/// .add_industries("eos") +/// .add_gps_motivations("erat") +/// .company_name("sadipscing") +/// .address("dolor") +/// .doit(); +/// # } +/// ``` +pub struct CompanyListCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Partners, + _website_url: Option, + _view: Option, + _services: Vec, + _request_metadata_user_overrides_user_id: Option, + _request_metadata_user_overrides_ip_address: Option, + _request_metadata_traffic_source_traffic_sub_id: Option, + _request_metadata_traffic_source_traffic_source_id: Option, + _request_metadata_partners_session_id: Option, + _request_metadata_locale: Option, + _request_metadata_experiment_ids: Vec, + _page_token: Option, + _page_size: Option, + _order_by: Option, + _min_monthly_budget_units: Option, + _min_monthly_budget_nanos: Option, + _min_monthly_budget_currency_code: Option, + _max_monthly_budget_units: Option, + _max_monthly_budget_nanos: Option, + _max_monthly_budget_currency_code: Option, + _language_codes: Vec, + _industries: Vec, + _gps_motivations: Vec, + _company_name: Option, + _address: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, +} + +impl<'a, C, A> CallBuilder for CompanyListCall<'a, C, A> {} + +impl<'a, C, A> CompanyListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ListCompaniesResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "partners.companies.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((26 + self._additional_params.len())); + if let Some(value) = self._website_url { + params.push(("websiteUrl", value.to_string())); + } + if let Some(value) = self._view { + params.push(("view", value.to_string())); + } + if self._services.len() > 0 { + let mut s = String::new(); + for f in self._services.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("services", s)); + } + if let Some(value) = self._request_metadata_user_overrides_user_id { + params.push(("requestMetadata.userOverrides.userId", value.to_string())); + } + if let Some(value) = self._request_metadata_user_overrides_ip_address { + params.push(("requestMetadata.userOverrides.ipAddress", value.to_string())); + } + if let Some(value) = self._request_metadata_traffic_source_traffic_sub_id { + params.push(("requestMetadata.trafficSource.trafficSubId", value.to_string())); + } + if let Some(value) = self._request_metadata_traffic_source_traffic_source_id { + params.push(("requestMetadata.trafficSource.trafficSourceId", value.to_string())); + } + if let Some(value) = self._request_metadata_partners_session_id { + params.push(("requestMetadata.partnersSessionId", value.to_string())); + } + if let Some(value) = self._request_metadata_locale { + params.push(("requestMetadata.locale", value.to_string())); + } + if self._request_metadata_experiment_ids.len() > 0 { + let mut s = String::new(); + for f in self._request_metadata_experiment_ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("requestMetadata.experimentIds", s)); + } + 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._order_by { + params.push(("orderBy", value.to_string())); + } + if let Some(value) = self._min_monthly_budget_units { + params.push(("minMonthlyBudget.units", value.to_string())); + } + if let Some(value) = self._min_monthly_budget_nanos { + params.push(("minMonthlyBudget.nanos", value.to_string())); + } + if let Some(value) = self._min_monthly_budget_currency_code { + params.push(("minMonthlyBudget.currencyCode", value.to_string())); + } + if let Some(value) = self._max_monthly_budget_units { + params.push(("maxMonthlyBudget.units", value.to_string())); + } + if let Some(value) = self._max_monthly_budget_nanos { + params.push(("maxMonthlyBudget.nanos", value.to_string())); + } + if let Some(value) = self._max_monthly_budget_currency_code { + params.push(("maxMonthlyBudget.currencyCode", value.to_string())); + } + if self._language_codes.len() > 0 { + let mut s = String::new(); + for f in self._language_codes.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("languageCodes", s)); + } + if self._industries.len() > 0 { + let mut s = String::new(); + for f in self._industries.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("industries", s)); + } + if self._gps_motivations.len() > 0 { + let mut s = String::new(); + for f in self._gps_motivations.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("gpsMotivations", s)); + } + if let Some(value) = self._company_name { + params.push(("companyName", value.to_string())); + } + if let Some(value) = self._address { + params.push(("address", value.to_string())); + } + for &field in ["alt", "websiteUrl", "view", "services", "requestMetadata.userOverrides.userId", "requestMetadata.userOverrides.ipAddress", "requestMetadata.trafficSource.trafficSubId", "requestMetadata.trafficSource.trafficSourceId", "requestMetadata.partnersSessionId", "requestMetadata.locale", "requestMetadata.experimentIds", "pageToken", "pageSize", "orderBy", "minMonthlyBudget.units", "minMonthlyBudget.nanos", "minMonthlyBudget.currencyCode", "maxMonthlyBudget.units", "maxMonthlyBudget.nanos", "maxMonthlyBudget.currencyCode", "languageCodes", "industries", "gpsMotivations", "companyName", "address"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://partners.googleapis.com/v2/companies".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 Err(Error::MissingAPIKey) + } + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + 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) + .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_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Website URL that will help to find a better matched company. . + /// + /// Sets the *website url* query property to the given value. + pub fn website_url(mut self, new_value: &str) -> CompanyListCall<'a, C, A> { + self._website_url = Some(new_value.to_string()); + self + } + /// The view of the `Company` resource to be returned. This must not be `COMPANY_VIEW_UNSPECIFIED`. + /// + /// Sets the *view* query property to the given value. + pub fn view(mut self, new_value: &str) -> CompanyListCall<'a, C, A> { + self._view = Some(new_value.to_string()); + self + } + /// List of services the company can help with. + /// + /// Append the given value to the *services* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + pub fn add_services(mut self, new_value: &str) -> CompanyListCall<'a, C, A> { + self._services.push(new_value.to_string()); + self + } + /// Logged-in user ID to impersonate instead of the user's ID. + /// + /// Sets the *request metadata.user overrides.user id* query property to the given value. + pub fn request_metadata_user_overrides_user_id(mut self, new_value: &str) -> CompanyListCall<'a, C, A> { + self._request_metadata_user_overrides_user_id = Some(new_value.to_string()); + self + } + /// IP address to use instead of the user's geo-located IP address. + /// + /// Sets the *request metadata.user overrides.ip address* query property to the given value. + pub fn request_metadata_user_overrides_ip_address(mut self, new_value: &str) -> CompanyListCall<'a, C, A> { + self._request_metadata_user_overrides_ip_address = Some(new_value.to_string()); + self + } + /// Second level identifier to indicate where the traffic comes from. An identifier has multiple letters created by a team which redirected the traffic to us. + /// + /// Sets the *request metadata.traffic source.traffic sub id* query property to the given value. + pub fn request_metadata_traffic_source_traffic_sub_id(mut self, new_value: &str) -> CompanyListCall<'a, C, A> { + self._request_metadata_traffic_source_traffic_sub_id = Some(new_value.to_string()); + self + } + /// Identifier to indicate where the traffic comes from. An identifier has multiple letters created by a team which redirected the traffic to us. + /// + /// Sets the *request metadata.traffic source.traffic source id* query property to the given value. + pub fn request_metadata_traffic_source_traffic_source_id(mut self, new_value: &str) -> CompanyListCall<'a, C, A> { + self._request_metadata_traffic_source_traffic_source_id = Some(new_value.to_string()); + self + } + /// Google Partners session ID. + /// + /// Sets the *request metadata.partners session id* query property to the given value. + pub fn request_metadata_partners_session_id(mut self, new_value: &str) -> CompanyListCall<'a, C, A> { + self._request_metadata_partners_session_id = Some(new_value.to_string()); + self + } + /// Locale to use for the current request. + /// + /// Sets the *request metadata.locale* query property to the given value. + pub fn request_metadata_locale(mut self, new_value: &str) -> CompanyListCall<'a, C, A> { + self._request_metadata_locale = Some(new_value.to_string()); + self + } + /// Experiment IDs the current request belongs to. + /// + /// Append the given value to the *request metadata.experiment ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + pub fn add_request_metadata_experiment_ids(mut self, new_value: &str) -> CompanyListCall<'a, C, A> { + self._request_metadata_experiment_ids.push(new_value.to_string()); + self + } + /// A token identifying a page of results that the server returns. Typically, this is the value of `ListCompaniesResponse.next_page_token` returned from the previous call to ListCompanies. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> CompanyListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Requested page size. Server may return fewer companies than requested. If unspecified, server picks an appropriate default. + /// + /// Sets the *page size* query property to the given value. + pub fn page_size(mut self, new_value: i32) -> CompanyListCall<'a, C, A> { + self._page_size = Some(new_value); + self + } + /// How to order addresses within the returned companies. Currently, only `address` and `address desc` is supported which will sorted by closest to farthest in distance from given address and farthest to closest distance from given address respectively. + /// + /// Sets the *order by* query property to the given value. + pub fn order_by(mut self, new_value: &str) -> CompanyListCall<'a, C, A> { + self._order_by = Some(new_value.to_string()); + self + } + /// The whole units of the amount. For example if `currencyCode` is `"USD"`, then 1 unit is one US dollar. + /// + /// Sets the *min monthly budget.units* query property to the given value. + pub fn min_monthly_budget_units(mut self, new_value: &str) -> CompanyListCall<'a, C, A> { + self._min_monthly_budget_units = Some(new_value.to_string()); + self + } + /// Number of nano (10^-9) units of the amount. The value must be between -999,999,999 and +999,999,999 inclusive. If `units` is positive, `nanos` must be positive or zero. If `units` is zero, `nanos` can be positive, zero, or negative. If `units` is negative, `nanos` must be negative or zero. For example $-1.75 is represented as `units`=-1 and `nanos`=-750,000,000. + /// + /// Sets the *min monthly budget.nanos* query property to the given value. + pub fn min_monthly_budget_nanos(mut self, new_value: i32) -> CompanyListCall<'a, C, A> { + self._min_monthly_budget_nanos = Some(new_value); + self + } + /// The 3-letter currency code defined in ISO 4217. + /// + /// Sets the *min monthly budget.currency code* query property to the given value. + pub fn min_monthly_budget_currency_code(mut self, new_value: &str) -> CompanyListCall<'a, C, A> { + self._min_monthly_budget_currency_code = Some(new_value.to_string()); + self + } + /// The whole units of the amount. For example if `currencyCode` is `"USD"`, then 1 unit is one US dollar. + /// + /// Sets the *max monthly budget.units* query property to the given value. + pub fn max_monthly_budget_units(mut self, new_value: &str) -> CompanyListCall<'a, C, A> { + self._max_monthly_budget_units = Some(new_value.to_string()); + self + } + /// Number of nano (10^-9) units of the amount. The value must be between -999,999,999 and +999,999,999 inclusive. If `units` is positive, `nanos` must be positive or zero. If `units` is zero, `nanos` can be positive, zero, or negative. If `units` is negative, `nanos` must be negative or zero. For example $-1.75 is represented as `units`=-1 and `nanos`=-750,000,000. + /// + /// Sets the *max monthly budget.nanos* query property to the given value. + pub fn max_monthly_budget_nanos(mut self, new_value: i32) -> CompanyListCall<'a, C, A> { + self._max_monthly_budget_nanos = Some(new_value); + self + } + /// The 3-letter currency code defined in ISO 4217. + /// + /// Sets the *max monthly budget.currency code* query property to the given value. + pub fn max_monthly_budget_currency_code(mut self, new_value: &str) -> CompanyListCall<'a, C, A> { + self._max_monthly_budget_currency_code = Some(new_value.to_string()); + self + } + /// List of language codes that company can support. Only primary language subtags are accepted as defined by BCP 47 (IETF BCP 47, "Tags for Identifying Languages"). + /// + /// Append the given value to the *language codes* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + pub fn add_language_codes(mut self, new_value: &str) -> CompanyListCall<'a, C, A> { + self._language_codes.push(new_value.to_string()); + self + } + /// List of industries the company can help with. + /// + /// Append the given value to the *industries* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + pub fn add_industries(mut self, new_value: &str) -> CompanyListCall<'a, C, A> { + self._industries.push(new_value.to_string()); + self + } + /// List of reasons for using Google Partner Search to get companies. + /// + /// Append the given value to the *gps motivations* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + pub fn add_gps_motivations(mut self, new_value: &str) -> CompanyListCall<'a, C, A> { + self._gps_motivations.push(new_value.to_string()); + self + } + /// Company name to search for. + /// + /// Sets the *company name* query property to the given value. + pub fn company_name(mut self, new_value: &str) -> CompanyListCall<'a, C, A> { + self._company_name = Some(new_value.to_string()); + self + } + /// The address to use when searching for companies. If not given, the geo-located address of the request is used. + /// + /// Sets the *address* query property to the given value. + pub fn address(mut self, new_value: &str) -> CompanyListCall<'a, C, A> { + self._address = Some(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> CompanyListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> CompanyListCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + +} + + +/// Lists states for current user. +/// +/// A builder for the *list* method supported by a *userState* resource. +/// It is not used directly, but through a `UserStateMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_partners2 as partners2; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use partners2::Partners; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Partners::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling 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_states().list() +/// .request_metadata_user_overrides_user_id("eirmod") +/// .request_metadata_user_overrides_ip_address("elitr") +/// .request_metadata_traffic_source_traffic_sub_id("amet") +/// .request_metadata_traffic_source_traffic_source_id("no") +/// .request_metadata_partners_session_id("labore") +/// .request_metadata_locale("eirmod") +/// .add_request_metadata_experiment_ids("dolore") +/// .doit(); +/// # } +/// ``` +pub struct UserStateListCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Partners, + _request_metadata_user_overrides_user_id: Option, + _request_metadata_user_overrides_ip_address: Option, + _request_metadata_traffic_source_traffic_sub_id: Option, + _request_metadata_traffic_source_traffic_source_id: Option, + _request_metadata_partners_session_id: Option, + _request_metadata_locale: Option, + _request_metadata_experiment_ids: Vec, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, +} + +impl<'a, C, A> CallBuilder for UserStateListCall<'a, C, A> {} + +impl<'a, C, A> UserStateListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ListUserStatesResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "partners.userStates.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._request_metadata_user_overrides_user_id { + params.push(("requestMetadata.userOverrides.userId", value.to_string())); + } + if let Some(value) = self._request_metadata_user_overrides_ip_address { + params.push(("requestMetadata.userOverrides.ipAddress", value.to_string())); + } + if let Some(value) = self._request_metadata_traffic_source_traffic_sub_id { + params.push(("requestMetadata.trafficSource.trafficSubId", value.to_string())); + } + if let Some(value) = self._request_metadata_traffic_source_traffic_source_id { + params.push(("requestMetadata.trafficSource.trafficSourceId", value.to_string())); + } + if let Some(value) = self._request_metadata_partners_session_id { + params.push(("requestMetadata.partnersSessionId", value.to_string())); + } + if let Some(value) = self._request_metadata_locale { + params.push(("requestMetadata.locale", value.to_string())); + } + if self._request_metadata_experiment_ids.len() > 0 { + let mut s = String::new(); + for f in self._request_metadata_experiment_ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("requestMetadata.experimentIds", s)); + } + for &field in ["alt", "requestMetadata.userOverrides.userId", "requestMetadata.userOverrides.ipAddress", "requestMetadata.trafficSource.trafficSubId", "requestMetadata.trafficSource.trafficSourceId", "requestMetadata.partnersSessionId", "requestMetadata.locale", "requestMetadata.experimentIds"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://partners.googleapis.com/v2/userStates".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 Err(Error::MissingAPIKey) + } + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + 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) + .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_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Logged-in user ID to impersonate instead of the user's ID. + /// + /// Sets the *request metadata.user overrides.user id* query property to the given value. + pub fn request_metadata_user_overrides_user_id(mut self, new_value: &str) -> UserStateListCall<'a, C, A> { + self._request_metadata_user_overrides_user_id = Some(new_value.to_string()); + self + } + /// IP address to use instead of the user's geo-located IP address. + /// + /// Sets the *request metadata.user overrides.ip address* query property to the given value. + pub fn request_metadata_user_overrides_ip_address(mut self, new_value: &str) -> UserStateListCall<'a, C, A> { + self._request_metadata_user_overrides_ip_address = Some(new_value.to_string()); + self + } + /// Second level identifier to indicate where the traffic comes from. An identifier has multiple letters created by a team which redirected the traffic to us. + /// + /// Sets the *request metadata.traffic source.traffic sub id* query property to the given value. + pub fn request_metadata_traffic_source_traffic_sub_id(mut self, new_value: &str) -> UserStateListCall<'a, C, A> { + self._request_metadata_traffic_source_traffic_sub_id = Some(new_value.to_string()); + self + } + /// Identifier to indicate where the traffic comes from. An identifier has multiple letters created by a team which redirected the traffic to us. + /// + /// Sets the *request metadata.traffic source.traffic source id* query property to the given value. + pub fn request_metadata_traffic_source_traffic_source_id(mut self, new_value: &str) -> UserStateListCall<'a, C, A> { + self._request_metadata_traffic_source_traffic_source_id = Some(new_value.to_string()); + self + } + /// Google Partners session ID. + /// + /// Sets the *request metadata.partners session id* query property to the given value. + pub fn request_metadata_partners_session_id(mut self, new_value: &str) -> UserStateListCall<'a, C, A> { + self._request_metadata_partners_session_id = Some(new_value.to_string()); + self + } + /// Locale to use for the current request. + /// + /// Sets the *request metadata.locale* query property to the given value. + pub fn request_metadata_locale(mut self, new_value: &str) -> UserStateListCall<'a, C, A> { + self._request_metadata_locale = Some(new_value.to_string()); + self + } + /// Experiment IDs the current request belongs to. + /// + /// Append the given value to the *request metadata.experiment ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + pub fn add_request_metadata_experiment_ids(mut self, new_value: &str) -> UserStateListCall<'a, C, A> { + self._request_metadata_experiment_ids.push(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserStateListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> UserStateListCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + +} + + diff --git a/gen/playmoviespartner1-cli/Cargo.toml b/gen/playmoviespartner1-cli/Cargo.toml new file mode 100644 index 0000000000..a1038a2352 --- /dev/null +++ b/gen/playmoviespartner1-cli/Cargo.toml @@ -0,0 +1,35 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-playmoviespartner1-cli" +version = "0.3.2+20150812" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with playmoviespartner (protocol v1)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/playmoviespartner1-cli" +homepage = "https://developers.google.com/playmoviespartner/" +documentation = "http://byron.github.io/google-apis-rs/google_playmoviespartner1_cli" +license = "MIT" +keywords = ["playmoviespartner", "google", "cli"] + +[[bin]] +name = "playmoviespartner1" + +[dependencies] +hyper = ">= 0.6.8" +mime = "0.1.0" +serde = ">= 0.6.0" +serde_json = ">= 0.6.0" +yup-oauth2 = "*" +strsim = "*" +yup-hyper-mock = ">=1.0.0" +clap = ">= 1.0.3" + +[build-dependencies] +syntex = { version = "*" } +serde_codegen = { version = "*" } + + +[dependencies.google-playmoviespartner1] +path = "../playmoviespartner1" diff --git a/gen/playmoviespartner1-cli/LICENSE.md b/gen/playmoviespartner1-cli/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/playmoviespartner1-cli/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/playmoviespartner1-cli/README.md b/gen/playmoviespartner1-cli/README.md new file mode 100644 index 0000000000..da438fb982 --- /dev/null +++ b/gen/playmoviespartner1-cli/README.md @@ -0,0 +1,119 @@ + +The `playmoviespartner1` command-line interface *(CLI)* allows to use most features of the *Google playmoviespartner* service from the comfort of your terminal. + +By default all output is printed to standard out, but flags can be set to direct it into a file independent of your shell's +capabilities. Errors will be printed to standard error, and cause the program's exit code to be non-zero. + +If data-structures are requested, these will be returned as pretty-printed JSON, to be useful as input to other tools. + +Everything else about the *playmoviespartner* API can be found at the +[official documentation site](https://developers.google.com/playmoviespartner/). + +# Downloads + +You can download the pre-compiled 64bit binaries for the following platforms: + +* ![icon](http://megaicons.net/static/img/icons_sizes/6/140/16/ubuntu-icon.png) [ubuntu](http://dl.byronimo.de/google.rs/cli/0.3.2/ubuntu/playmoviespartner1.tar.gz) +* ![icon](http://hydra-media.cursecdn.com/wow.gamepedia.com/a/a2/Apple-icon-16x16.png?version=25ddd67ac3dd3b634478e3978b76cb74) [osx](http://dl.byronimo.de/google.rs/cli/0.3.2/osx/playmoviespartner1.tar.gz) + +Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/playmoviespartner1-cli). + +# Usage + +This documentation was generated from the *playmoviespartner* API at revision *20150812*. The CLI is at version *0.3.2*. + +```bash +playmoviespartner1 [options] + accounts + avails-list [-p ]... [-o ] + experience-locales-get [-p ]... [-o ] + experience-locales-list [-p ]... [-o ] + orders-get [-p ]... [-o ] + orders-list [-p ]... [-o ] + store-infos-country-get [-p ]... [-o ] + store-infos-list [-p ]... [-o ] + playmoviespartner1 --help + +Configuration: + [--scope ]... + Specify the authentication a method should be executed in. Each scope + requires the user to grant this application permission to use it. + If unset, it defaults to the shortest scope url for a particular method. + --config-dir + A directory into which we will store our persistent data. Defaults to + a user-writable directory that we will create during the first invocation. + [default: ~/.google-service-cli] + --debug + Output all server communication to standard error. `tx` and `rx` are placed + into the same stream. + --debug-auth + Output all communication related to authentication to standard error. `tx` + and `rx` are placed into the same stream. + +``` + +# Configuration + +The program will store all persistent data in the `~/.google-service-cli` directory in *JSON* files prefixed with `playmoviespartner1-`. You can change the directory used to store configuration with the `--config-dir` flag on a per-invocation basis. + +More information about the various kinds of persistent data are given in the following paragraphs. + +# Authentication + +Most APIs require a user to authenticate any request. If this is the case, the [scope][scopes] determines the +set of permissions granted. The granularity of these is usually no more than *read-only* or *full-access*. + +If not set, the system will automatically select the smallest feasible scope, e.g. when invoking a +method that is read-only, it will ask only for a read-only scope. +You may use the `--scope` flag to specify a scope directly. +All applicable scopes are documented in the respective method's CLI documentation. + +The first time a scope is used, the user is asked for permission. Follow the instructions given +by the CLI to grant permissions, or to decline. + +If a scope was authenticated by the user, the respective information will be stored as *JSON* in the configuration +directory, e.g. `~/.google-service-cli/playmoviespartner1-token-.json`. No manual management of these tokens +is necessary. + +To revoke granted authentication, please refer to the [official documentation][revoke-access]. + +# Application Secrets + +In order to allow any application to use Google services, it will need to be registered using the +[Google Developer Console][google-dev-console]. APIs the application may use are then enabled for it +one by one. Most APIs can be used for free and have a daily quota. + +To allow more comfortable usage of the CLI without forcing anyone to register an own application, the CLI +comes with a default application secret that is configured accordingly. This also means that heavy usage +all around the world may deplete the daily quota. + +You can workaround this limitation by putting your own secrets file at this location: +`~/.google-service-cli/playmoviespartner1-secret.json`, assuming that the required *playmoviespartner* API +was enabled for it. Such a secret file can be downloaded in the *Google Developer Console* at +*APIs & auth -> Credentials -> Download JSON* and used as is. + +Learn more about how to setup Google projects and enable APIs using the [official documentation][google-project-new]. + + +# Debugging + +Even though the CLI does its best to provide usable error messages, sometimes it might be desirable to know +what exactly led to a particular issue. This is done by allowing all client-server communication to be +output to standard error *as-is*. + +The `--debug` flag will print all client-server communication to standard error, whereas the `--debug-auth` flag +will cause all communication related to authentication to standard error. +If the `--debug` flag is set, error-results will be debug-printed, possibly yielding more information about the +issue at hand. + +You may consider redirecting standard error into a file for ease of use, e.g. `playmoviespartner1 --debug [options] 2>debug.txt`. + + +[scopes]: https://developers.google.com/+/api/oauth#scopes +[revoke-access]: http://webapps.stackexchange.com/a/30849 +[google-dev-console]: https://console.developers.google.com/ +[google-project-new]: https://developers.google.com/console/help/new/ \ No newline at end of file diff --git a/gen/playmoviespartner1-cli/mkdocs.yml b/gen/playmoviespartner1-cli/mkdocs.yml new file mode 100644 index 0000000000..7cfb5d6562 --- /dev/null +++ b/gen/playmoviespartner1-cli/mkdocs.yml @@ -0,0 +1,23 @@ +site_name: playmoviespartner v0.3.2+20150812 +site_url: http://byron.github.io/google-apis-rs/google-playmoviespartner1-cli +site_description: Write integrating applications with bcore + +repo_url: https://github.com/Byron/google-apis-rs/tree/master/gen/playmoviespartner1-cli + +docs_dir: docs +site_dir: build_html + +pages: +- ['index.md', 'Home'] +- ['accounts_avails-list.md', 'Accounts', 'Avails List'] +- ['accounts_experience-locales-get.md', 'Accounts', 'Experience Locales Get'] +- ['accounts_experience-locales-list.md', 'Accounts', 'Experience Locales List'] +- ['accounts_orders-get.md', 'Accounts', 'Orders Get'] +- ['accounts_orders-list.md', 'Accounts', 'Orders List'] +- ['accounts_store-infos-country-get.md', 'Accounts', 'Store Infos Country Get'] +- ['accounts_store-infos-list.md', 'Accounts', 'Store Infos List'] + +theme: readthedocs + +copyright: Copyright © 2015, `Sebastian Thiel` + diff --git a/gen/playmoviespartner1-cli/src/cmn.rs b/gen/playmoviespartner1-cli/src/cmn.rs new file mode 100644 index 0000000000..8358f156fa --- /dev/null +++ b/gen/playmoviespartner1-cli/src/cmn.rs @@ -0,0 +1,721 @@ +// COPY OF 'src/rust/cli/cmn.rs' +// DO NOT EDIT +use oauth2::{ApplicationSecret, ConsoleApplicationSecret, TokenStorage, Token}; +use serde_json as json; +use serde_json::value::Value; +use mime::Mime; +use clap::{App, SubCommand}; +use strsim; + +use std::fs; +use std::env; +use std::io; +use std::fmt; +use std::path::{Path, PathBuf}; +use std::str::FromStr; +use std::string::ToString; +use std::io::{Write, Read, stdout}; + +use std::default::Default; + +const FIELD_SEP: char = '.'; + + +pub enum ComplexType { + Pod, + Vec, + Map, +} + + // Null, + // Bool(bool), + // I64(i64), + // U64(u64), + // F64(f64), + // String(String), + +pub enum JsonType { + Boolean, + Int, + Uint, + Float, + String, +} + +pub struct JsonTypeInfo { + pub jtype: JsonType, + pub ctype: ComplexType, +} + +// Based on @erickt user comment. Thanks for the idea ! +// Remove all keys whose values are null from given value (changed in place) +pub fn remove_json_null_values(value: &mut Value) { + match *value { + Value::Object(ref mut map) => { + let mut for_removal = Vec::new(); + + for (key, mut value) in map.iter_mut() { + if value.is_null() { + for_removal.push(key.clone()); + } else { + remove_json_null_values(&mut value); + } + } + + for key in &for_removal { + map.remove(key); + } + } + _ => {} + } +} + +fn did_you_mean<'a>(v: &str, possible_values: &[&'a str]) -> Option<&'a str> { + + let mut candidate: Option<(f64, &str)> = None; + for pv in possible_values { + let confidence = strsim::jaro_winkler(v, pv); + if confidence > 0.8 && (candidate.is_none() || (candidate.as_ref().unwrap().0 < confidence)) { + candidate = Some((confidence, pv)); + } + } + match candidate { + None => None, + Some((_, candidate)) => Some(candidate), + } +} + +pub enum CallType { + Upload(UploadProtocol), + Standard, +} + +arg_enum!{ + pub enum UploadProtocol { + Simple, + Resumable + } +} + +impl AsRef for UploadProtocol { + fn as_ref(&self) -> &str { + match *self { + UploadProtocol::Simple => "simple", + UploadProtocol::Resumable => "resumable" + } + } +} + +impl AsRef for CallType { + fn as_ref(&self) -> &str { + match *self { + CallType::Upload(ref proto) => proto.as_ref(), + CallType::Standard => "standard-request" + } + } +} + +#[derive(Clone, Default)] +pub struct FieldCursor(Vec); + +impl ToString for FieldCursor { + fn to_string(&self) -> String { + self.0.join(".") + } +} + +impl From<&'static str> for FieldCursor { + fn from(value: &'static str) -> FieldCursor { + let mut res = FieldCursor::default(); + res.set(value).unwrap(); + res + } +} + +impl FieldCursor { + pub fn set(&mut self, value: &str) -> Result<(), CLIError> { + if value.len() == 0 { + return Err(CLIError::Field(FieldError::Empty)) + } + + let mut first_is_field_sep = false; + let mut char_count: usize = 0; + let mut last_c = FIELD_SEP; + let mut num_conscutive_field_seps = 0; + + let mut field = String::new(); + let mut fields = self.0.clone(); + + let push_field = |fs: &mut Vec, f: &mut String| { + if f.len() > 0 { + fs.push(f.clone()); + f.truncate(0); + } + }; + + for (cid, c) in value.chars().enumerate() { + char_count += 1; + + if c == FIELD_SEP { + if cid == 0 { + first_is_field_sep = true; + } + num_conscutive_field_seps += 1; + if cid > 0 && last_c == FIELD_SEP { + if fields.pop().is_none() { + return Err(CLIError::Field(FieldError::PopOnEmpty(value.to_string()))) + } + } else { + push_field(&mut fields, &mut field); + } + } else { + num_conscutive_field_seps = 0; + if cid == 1 { + if first_is_field_sep { + fields.truncate(0); + } + } + field.push(c); + } + + last_c = c; + } + + push_field(&mut fields, &mut field); + + if char_count == 1 && first_is_field_sep { + fields.truncate(0); + } + if char_count > 1 && num_conscutive_field_seps == 1 { + return Err(CLIError::Field(FieldError::TrailingFieldSep(value.to_string()))) + } + + self.0 = fields; + Ok(()) + } + + pub fn did_you_mean(value: &str, possible_values: &[&str]) -> Option { + if value.len() == 0 { + return None + } + + let mut last_c = FIELD_SEP; + + let mut field = String::new(); + let mut output = String::new(); + + let push_field = |fs: &mut String, f: &mut String| { + if f.len() > 0 { + fs.push_str( + match did_you_mean(&f, possible_values) { + Some(candidate) => candidate, + None => &f, + }); + f.truncate(0); + } + }; + + for (cid, c) in value.chars().enumerate() { + if c == FIELD_SEP { + if last_c != FIELD_SEP { + push_field(&mut output, &mut field); + } + output.push(c); + } else { + field.push(c); + } + + last_c = c; + } + + push_field(&mut output, &mut field); + + if &output == value { + None + } else { + Some(output) + } + } + + pub fn set_json_value(&self, mut object: &mut Value, + value: &str, type_info: JsonTypeInfo, + err: &mut InvalidOptionsError, + orig_cursor: &FieldCursor) { + assert!(self.0.len() > 0); + + for field in &self.0[..self.0.len()-1] { + let tmp = object; + object = + match *tmp { + Value::Object(ref mut mapping) => { + mapping.entry(field.to_owned()).or_insert( + Value::Object(Default::default()) + ) + }, + _ => panic!("We don't expect non-object Values here ...") + }; + } + + match *object { + Value::Object(ref mut mapping) => { + let field = &self.0[self.0.len()-1]; + let to_jval = + |value: &str, jtype: JsonType, err: &mut InvalidOptionsError| + -> Value { + match jtype { + JsonType::Boolean => + Value::Bool(arg_from_str(value, err, &field, "boolean")), + JsonType::Int => + Value::I64(arg_from_str(value, err, &field, "int")), + JsonType::Uint => + Value::U64(arg_from_str(value, err, &field, "uint")), + JsonType::Float => + Value::F64(arg_from_str(value, err, &field, "float")), + JsonType::String => + Value::String(value.to_owned()), + } + }; + + match type_info.ctype { + ComplexType::Pod => { + if mapping.insert(field.to_owned(), to_jval(value, type_info.jtype, err)).is_some() { + err.issues.push(CLIError::Field(FieldError::Duplicate(orig_cursor.to_string()))); + } + }, + ComplexType::Vec => { + match *mapping.entry(field.to_owned()) + .or_insert(Value::Array(Default::default())) { + Value::Array(ref mut values) => values.push(to_jval(value, type_info.jtype, err)), + _ => unreachable!() + } + }, + ComplexType::Map => { + let (key, value) = parse_kv_arg(value, err, true); + let jval = to_jval(value.unwrap_or(""), type_info.jtype, err); + + match *mapping.entry(field.to_owned()) + .or_insert(Value::Object(Default::default())) { + Value::Object(ref mut value_map) => { + if value_map.insert(key.to_owned(), jval).is_some() { + err.issues.push(CLIError::Field(FieldError::Duplicate(orig_cursor.to_string()))); + } + } + _ => unreachable!() + } + } + } + }, + _ => unreachable!() + } + } + + pub fn num_fields(&self) -> usize { + self.0.len() + } +} + +pub fn parse_kv_arg<'a>(kv: &'a str, err: &mut InvalidOptionsError, for_hashmap: bool) + -> (&'a str, Option<&'a str>) { + let mut add_err = || err.issues.push(CLIError::InvalidKeyValueSyntax(kv.to_string(),for_hashmap)); + match kv.find('=') { + None => { + add_err(); + return (kv, None) + }, + Some(pos) => { + let key = &kv[..pos]; + if kv.len() <= pos + 1 { + add_err(); + return (key, Some("")) + } + (key, Some(&kv[pos+1..])) + } + } +} + +pub fn calltype_from_str(name: &str, valid_protocols: Vec, err: &mut InvalidOptionsError) -> CallType { + CallType::Upload( + match UploadProtocol::from_str(name) { + Ok(up) => up, + Err(msg) => { + err.issues.push(CLIError::InvalidUploadProtocol(name.to_string(), valid_protocols)); + UploadProtocol::Simple + } + }) +} + +pub fn input_file_from_opts(file_path: &str, err: &mut InvalidOptionsError) -> Option { + match fs::File::open(file_path) { + Ok(f) => Some(f), + Err(io_err) => { + err.issues.push(CLIError::Input(InputError::IOError((file_path.to_string(), io_err)))); + None + } + } +} + +pub fn input_mime_from_opts(mime: &str, err: &mut InvalidOptionsError) -> Option { + match mime.parse() { + Ok(m) => Some(m), + Err(_) => { + err.issues.push(CLIError::Input(InputError::Mime(mime.to_string()))); + None + } + } +} + +pub fn writer_from_opts(arg: Option<&str>) -> Result, io::Error> { + let f = arg.unwrap_or("-"); + match f { + "-" => Ok(Box::new(stdout())), + _ => match fs::OpenOptions::new().create(true).write(true).open(f) { + Ok(f) => Ok(Box::new(f)), + Err(io_err) => Err(io_err), + } + } +} + + +pub fn arg_from_str<'a, T>(arg: &str, err: &mut InvalidOptionsError, + arg_name: &'a str, + arg_type: &'a str) -> T + where T: FromStr + Default, + ::Err: fmt::Display { + match FromStr::from_str(arg) { + Err(perr) => { + err.issues.push( + CLIError::ParseError(arg_name.to_owned(), arg_type.to_owned(), arg.to_string(), format!("{}", perr)) + ); + Default::default() + }, + Ok(v) => v, + } +} + +pub struct JsonTokenStorage { + pub program_name: &'static str, + pub db_dir: String, +} + +impl JsonTokenStorage { + fn path(&self, scope_hash: u64) -> PathBuf { + Path::new(&self.db_dir).join(&format!("{}-token-{}.json", self.program_name, scope_hash)) + } +} + +impl TokenStorage for JsonTokenStorage { + type Error = json::Error; + + // NOTE: logging might be interesting, currently we swallow all errors + fn set(&mut self, scope_hash: u64, _: &Vec<&str>, token: Option) -> Result<(), json::Error> { + match token { + None => { + match fs::remove_file(self.path(scope_hash)) { + Err(err) => + match err.kind() { + io::ErrorKind::NotFound => Ok(()), + _ => Err(json::Error::IoError(err)) + }, + Ok(_) => Ok(()), + } + } + Some(token) => { + match fs::OpenOptions::new().create(true).write(true).open(&self.path(scope_hash)) { + Ok(mut f) => { + match json::to_writer_pretty(&mut f, &token) { + Ok(_) => Ok(()), + Err(serde_err) => Err(serde_err), + } + }, + Err(io_err) => Err(json::Error::IoError(io_err)) + } + } + } + } + + fn get(&self, scope_hash: u64, _: &Vec<&str>) -> Result, json::Error> { + match fs::File::open(&self.path(scope_hash)) { + Ok(mut f) => { + match json::de::from_reader(f) { + Ok(token) => Ok(Some(token)), + Err(err) => Err(err), + } + }, + Err(io_err) => { + match io_err.kind() { + io::ErrorKind::NotFound => Ok(None), + _ => Err(json::Error::IoError(io_err)) + } + } + } + } +} + + +#[derive(Debug)] +pub enum ApplicationSecretError { + DecoderError((String, json::Error)), + FormatError(String), +} + +impl fmt::Display for ApplicationSecretError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + ApplicationSecretError::DecoderError((ref path, ref err)) + => writeln!(f, "Could not decode file at '{}' with error: {}.", + path, err), + ApplicationSecretError::FormatError(ref path) + => writeln!(f, "'installed' field is unset in secret file at '{}'.", + path), + } + } +} + +#[derive(Debug)] +pub enum ConfigurationError { + DirectoryCreationFailed((String, io::Error)), + DirectoryUnset, + HomeExpansionFailed(String), + Secret(ApplicationSecretError), + IOError((String, io::Error)), +} + +impl fmt::Display for ConfigurationError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + ConfigurationError::DirectoryCreationFailed((ref dir, ref err)) + => writeln!(f, "Directory '{}' could not be created with error: {}.", dir, err), + ConfigurationError::DirectoryUnset + => writeln!(f, "--config-dir was unset or empty."), + ConfigurationError::HomeExpansionFailed(ref dir) + => writeln!(f, "Couldn't find HOME directory of current user, failed to expand '{}'.", dir), + ConfigurationError::Secret(ref err) + => writeln!(f, "Secret -> {}", err), + ConfigurationError::IOError((ref path, ref err)) + => writeln!(f, "IO operation failed on path '{}' with error: {}.", path, err), + } + } +} + +#[derive(Debug)] +pub enum InputError { + IOError((String, io::Error)), + Mime(String), +} + +impl fmt::Display for InputError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + InputError::IOError((ref file_path, ref io_err)) + => writeln!(f, "Failed to open '{}' for reading with error: {}.", file_path, io_err), + InputError::Mime(ref mime) + => writeln!(f, "'{}' is not a known mime-type.", mime), + } + } +} + +#[derive(Debug)] +pub enum FieldError { + PopOnEmpty(String), + TrailingFieldSep(String), + Unknown(String, Option, Option), + Duplicate(String), + Empty, +} + + +impl fmt::Display for FieldError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + FieldError::PopOnEmpty(ref field) + => writeln!(f, "'{}': Cannot move up on empty field cursor.", field), + FieldError::TrailingFieldSep(ref field) + => writeln!(f, "'{}': Single field separator may not be last character.", field), + FieldError::Unknown(ref field, ref suggestion, ref value) => { + let suffix = + match *suggestion { + Some(ref s) => { + let kv = + match *value { + Some(ref v) => format!("{}={}", s, v), + None => s.clone(), + }; + format!(" Did you mean '{}' ?", kv) + }, + None => String::new(), + }; + writeln!(f, "Field '{}' does not exist.{}", field, suffix) + }, + FieldError::Duplicate(ref cursor) + => writeln!(f, "Value at '{}' was already set", cursor), + FieldError::Empty + => writeln!(f, "Field names must not be empty."), + } + } +} + + +#[derive(Debug)] +pub enum CLIError { + Configuration(ConfigurationError), + ParseError(String, String, String, String), + UnknownParameter(String, Vec<&'static str>), + InvalidUploadProtocol(String, Vec), + InvalidKeyValueSyntax(String, bool), + Input(InputError), + Field(FieldError), + MissingCommandError, + MissingMethodError(String), +} + +impl fmt::Display for CLIError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + CLIError::Configuration(ref err) => write!(f, "Configuration -> {}", err), + CLIError::Input(ref err) => write!(f, "Input -> {}", err), + CLIError::Field(ref err) => write!(f, "Field -> {}", err), + CLIError::InvalidUploadProtocol(ref proto_name, ref valid_names) + => writeln!(f, "'{}' is not a valid upload protocol. Choose from one of {}.", proto_name, valid_names.join(", ")), + CLIError::ParseError(ref arg_name, ref type_name, ref value, ref err_desc) + => writeln!(f, "Failed to parse argument '{}' with value '{}' as {} with error: {}.", + arg_name, value, type_name, err_desc), + CLIError::UnknownParameter(ref param_name, ref possible_values) => { + let mut suffix = + match did_you_mean(param_name, &possible_values) { + Some(v) => format!(" Did you mean '{}' ?", v), + None => String::new(), + }; + write!(f, "Parameter '{}' is unknown.{}\n", param_name, suffix) + }, + CLIError::InvalidKeyValueSyntax(ref kv, is_hashmap) => { + let hashmap_info = if is_hashmap { "hashmap " } else { "" }; + writeln!(f, "'{}' does not match {}pattern =.", kv, hashmap_info) + }, + CLIError::MissingCommandError => writeln!(f, "Please specify the main sub-command."), + CLIError::MissingMethodError(ref cmd) => writeln!(f, "Please specify the method to call on the '{}' command.", cmd), + } + } +} + +#[derive(Debug)] +pub struct InvalidOptionsError { + pub issues: Vec, + pub exit_code: i32, +} + +impl fmt::Display for InvalidOptionsError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + for issue in &self.issues { + try!(issue.fmt(f)); + } + Ok(()) + } +} + +impl InvalidOptionsError { + pub fn single(err: CLIError, exit_code: i32) -> InvalidOptionsError { + InvalidOptionsError { + issues: vec![err], + exit_code: exit_code, + } + } + + pub fn new() -> InvalidOptionsError { + InvalidOptionsError { + issues: Vec::new(), + exit_code: 1, + } + } +} + +pub fn assure_config_dir_exists(dir: &str) -> Result { + let trdir = dir.trim(); + if trdir.len() == 0 { + return Err(CLIError::Configuration(ConfigurationError::DirectoryUnset)) + } + + let expanded_config_dir = + if trdir.as_bytes()[0] == b'~' { + match env::var("HOME").ok().or(env::var("UserProfile").ok()) { + None => return Err(CLIError::Configuration(ConfigurationError::HomeExpansionFailed(trdir.to_string()))), + Some(mut user) => { + user.push_str(&trdir[1..]); + user + } + } + } else { + trdir.to_string() + }; + + if let Err(err) = fs::create_dir(&expanded_config_dir) { + if err.kind() != io::ErrorKind::AlreadyExists { + return Err(CLIError::Configuration( + ConfigurationError::DirectoryCreationFailed((expanded_config_dir, err)))) + } + } + + Ok(expanded_config_dir) +} + +pub fn application_secret_from_directory(dir: &str, + secret_basename: &str, + json_console_secret: &str) + -> Result { + let secret_path = Path::new(dir).join(secret_basename); + let secret_str = || secret_path.as_path().to_str().unwrap().to_string(); + let secret_io_error = |io_err: io::Error| { + Err(CLIError::Configuration(ConfigurationError::IOError( + (secret_str(), io_err) + ))) + }; + + for _ in 0..2 { + match fs::File::open(&secret_path) { + Err(mut err) => { + if err.kind() == io::ErrorKind::NotFound { + // Write our built-in one - user may adjust the written file at will + + err = match fs::OpenOptions::new().create(true).write(true).open(&secret_path) { + Err(cfe) => cfe, + Ok(mut f) => { + // Assure we convert 'ugly' json string into pretty one + let console_secret: ConsoleApplicationSecret + = json::from_str(json_console_secret).unwrap(); + match json::to_writer_pretty(&mut f, &console_secret) { + Err(serde_err) => match serde_err { + json::Error::IoError(err) => err, + _ => panic!("Unexpected serde error: {:#?}", serde_err) + }, + Ok(_) => continue, + } + } + }; + // fall through to IO error handling + } + return secret_io_error(err) + }, + Ok(mut f) => { + match json::de::from_reader::<_, ConsoleApplicationSecret>(f) { + Err(json::Error::IoError(err)) => + return secret_io_error(err), + Err(json_err) => + return Err(CLIError::Configuration( + ConfigurationError::Secret( + ApplicationSecretError::DecoderError( + (secret_str(), json_err) + )))), + Ok(console_secret) => + match console_secret.installed { + Some(secret) => return Ok(secret), + None => return Err( + CLIError::Configuration( + ConfigurationError::Secret( + ApplicationSecretError::FormatError(secret_str()) + ))) + }, + } + } + } + } + unreachable!(); +} diff --git a/gen/playmoviespartner1-cli/src/main.rs b/gen/playmoviespartner1-cli/src/main.rs new file mode 100644 index 0000000000..a0ba81f058 --- /dev/null +++ b/gen/playmoviespartner1-cli/src/main.rs @@ -0,0 +1,910 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/cli/main.rs.mako' +// DO NOT EDIT ! +#![allow(unused_variables, unused_imports, dead_code, unused_mut)] + +#[macro_use] +extern crate clap; +extern crate yup_oauth2 as oauth2; +extern crate yup_hyper_mock as mock; +extern crate serde; +extern crate serde_json; +extern crate hyper; +extern crate mime; +extern crate strsim; +extern crate google_playmoviespartner1 as api; + +use std::env; +use std::io::{self, Write}; +use clap::{App, SubCommand, Arg}; + +mod cmn; + +use cmn::{InvalidOptionsError, CLIError, JsonTokenStorage, arg_from_str, writer_from_opts, parse_kv_arg, + input_file_from_opts, input_mime_from_opts, FieldCursor, FieldError, CallType, UploadProtocol, + calltype_from_str, remove_json_null_values, ComplexType, JsonType, JsonTypeInfo}; + +use std::default::Default; +use std::str::FromStr; + +use oauth2::{Authenticator, DefaultAuthenticatorDelegate}; +use serde_json as json; +use clap::ArgMatches; + +enum DoitError { + IoError(String, io::Error), + ApiError(api::Error), +} + +struct Engine<'n, 'a> { + opt: ArgMatches<'n, 'a>, + hub: api::Playmoviespartner>, + gp: Vec<&'static str>, + gpm: Vec<(&'static str, &'static str)>, +} + + +impl<'n, 'a> Engine<'n, 'a> { + fn _accounts_avails_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.accounts().avails_list(opt.value_of("account-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "video-ids" => { + call = call.add_video_ids(value.unwrap_or("")); + }, + "title" => { + call = call.title(value.unwrap_or("")); + }, + "territories" => { + call = call.add_territories(value.unwrap_or("")); + }, + "studio-names" => { + call = call.add_studio_names(value.unwrap_or("")); + }, + "pph-names" => { + call = call.add_pph_names(value.unwrap_or("")); + }, + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "page-size" => { + call = call.page_size(arg_from_str(value.unwrap_or("-0"), err, "page-size", "integer")); + }, + "alt-id" => { + call = call.alt_id(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["pph-names", "alt-id", "video-ids", "page-size", "page-token", "title", "studio-names", "territories"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _accounts_experience_locales_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.accounts().experience_locales_get(opt.value_of("account-id").unwrap_or(""), opt.value_of("el-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _accounts_experience_locales_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.accounts().experience_locales_list(opt.value_of("account-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "title-level-eidr" => { + call = call.title_level_eidr(value.unwrap_or("")); + }, + "studio-names" => { + call = call.add_studio_names(value.unwrap_or("")); + }, + "status" => { + call = call.add_status(value.unwrap_or("")); + }, + "pph-names" => { + call = call.add_pph_names(value.unwrap_or("")); + }, + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "page-size" => { + call = call.page_size(arg_from_str(value.unwrap_or("-0"), err, "page-size", "integer")); + }, + "edit-level-eidr" => { + call = call.edit_level_eidr(value.unwrap_or("")); + }, + "custom-id" => { + call = call.custom_id(value.unwrap_or("")); + }, + "alt-cut-id" => { + call = call.alt_cut_id(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["status", "pph-names", "title-level-eidr", "page-size", "studio-names", "page-token", "edit-level-eidr", "custom-id", "alt-cut-id"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _accounts_orders_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.accounts().orders_get(opt.value_of("account-id").unwrap_or(""), opt.value_of("order-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _accounts_orders_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.accounts().orders_list(opt.value_of("account-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "studio-names" => { + call = call.add_studio_names(value.unwrap_or("")); + }, + "status" => { + call = call.add_status(value.unwrap_or("")); + }, + "pph-names" => { + call = call.add_pph_names(value.unwrap_or("")); + }, + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "page-size" => { + call = call.page_size(arg_from_str(value.unwrap_or("-0"), err, "page-size", "integer")); + }, + "name" => { + call = call.name(value.unwrap_or("")); + }, + "custom-id" => { + call = call.custom_id(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["status", "pph-names", "name", "page-size", "studio-names", "page-token", "custom-id"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _accounts_store_infos_country_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.accounts().store_infos_country_get(opt.value_of("account-id").unwrap_or(""), opt.value_of("video-id").unwrap_or(""), opt.value_of("country").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _accounts_store_infos_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.accounts().store_infos_list(opt.value_of("account-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "video-ids" => { + call = call.add_video_ids(value.unwrap_or("")); + }, + "video-id" => { + call = call.video_id(value.unwrap_or("")); + }, + "studio-names" => { + call = call.add_studio_names(value.unwrap_or("")); + }, + "pph-names" => { + call = call.add_pph_names(value.unwrap_or("")); + }, + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "page-size" => { + call = call.page_size(arg_from_str(value.unwrap_or("-0"), err, "page-size", "integer")); + }, + "name" => { + call = call.name(value.unwrap_or("")); + }, + "countries" => { + call = call.add_countries(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["pph-names", "video-ids", "page-size", "countries", "studio-names", "video-id", "page-token", "name"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _doit(&self, dry_run: bool) -> Result, Option> { + let mut err = InvalidOptionsError::new(); + let mut call_result: Result<(), DoitError> = Ok(()); + let mut err_opt: Option = None; + match self.opt.subcommand() { + ("accounts", Some(opt)) => { + match opt.subcommand() { + ("avails-list", Some(opt)) => { + call_result = self._accounts_avails_list(opt, dry_run, &mut err); + }, + ("experience-locales-get", Some(opt)) => { + call_result = self._accounts_experience_locales_get(opt, dry_run, &mut err); + }, + ("experience-locales-list", Some(opt)) => { + call_result = self._accounts_experience_locales_list(opt, dry_run, &mut err); + }, + ("orders-get", Some(opt)) => { + call_result = self._accounts_orders_get(opt, dry_run, &mut err); + }, + ("orders-list", Some(opt)) => { + call_result = self._accounts_orders_list(opt, dry_run, &mut err); + }, + ("store-infos-country-get", Some(opt)) => { + call_result = self._accounts_store_infos_country_get(opt, dry_run, &mut err); + }, + ("store-infos-list", Some(opt)) => { + call_result = self._accounts_store_infos_list(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("accounts".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + _ => { + err.issues.push(CLIError::MissingCommandError); + writeln!(io::stderr(), "{}\n", self.opt.usage()).ok(); + } + } + + if dry_run { + if err.issues.len() > 0 { + err_opt = Some(err); + } + Err(err_opt) + } else { + Ok(call_result) + } + } + + // Please note that this call will fail if any part of the opt can't be handled + fn new(opt: ArgMatches<'a, 'n>) -> Result, InvalidOptionsError> { + let (config_dir, secret) = { + let config_dir = match cmn::assure_config_dir_exists(opt.value_of("folder").unwrap_or("~/.google-service-cli")) { + Err(e) => return Err(InvalidOptionsError::single(e, 3)), + Ok(p) => p, + }; + + match cmn::application_secret_from_directory(&config_dir, "playmoviespartner1-secret.json", + "{\"installed\":{\"auth_uri\":\"https://accounts.google.com/o/oauth2/auth\",\"client_secret\":\"hCsslbCUyfehWMmbkG8vTYxG\",\"token_uri\":\"https://accounts.google.com/o/oauth2/token\",\"client_email\":\"\",\"redirect_uris\":[\"urn:ietf:wg:oauth:2.0:oob\",\"oob\"],\"client_x509_cert_url\":\"\",\"client_id\":\"620010449518-9ngf7o4dhs0dka470npqvor6dc5lqb9b.apps.googleusercontent.com\",\"auth_provider_x509_cert_url\":\"https://www.googleapis.com/oauth2/v1/certs\"}}") { + Ok(secret) => (config_dir, secret), + Err(e) => return Err(InvalidOptionsError::single(e, 4)) + } + }; + + let auth = Authenticator::new( &secret, DefaultAuthenticatorDelegate, + if opt.is_present("debug-auth") { + hyper::Client::with_connector(mock::TeeConnector { + connector: hyper::net::HttpsConnector::::default() + }) + } else { + hyper::Client::new() + }, + JsonTokenStorage { + program_name: "playmoviespartner1", + db_dir: config_dir.clone(), + }, None); + + let client = + if opt.is_present("debug") { + hyper::Client::with_connector(mock::TeeConnector { + connector: hyper::net::HttpsConnector::::default() + }) + } else { + hyper::Client::new() + }; + let engine = Engine { + opt: opt, + hub: api::Playmoviespartner::new(client, auth), + gp: vec!["$-xgafv", "access-token", "alt", "bearer-token", "callback", "fields", "key", "oauth-token", "pp", "pretty-print", "quota-user", "upload-type", "upload-protocol"], + gpm: vec![ + ("$-xgafv", "$.xgafv"), + ("access-token", "access_token"), + ("bearer-token", "bearer_token"), + ("oauth-token", "oauth_token"), + ("pretty-print", "prettyPrint"), + ("quota-user", "quotaUser"), + ("upload-type", "uploadType"), + ("upload-protocol", "upload_protocol"), + ] + }; + + match engine._doit(true) { + Err(Some(err)) => Err(err), + Err(None) => Ok(engine), + Ok(_) => unreachable!(), + } + } + + fn doit(&self) -> Result<(), DoitError> { + match self._doit(false) { + Ok(res) => res, + Err(_) => unreachable!(), + } + } +} + +fn main() { + let mut exit_status = 0i32; + let arg_data = [ + ("accounts", "methods: 'avails-list', 'experience-locales-get', 'experience-locales-list', 'orders-get', 'orders-list', 'store-infos-country-get' and 'store-infos-list'", vec![ + ("avails-list", + Some(r##"List Avails owned or managed by the partner. See _Authentication and Authorization rules_ and _List methods rules_ for more information about this method."##), + "Details at http://byron.github.io/google-apis-rs/google_playmoviespartner1_cli/accounts_avails-list", + vec![ + (Some(r##"account-id"##), + None, + Some(r##"REQUIRED. See _General rules_ for more information about this field."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("experience-locales-get", + Some(r##"Get an ExperienceLocale given its id. See _Authentication and Authorization rules_ and _Get methods rules_ for more information about this method."##), + "Details at http://byron.github.io/google-apis-rs/google_playmoviespartner1_cli/accounts_experience-locales-get", + vec![ + (Some(r##"account-id"##), + None, + Some(r##"REQUIRED. See _General rules_ for more information about this field."##), + Some(true), + Some(false)), + + (Some(r##"el-id"##), + None, + Some(r##"REQUIRED. ExperienceLocale ID, as defined by Google."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("experience-locales-list", + Some(r##"List ExperienceLocales owned or managed by the partner. See _Authentication and Authorization rules_ and _List methods rules_ for more information about this method."##), + "Details at http://byron.github.io/google-apis-rs/google_playmoviespartner1_cli/accounts_experience-locales-list", + vec![ + (Some(r##"account-id"##), + None, + Some(r##"REQUIRED. See _General rules_ for more information about this field."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("orders-get", + Some(r##"Get an Order given its id. See _Authentication and Authorization rules_ and _Get methods rules_ for more information about this method."##), + "Details at http://byron.github.io/google-apis-rs/google_playmoviespartner1_cli/accounts_orders-get", + vec![ + (Some(r##"account-id"##), + None, + Some(r##"REQUIRED. See _General rules_ for more information about this field."##), + Some(true), + Some(false)), + + (Some(r##"order-id"##), + None, + Some(r##"REQUIRED. Order ID."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("orders-list", + Some(r##"List Orders owned or managed by the partner. See _Authentication and Authorization rules_ and _List methods rules_ for more information about this method."##), + "Details at http://byron.github.io/google-apis-rs/google_playmoviespartner1_cli/accounts_orders-list", + vec![ + (Some(r##"account-id"##), + None, + Some(r##"REQUIRED. See _General rules_ for more information about this field."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("store-infos-country-get", + Some(r##"Get a StoreInfo given its video id and country. See _Authentication and Authorization rules_ and _Get methods rules_ for more information about this method."##), + "Details at http://byron.github.io/google-apis-rs/google_playmoviespartner1_cli/accounts_store-infos-country-get", + vec![ + (Some(r##"account-id"##), + None, + Some(r##"REQUIRED. See _General rules_ for more information about this field."##), + Some(true), + Some(false)), + + (Some(r##"video-id"##), + None, + Some(r##"REQUIRED. Video ID."##), + Some(true), + Some(false)), + + (Some(r##"country"##), + None, + Some(r##"REQUIRED. Edit country."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("store-infos-list", + Some(r##"List StoreInfos owned or managed by the partner. See _Authentication and Authorization rules_ and _List methods rules_ for more information about this method."##), + "Details at http://byron.github.io/google-apis-rs/google_playmoviespartner1_cli/accounts_store-infos-list", + vec![ + (Some(r##"account-id"##), + None, + Some(r##"REQUIRED. See _General rules_ for more information about this field."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ]; + + let mut app = App::new("playmoviespartner1") + .author("Sebastian Thiel ") + .version("0.3.2+20150812") + .about("Lets Google Play Movies Partners get the delivery status of their titles.") + .after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_playmoviespartner1_cli") + .arg(Arg::with_name("url") + .long("scope") + .help("Specify the authentication a method should be executed in. Each scope requires the user to grant this application permission to use it.If unset, it defaults to the shortest scope url for a particular method.") + .multiple(true) + .takes_value(true)) + .arg(Arg::with_name("folder") + .long("config-dir") + .help("A directory into which we will store our persistent data. Defaults to a user-writable directory that we will create during the first invocation.[default: ~/.google-service-cli") + .multiple(false) + .takes_value(true)) + .arg(Arg::with_name("debug") + .long("debug") + .help("Output all server communication to standard error. `tx` and `rx` are placed into the same stream.") + .multiple(false) + .takes_value(false)) + .arg(Arg::with_name("debug-auth") + .long("debug-auth") + .help("Output all communication related to authentication to standard error. `tx` and `rx` are placed into the same stream.") + .multiple(false) + .takes_value(false)); + + for &(main_command_name, ref about, ref subcommands) in arg_data.iter() { + let mut mcmd = SubCommand::with_name(main_command_name).about(about); + + for &(sub_command_name, ref desc, url_info, ref args) in subcommands { + let mut scmd = SubCommand::with_name(sub_command_name); + if let &Some(desc) = desc { + scmd = scmd.about(desc); + } + scmd = scmd.after_help(url_info); + + for &(ref arg_name, ref flag, ref desc, ref required, ref multi) in args { + let arg_name_str = + match (arg_name, flag) { + (&Some(an), _ ) => an, + (_ , &Some(f)) => f, + _ => unreachable!(), + }; + let mut arg = Arg::with_name(arg_name_str) + .empty_values(false); + if let &Some(short_flag) = flag { + arg = arg.short(short_flag); + } + if let &Some(desc) = desc { + arg = arg.help(desc); + } + if arg_name.is_some() && flag.is_some() { + arg = arg.takes_value(true); + } + if let &Some(required) = required { + arg = arg.required(required); + } + if let &Some(multi) = multi { + arg = arg.multiple(multi); + } + scmd = scmd.arg(arg); + } + mcmd = mcmd.subcommand(scmd); + } + app = app.subcommand(mcmd); + } + + let matches = app.get_matches(); + + let debug = matches.is_present("debug"); + match Engine::new(matches) { + Err(err) => { + exit_status = err.exit_code; + writeln!(io::stderr(), "{}", err).ok(); + }, + Ok(engine) => { + if let Err(doit_err) = engine.doit() { + exit_status = 1; + match doit_err { + DoitError::IoError(path, err) => { + writeln!(io::stderr(), "Failed to open output file '{}': {}", path, err).ok(); + }, + DoitError::ApiError(err) => { + if debug { + writeln!(io::stderr(), "{:#?}", err).ok(); + } else { + writeln!(io::stderr(), "{}", err).ok(); + } + } + } + } + } + } + + std::process::exit(exit_status); +} \ No newline at end of file diff --git a/gen/playmoviespartner1/Cargo.toml b/gen/playmoviespartner1/Cargo.toml new file mode 100644 index 0000000000..32421bb768 --- /dev/null +++ b/gen/playmoviespartner1/Cargo.toml @@ -0,0 +1,29 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-playmoviespartner1" +version = "0.1.9+20150812" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with playmoviespartner (protocol v1)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/playmoviespartner1" +homepage = "https://developers.google.com/playmoviespartner/" +documentation = "http://byron.github.io/google-apis-rs/google_playmoviespartner1" +license = "MIT" +keywords = ["playmoviespartner", "google", "protocol", "web", "api"] +build = "src/build.rs" + + +[dependencies] +hyper = ">= 0.6.8" +mime = "0.1.0" +serde = ">= 0.6.0" +serde_json = ">= 0.6.0" +yup-oauth2 = "*" +url = "*" + +[build-dependencies] +syntex = { version = "*" } +serde_codegen = { version = "*" } + diff --git a/gen/playmoviespartner1/LICENSE.md b/gen/playmoviespartner1/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/playmoviespartner1/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/playmoviespartner1/README.md b/gen/playmoviespartner1/README.md new file mode 100644 index 0000000000..642cacbe14 --- /dev/null +++ b/gen/playmoviespartner1/README.md @@ -0,0 +1,173 @@ + +The `google-playmoviespartner1` library allows access to all features of the *Google playmoviespartner* service. + +This documentation was generated from *playmoviespartner* crate version *0.1.9+20150812*, where *20150812* is the exact revision of the *playmoviespartner:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. + +Everything else about the *playmoviespartner* *v1* API can be found at the +[official documentation site](https://developers.google.com/playmoviespartner/). +# Features + +Handle the following *Resources* with ease from the central [hub](http://byron.github.io/google-apis-rs/google_playmoviespartner1/struct.Playmoviespartner.html) ... + +* accounts + * [*avails list*](http://byron.github.io/google-apis-rs/google_playmoviespartner1/struct.AccountAvailListCall.html), [*experience locales get*](http://byron.github.io/google-apis-rs/google_playmoviespartner1/struct.AccountExperienceLocaleGetCall.html), [*experience locales list*](http://byron.github.io/google-apis-rs/google_playmoviespartner1/struct.AccountExperienceLocaleListCall.html), [*orders get*](http://byron.github.io/google-apis-rs/google_playmoviespartner1/struct.AccountOrderGetCall.html), [*orders list*](http://byron.github.io/google-apis-rs/google_playmoviespartner1/struct.AccountOrderListCall.html), [*store infos country get*](http://byron.github.io/google-apis-rs/google_playmoviespartner1/struct.AccountStoreInfoCountryGetCall.html) and [*store infos list*](http://byron.github.io/google-apis-rs/google_playmoviespartner1/struct.AccountStoreInfoListCall.html) + + + + +# Structure of this Library + +The API is structured into the following primary items: + +* **[Hub](http://byron.github.io/google-apis-rs/google_playmoviespartner1/struct.Playmoviespartner.html)** + * a central object to maintain state and allow accessing all *Activities* + * creates [*Method Builders*](http://byron.github.io/google-apis-rs/google_playmoviespartner1/trait.MethodsBuilder.html) which in turn + allow access to individual [*Call Builders*](http://byron.github.io/google-apis-rs/google_playmoviespartner1/trait.CallBuilder.html) +* **[Resources](http://byron.github.io/google-apis-rs/google_playmoviespartner1/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_playmoviespartner1/trait.Part.html)** + * a collection of properties + * never directly used in *Activities* +* **[Activities](http://byron.github.io/google-apis-rs/google_playmoviespartner1/trait.CallBuilder.html)** + * operations to apply to *Resources* + +All *structures* are marked with applicable traits to further categorize them and ease browsing. + +Generally speaking, you can invoke *Activities* like this: + +```Rust,ignore +let r = hub.resource().activity(...).doit() +``` + +Or specifically ... + +```ignore +let r = hub.accounts().store_infos_country_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-playmoviespartner1 = "*" +``` + +## A complete example + +```Rust +extern crate hyper; +extern crate yup_oauth2 as oauth2; +extern crate google_playmoviespartner1 as playmoviespartner1; +use playmoviespartner1::{Result, Error}; +use std::default::Default; +use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +use playmoviespartner1::Playmoviespartner; + +// 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 = Playmoviespartner::new(hyper::Client::new(), auth); +// You can configure optional parameters by calling 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().store_infos_country_get("accountId", "videoId", "country") + .doit(); + +match result { + Err(e) => match e { + // The Error enum provides details about what exactly happened. + // You can also just use its `Debug`, `Display` or `Error` traits + Error::HttpError(_) + |Error::MissingAPIKey + |Error::MissingToken(_) + |Error::Cancelled + |Error::UploadSizeLimitExceeded(_, _) + |Error::Failure(_) + |Error::BadRequest(_) + |Error::FieldClash(_) + |Error::JsonDecodeError(_, _) => println!("{}", e), + }, + Ok(res) => println!("Success: {:?}", res), +} + +``` +## Handling Errors + +All errors produced by the system are provided either as [Result](http://byron.github.io/google-apis-rs/google_playmoviespartner1/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_playmoviespartner1/trait.Delegate.html), or the [Authenticator Delegate](http://byron.github.io/google-apis-rs/google_playmoviespartner1/../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 Downloads +If a method supports downloads, the response body, which is part of the [Result](http://byron.github.io/google-apis-rs/google_playmoviespartner1/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_playmoviespartner1/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_playmoviespartner1/trait.Delegate.html) to the +[Method Builder](http://byron.github.io/google-apis-rs/google_playmoviespartner1/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_playmoviespartner1/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_playmoviespartner1/trait.RequestValue.html) and +[decodable](http://byron.github.io/google-apis-rs/google_playmoviespartner1/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_playmoviespartner1/trait.Part.html) which are identifiable 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_playmoviespartner1/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_playmoviespartner1/trait.RequestValue.html) are moved + +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 **playmoviespartner1** 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/playmoviespartner1/src/build.rs b/gen/playmoviespartner1/src/build.rs new file mode 100644 index 0000000000..fc97d3fa42 --- /dev/null +++ b/gen/playmoviespartner1/src/build.rs @@ -0,0 +1,16 @@ +extern crate syntex; +extern crate serde_codegen; + +use std::env; +use std::path::Path; + +pub fn main() { + let out_dir = env::var_os("OUT_DIR").unwrap(); + + let src = Path::new("src/lib.rs.in"); + let dst = Path::new(&out_dir).join("lib.rs"); + + let mut registry = syntex::Registry::new(); + serde_codegen::register(&mut registry); + registry.expand("google-playmoviespartner1", &src, &dst).unwrap(); +} diff --git a/gen/playmoviespartner1/src/cmn.rs b/gen/playmoviespartner1/src/cmn.rs new file mode 100644 index 0000000000..0e31353ba3 --- /dev/null +++ b/gen/playmoviespartner1/src/cmn.rs @@ -0,0 +1,762 @@ +// COPY OF 'src/rust/api/cmn.rs' +// DO NOT EDIT +use std::io::{self, Read, Seek, Cursor, Write, SeekFrom}; +use std; +use std::fmt::{self, Display}; +use std::str::FromStr; +use std::error; +use std::thread::sleep_ms; + +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::h1::LINE_ENDING; +use hyper::method::Method; +use hyper::status::StatusCode; + +use serde_json as json; + +/// 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 {} + +/// Identifies types for building methods of a particular resource type +pub trait MethodsBuilder {} + +/// Identifies types which represent builders for a particular resource method +pub trait CallBuilder {} + +/// Identifies types which can be inserted and deleted. +/// Types with this trait are most commonly used by clients of this API. +pub trait Resource {} + +/// Identifies types which are used in API responses. +pub trait ResponseResult {} + +/// Identifies types which are used in API requests. +pub trait RequestValue {} + +/// Identifies types which are not actually used by the API +/// This might be a bug within the google API schema. +pub trait UnusedType {} + +/// Identifies types which are only used as part of other types, which +/// usually are carrying the `Resource` trait. +pub trait Part {} + +/// 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 {} + +/// 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 +} + +/// A utility to represent detailed errors we might see in case there are BadRequests. +/// The latter happen if the sent parameters or request structures are unsound +#[derive(Deserialize, Serialize, Debug)] +pub struct ErrorResponse { + error: ServerError, +} + +#[derive(Deserialize, Serialize, Debug)] +pub struct ServerError { + errors: Vec, + code: u16, + message: String, +} + +#[derive(Deserialize, Serialize, Debug)] +pub struct ServerMessage { + domain: String, + reason: String, + message: String, + #[serde(rename="locationType")] + location_type: Option, + location: 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 successful. That way, the delegate 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. + /// + /// If you choose to retry after a duration, the duration should be chosen using the + /// [exponential backoff algorithm](http://en.wikipedia.org/wiki/Exponential_backoff). + /// + /// Return retry information. + fn http_error(&mut self, &hyper::Error) -> 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 it as a general information about the + /// impending failure. + /// The given Error provides information about why the token couldn't be acquired in the + /// first place + fn token(&mut self, err: &error::Error) -> Option { + let _ = err; + 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/canceled, 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()`. + /// It will also be called with None after a successful upload, which allows the delegate + /// to forget the URL. That way, we will not attempt to resume an upload that has already + /// finished. + fn store_upload_url(&mut self, url: Option<&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: &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. + /// + /// If you choose to retry after a duration, the duration should be chosen using the + /// [exponential backoff algorithm](http://en.wikipedia.org/wiki/Exponential_backoff). + fn http_failure(&mut self, _: &hyper::client::Response, Option, _: 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 {} + + +#[derive(Debug)] +pub enum Error { + /// The http connection failed + HttpError(hyper::Error), + + /// 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), + + /// Represents information about a request that was not understood by the server. + /// Details are included. + BadRequest(ErrorResponse), + + /// 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(Box), + + /// 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(String, json::Error), + + /// Indicates an HTTP repsonse with a non-success status code + Failure(hyper::client::Response), +} + + +impl Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + Error::HttpError(ref err) => err.fmt(f), + Error::UploadSizeLimitExceeded(ref resource_size, ref max_size) => + writeln!(f, "The media size {} exceeds the maximum allowed upload size of {}" + , resource_size, max_size), + Error::MissingAPIKey => { + (writeln!(f, "The application's API key was not found in the configuration")).ok(); + writeln!(f, "It is used as there are no Scopes defined for this method.") + }, + Error::BadRequest(ref err) => { + try!(writeln!(f, "Bad Requst ({}): {}", err.error.code, err.error.message)); + for err in err.error.errors.iter() { + try!(writeln!(f, " {}: {}, {}{}", + err.domain, + err.message, + err.reason, + match &err.location { + &Some(ref loc) => format!("@{}", loc), + &None => String::new(), + })); + } + Ok(()) + }, + Error::MissingToken(ref err) => + writeln!(f, "Token retrieval failed with error: {}", err), + Error::Cancelled => + writeln!(f, "Operation cancelled by delegate"), + Error::FieldClash(field) => + writeln!(f, "The custom parameter '{}' is already provided natively by the CallBuilder.", field), + Error::JsonDecodeError(ref json_str, ref err) + => writeln!(f, "{}: {}", err, json_str), + Error::Failure(ref response) => + writeln!(f, "Http status indicates failure: {:?}", response), + } + } +} + +impl error::Error for Error { + fn description(&self) -> &str { + match *self { + Error::HttpError(ref err) => err.description(), + Error::JsonDecodeError(_, ref err) => err.description(), + _ => "NO DESCRIPTION POSSIBLE - use `Display.fmt()` instead" + } + } + + fn cause(&self) -> Option<&error::Error> { + match *self { + Error::HttpError(ref err) => err.cause(), + Error::JsonDecodeError(_, ref err) => err.cause(), + _ => None + } + } +} + +/// A universal result type used as return for all calls. +pub type Result = std::result::Result; + +/// 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 + 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 following macro invocation needs to be expanded, as `include!` +// doens't support external macros +// header!{ +// #[doc="The `X-Upload-Content-Type` header."] +// (XUploadContentType, "X-Upload-Content-Type") => [Mime] + +// xupload_content_type { +// test_header!( +// test1, +// vec![b"text/plain"], +// Some(HeaderField( +// vec![Mime(TopLevel::Text, SubLevel::Plain, Vec::new())] +// ))); + +// } +// } + +/// The `X-Upload-Content-Type` header. +/// +/// Generated via rustc --pretty expanded -Z unstable-options, and manually +/// processed to be more readable. +#[derive(PartialEq, Debug, Clone)] +pub struct XUploadContentType(pub Mime); + +impl ::std::ops::Deref for XUploadContentType { + type Target = Mime; + fn deref<'a>(&'a self) -> &'a Mime { &self.0 } +} +impl ::std::ops::DerefMut for XUploadContentType { + fn deref_mut<'a>(&'a mut self) -> &'a mut Mime { &mut self.0 } +} +impl Header for XUploadContentType { + fn header_name() -> &'static str { "X-Upload-Content-Type" } + fn parse_header(raw: &[Vec]) -> hyper::error::Result { + hyper::header::parsing::from_one_raw_str(raw).map(XUploadContentType) + } +} +impl HeaderFormat for XUploadContentType { + fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { + Display::fmt(&**self, f) + } +} +impl Display for XUploadContentType { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Display::fmt(&**self, f) + } +} + +#[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]) -> hyper::error::Result { + Err(hyper::error::Error::Method) + } +} + + +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]) -> hyper::error::Result { + if raw.len() > 0 { + let v = &raw[0]; + if let Ok(s) = std::str::from_utf8(v) { + const PREFIX: &'static str = "bytes "; + if s.starts_with(PREFIX) { + if let Ok(c) = ::from_str(&s[PREFIX.len()..]) { + return Ok(RangeResponseHeader(c)) + } + } + } + } + Err(hyper::error::Error::Method) + } +} + +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, 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, A> ResumableUploadHelper<'a, A> + where A: oauth2::GetToken { + + fn query_transfer_status(&mut self) -> std::result::Result> { + 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, None) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + return Err(Ok(r)) + } + }; + return Ok(h.0.last) + } + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + return Err(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() { + Ok(s) => s, + Err(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 + }; + + self.reader.seek(SeekFrom::Start(start)).unwrap(); + loop { + let request_size = match self.content_length - start { + rs if rs > chunk_size => chunk_size, + rs => rs + }; + + 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 + } + // workaround https://github.com/rust-lang/rust/issues/22252 + let res = 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(); + match res { + 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, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + } + return Some(Ok(res)) + }, + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + return Some(Err(err)) + } + } + } + } +} + +// Copy of src/rust/cli/cmn.rs +// TODO(ST): Allow sharing common code between program types +pub fn remove_json_null_values(value: &mut json::value::Value) { + match *value { + json::value::Value::Object(ref mut map) => { + let mut for_removal = Vec::new(); + + for (key, mut value) in map.iter_mut() { + if value.is_null() { + for_removal.push(key.clone()); + } else { + remove_json_null_values(&mut value); + } + } + + for key in &for_removal { + map.remove(key); + } + } + _ => {} + } +} diff --git a/gen/playmoviespartner1/src/lib.rs b/gen/playmoviespartner1/src/lib.rs new file mode 100644 index 0000000000..0c229daf0c --- /dev/null +++ b/gen/playmoviespartner1/src/lib.rs @@ -0,0 +1,177 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/api/lib.rs.mako' +// DO NOT EDIT ! + +//! This documentation was generated from *playmoviespartner* crate version *0.1.9+20150812*, where *20150812* is the exact revision of the *playmoviespartner:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +//! +//! Everything else about the *playmoviespartner* *v1* API can be found at the +//! [official documentation site](https://developers.google.com/playmoviespartner/). +//! The original source code is [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/playmoviespartner1). +//! # Features +//! +//! Handle the following *Resources* with ease from the central [hub](struct.Playmoviespartner.html) ... +//! +//! * accounts +//! * [*avails list*](struct.AccountAvailListCall.html), [*experience locales get*](struct.AccountExperienceLocaleGetCall.html), [*experience locales list*](struct.AccountExperienceLocaleListCall.html), [*orders get*](struct.AccountOrderGetCall.html), [*orders list*](struct.AccountOrderListCall.html), [*store infos country get*](struct.AccountStoreInfoCountryGetCall.html) and [*store infos list*](struct.AccountStoreInfoListCall.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.Playmoviespartner.html)** +//! * a central object to maintain state and allow accessing all *Activities* +//! * creates [*Method Builders*](trait.MethodsBuilder.html) which in turn +//! allow access to individual [*Call Builders*](trait.CallBuilder.html) +//! * **[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* +//! +//! All *structures* are marked with applicable traits to further categorize them and ease browsing. +//! +//! Generally speaking, you can invoke *Activities* like this: +//! +//! ```Rust,ignore +//! let r = hub.resource().activity(...).doit() +//! ``` +//! +//! Or specifically ... +//! +//! ```ignore +//! let r = hub.accounts().store_infos_country_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-playmoviespartner1 = "*" +//! ``` +//! +//! ## A complete example +//! +//! ```test_harness,no_run +//! extern crate hyper; +//! extern crate yup_oauth2 as oauth2; +//! extern crate google_playmoviespartner1 as playmoviespartner1; +//! use playmoviespartner1::{Result, Error}; +//! # #[test] fn egal() { +//! use std::default::Default; +//! use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +//! use playmoviespartner1::Playmoviespartner; +//! +//! // 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 = Playmoviespartner::new(hyper::Client::new(), auth); +//! // You can configure optional parameters by calling 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().store_infos_country_get("accountId", "videoId", "country") +//! .doit(); +//! +//! match result { +//! Err(e) => match e { +//! // The Error enum provides details about what exactly happened. +//! // You can also just use its `Debug`, `Display` or `Error` traits +//! Error::HttpError(_) +//! |Error::MissingAPIKey +//! |Error::MissingToken(_) +//! |Error::Cancelled +//! |Error::UploadSizeLimitExceeded(_, _) +//! |Error::Failure(_) +//! |Error::BadRequest(_) +//! |Error::FieldClash(_) +//! |Error::JsonDecodeError(_, _) => println!("{}", e), +//! }, +//! Ok(res) => println!("Success: {:?}", res), +//! } +//! # } +//! ``` +//! ## 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 Downloads +//! 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 identifiable 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 moved +//! +//! 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 +//! +//! + +// 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)] + +include!(concat!(env!("OUT_DIR"), "/lib.rs")); \ No newline at end of file diff --git a/gen/playmoviespartner1/src/lib.rs.in b/gen/playmoviespartner1/src/lib.rs.in new file mode 100644 index 0000000000..7a19e85d9a --- /dev/null +++ b/gen/playmoviespartner1/src/lib.rs.in @@ -0,0 +1,2996 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/api/lib.rs.in.mako' +// DO NOT EDIT ! + +extern crate hyper; +extern crate serde; +extern crate serde_json; +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 serde_json as json; +use std::io; +use std::fs; +use std::thread::sleep_ms; + +pub use cmn::{MultiPartReader, ToParts, MethodInfo, Result, Error, CallBuilder, Hub, ReadSeek, Part, + ResponseResult, RequestValue, NestedType, Delegate, DefaultDelegate, MethodsBuilder, + Resource, ErrorResponse, remove_json_null_values}; + + +// ############## +// 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 the digital assets you publish on Google Play Movies and TV + PlaymovyPartnerReadonly, +} + +impl AsRef for Scope { + fn as_ref(&self) -> &str { + match *self { + Scope::PlaymovyPartnerReadonly => "https://www.googleapis.com/auth/playmovies_partner.readonly", + } + } +} + +impl Default for Scope { + fn default() -> Scope { + Scope::PlaymovyPartnerReadonly + } +} + + + +// ######## +// HUB ### +// ###### + +/// Central instance to access all Playmoviespartner related resource activities +/// +/// # Examples +/// +/// Instantiate a new hub +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate yup_oauth2 as oauth2; +/// extern crate google_playmoviespartner1 as playmoviespartner1; +/// use playmoviespartner1::{Result, Error}; +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use playmoviespartner1::Playmoviespartner; +/// +/// // 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 = Playmoviespartner::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling 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().store_infos_country_get("accountId", "videoId", "country") +/// .doit(); +/// +/// match result { +/// Err(e) => match e { +/// // The Error enum provides details about what exactly happened. +/// // You can also just use its `Debug`, `Display` or `Error` traits +/// Error::HttpError(_) +/// |Error::MissingAPIKey +/// |Error::MissingToken(_) +/// |Error::Cancelled +/// |Error::UploadSizeLimitExceeded(_, _) +/// |Error::Failure(_) +/// |Error::BadRequest(_) +/// |Error::FieldClash(_) +/// |Error::JsonDecodeError(_, _) => println!("{}", e), +/// }, +/// Ok(res) => println!("Success: {:?}", res), +/// } +/// # } +/// ``` +pub struct Playmoviespartner { + client: RefCell, + auth: RefCell, + _user_agent: String, +} + +impl<'a, C, A> Hub for Playmoviespartner {} + +impl<'a, C, A> Playmoviespartner + where C: BorrowMut, A: oauth2::GetToken { + + pub fn new(client: C, authenticator: A) -> Playmoviespartner { + Playmoviespartner { + client: RefCell::new(client), + auth: RefCell::new(authenticator), + _user_agent: "google-api-rust-client/0.1.9".to_string(), + } + } + + pub fn accounts(&'a self) -> AccountMethods<'a, C, 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.9`. + /// + /// 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 to the 'ListExperienceLocales' 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*). +/// +/// * [experience locales list accounts](struct.AccountExperienceLocaleListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ListExperienceLocalesResponse { + /// See _List methods rules_ for info about this field. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// List of ExperienceLocales that match the request criteria. + #[serde(rename="experienceLocales")] + pub experience_locales: Option>, +} + +impl ResponseResult for ListExperienceLocalesResponse {} + + +/// Response to the 'ListOrders' 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*). +/// +/// * [orders list accounts](struct.AccountOrderListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ListOrdersResponse { + /// See _List methods rules_ for info about this field. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// List of Orders that match the request criteria. + pub orders: Option>, +} + +impl ResponseResult for ListOrdersResponse {} + + +/// Response to the 'ListStoreInfos' 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*). +/// +/// * [store infos list accounts](struct.AccountStoreInfoListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ListStoreInfosResponse { + /// List of StoreInfos that match the request criteria. + #[serde(rename="storeInfos")] + pub store_infos: Option>, + /// See 'List methods rules' for info about this field. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, +} + +impl ResponseResult for ListStoreInfosResponse {} + + +/// An Avail describes the Availability Window of a specific Edit in a given country, which means the period Google is allowed to sell or rent the Edit. Avails are exposed in EMA format Version 1.6b (available at http://www.movielabs.com/md/avails/) Studios can see the Avails for the Titles they own. Post-production houses cannot see any Avails. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Avail { + /// Name of the post-production houses that manage the Avail. Not part of EMA Specs. + #[serde(rename="pphNames")] + pub pph_names: Option>, + /// Type of transaction. + #[serde(rename="licenseType")] + pub license_type: Option, + /// Manifestation Identifier. This should be the Manifestation Level EIDR. Example: "10.2340/1489-49A2-3956-4B2D-FE16-7" + #[serde(rename="encodeId")] + pub encode_id: Option, + /// Communicating if caption file will be delivered. + #[serde(rename="captionIncluded")] + pub caption_included: Option, + /// Release date of the Title in earliest released territory. Typically it is just the year, but it is free-form as per EMA spec. Examples: "1979", "Oct 2014" + #[serde(rename="releaseDate")] + pub release_date: Option, + /// Other identifier referring to the episode, as defined by partner. Only available on TV avails. Example: "rs_googlers_s1_3". + #[serde(rename="episodeAltId")] + pub episode_alt_id: Option, + /// OPTIONAL.TV Only. Title used by involved parties to refer to this episode. Only available on TV Avails. Example: "Coding at Google". + #[serde(rename="episodeTitleInternalAlias")] + pub episode_title_internal_alias: Option, + /// The number assigned to the episode within a season. Only available on TV Avails. Example: "3". + #[serde(rename="episodeNumber")] + pub episode_number: Option, + /// End of term in YYYY-MM-DD format in the timezone of the country of the Avail. "Open" if no end date is available. Example: "2019-02-17" + pub end: Option, + /// Other identifier referring to the Edit, as defined by partner. Example: "GOOGLER_2006" + #[serde(rename="altId")] + pub alt_id: Option, + /// Other identifier referring to the series, as defined by partner. Only available on TV avails. Example: "rs_googlers". + #[serde(rename="seriesAltId")] + pub series_alt_id: Option, + /// Start of term in YYYY-MM-DD format in the timezone of the country of the Avail. Example: "2013-05-14". + pub start: Option, + /// Title used by involved parties to refer to this content. Example: "Googlers, The". Only available on Movie Avails. + #[serde(rename="titleInternalAlias")] + pub title_internal_alias: Option, + /// Title used by involved parties to refer to this season. Only available on TV Avails. Example: "Googlers, The". + #[serde(rename="seasonTitleInternalAlias")] + pub season_title_internal_alias: Option, + /// ISO 3166-1 alpha-2 country code for the country or territory of this Avail. For Avails, we use Territory in lieu of Country to comply with EMA specifications. But please note that Territory and Country identify the same thing. Example: "US". + pub territory: Option, + /// Edit Identifier. This should be the Edit Level EIDR. Example: "10.2340/1489-49A2-3956-4B2D-FE16-6" + #[serde(rename="productId")] + pub product_id: Option, + /// Spoken language of the intended audience. Language shall be encoded in accordance with RFC 5646. Example: "fr". + #[serde(rename="storeLanguage")] + pub store_language: Option, + /// The number assigned to the season within a series. Only available on TV Avails. Example: "1". + #[serde(rename="seasonNumber")] + pub season_number: Option, + /// Indicates the format profile covered by the transaction. + #[serde(rename="formatProfile")] + pub format_profile: Option, + /// Value to be applied to the pricing type. Example: "4" or "2.99" + #[serde(rename="priceValue")] + pub price_value: Option, + /// Google-generated ID identifying the video linked to this Avail, once delivered. Not part of EMA Specs. Example: 'gtry456_xc' + #[serde(rename="videoId")] + pub video_id: Option, + /// Value representing the rating reason. Rating reasons should be formatted as per [EMA ratings spec](http://www.movielabs.com/md/ratings/) and comma-separated for inclusion of multiple reasons. Example: "L, S, V" + #[serde(rename="ratingReason")] + pub rating_reason: Option, + /// Communicating an exempt category as defined by FCC regulations. It is not required for non-US Avails. Example: "1" + #[serde(rename="captionExemption")] + pub caption_exemption: Option, + /// Work type as enumerated in EMA. + #[serde(rename="workType")] + pub work_type: Option, + /// The name of the studio that owns the Edit referred in the Avail. This is the equivalent of `studio_name` in other resources, but it follows the EMA nomenclature. Example: "Google Films". + #[serde(rename="displayName")] + pub display_name: Option, + /// Other identifier referring to the season, as defined by partner. Only available on TV avails. Example: "rs_googlers_s1". + #[serde(rename="seasonAltId")] + pub season_alt_id: Option, + /// Title Identifier. This should be the Title Level EIDR. Example: "10.5240/1489-49A2-3956-4B2D-FE16-5". + #[serde(rename="contentId")] + pub content_id: Option, + /// Rating system applied to the version of title within territory of Avail. Rating systems should be formatted as per [EMA ratings spec](http://www.movielabs.com/md/ratings/) Example: "MPAA" + #[serde(rename="ratingSystem")] + pub rating_system: Option, + /// Value representing the rating. Ratings should be formatted as per http://www.movielabs.com/md/ratings/ Example: "PG" + #[serde(rename="ratingValue")] + pub rating_value: Option, + /// Title used by involved parties to refer to this series. Only available on TV Avails. Example: "Googlers, The". + #[serde(rename="seriesTitleInternalAlias")] + pub series_title_internal_alias: Option, + /// First date an Edit could be publically announced as becoming available at a specific future date in territory of Avail. *Not* the Avail start date or pre-order start date. Format is YYYY-MM-DD. Only available for pre-orders. Example: "2012-12-10" + #[serde(rename="suppressionLiftDate")] + pub suppression_lift_date: Option, + /// Type of pricing that should be applied to this Avail based on how the partner classify them. Example: "Tier", "WSP", "SRP", or "Category". + #[serde(rename="priceType")] + pub price_type: Option, +} + +impl Part for Avail {} + + +/// An ExperienceLocale tracks the fulfillment of a Title in a country using a specific language, when delivered using component-based delivery. For example, a Title in Switzerland might have 3 ExperienceLocales: they both share the same country ("CH"), but each has different languages ("de", "fr", and "it"). Each ExperienceLocale is uniquely identified by an `el_id`, which is generated by Google. Externally, an ExperienceLocale can also be identified by partners using its EIDR IDs, AltCutID or `custom_id` (when provided). +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [experience locales get accounts](struct.AccountExperienceLocaleGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ExperienceLocale { + /// Name of the post-production houses that manage the ExperienceLocale. + #[serde(rename="pphNames")] + pub pph_names: Option>, + /// High-level status of the ExperienceLocale. + pub status: Option, + /// Title-level EIDR ID. Example: "10.5240/1489-49A2-3956-4B2D-FE16-5". + #[serde(rename="titleLevelEidr")] + pub title_level_eidr: Option, + /// Trailer ID, as defined by Google, linked to the trailer video in the ExperienceLocale. Example: 'gtry457_tr'. + #[serde(rename="trailerId")] + pub trailer_id: Option, + /// YouTube Channel ID linked to the ExperienceLocale. Example: "UCRG64darCZhb". + #[serde(rename="channelId")] + pub channel_id: Option, + /// Name of the studio that owns the ExperienceLocale. + #[serde(rename="studioName")] + pub studio_name: Option, + /// Video ID, as defined by Google, linked to the feature video in the ExperienceLocale. Example: 'gtry456_xc'. + #[serde(rename="videoId")] + pub video_id: Option, + /// Timestamp when the ExperienceLocale was approved. + #[serde(rename="approvedTime")] + pub approved_time: Option, + /// Edit-level EIDR ID. Example: "10.5240/1489-49A2-3956-4B2D-FE16-6". + #[serde(rename="editLevelEidr")] + pub edit_level_eidr: Option, + /// InventoryID as defined in the EMA specs. + #[serde(rename="inventoryId")] + pub inventory_id: Option, + /// PlayableSequenceID as defined in the EMA specs. + #[serde(rename="playableSequenceId")] + pub playable_sequence_id: Option, + /// Default Edit name, usually in the language of the country of origin. Example: "Googlers, The". + pub name: Option, + /// ID internally generated by Google to uniquely identify a ExperienceLocale. Example: 'KRZiVjY9h7t' + #[serde(rename="elId")] + pub el_id: Option, + /// PresentationID as defined in the EMA specs. + #[serde(rename="presentationId")] + pub presentation_id: Option, + /// Timestamp of the earliest start date of the Avails linked to this ExperienceLocale. + #[serde(rename="earliestAvailStartTime")] + pub earliest_avail_start_time: Option, + /// Language of the ExperienceLocale, using the "BCP 47" format. Examples: "en", "en-US", "es", "es-419". + pub language: Option, + /// Alternative Cut ID, sometimes available in lieu of the main Edit-level EIDR ID. This is not an EIDR ID, but a Partner-provided ID. Example: "206346_79838". + #[serde(rename="altCutId")] + pub alt_cut_id: Option, + /// List of custom IDs (defined by the partner) linked to this ExperienceLocale. Example: "R86241" + #[serde(rename="customIds")] + pub custom_ids: Option>, + /// ExperienceLocale priority, as defined by Google. The higher the value, the higher the priority. Example: 90 + pub priority: Option, + /// A simpler representation of the priority. + #[serde(rename="normalizedPriority")] + pub normalized_priority: Option, + /// Timestamp when the ExperienceLocale was created. + #[serde(rename="createdTime")] + pub created_time: Option, + /// Country where the ExperienceLocale is available, using the "ISO 3166-1 alpha-2" format. Example: "US". + pub country: Option, + /// Type of the Edit linked to the ExperienceLocale. + #[serde(rename="type")] + pub type_: Option, +} + +impl ResponseResult for ExperienceLocale {} + + +/// Information about a playable sequence (video) associated with an Edit and available at the Google Play Store. Internally, each StoreInfo is uniquely identified by a `video_id` and `country`. Externally, Title-level EIDR or Edit-level EIDR, if provided, can also be used to identify a specific title or edit in a country. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [store infos country get accounts](struct.AccountStoreInfoCountryGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct StoreInfo { + /// Name of the post-production houses that manage the Edit. + #[serde(rename="pphNames")] + pub pph_names: Option>, + /// Whether the Edit has a EST offer. + #[serde(rename="hasEstOffer")] + pub has_est_offer: Option, + /// Title-level EIDR ID. Example: "10.5240/1489-49A2-3956-4B2D-FE16-5". + #[serde(rename="titleLevelEidr")] + pub title_level_eidr: Option, + /// Whether the Edit has a SD offer. + #[serde(rename="hasSdOffer")] + pub has_sd_offer: Option, + /// The number assigned to the season within a show. Only available on TV Edits. Example: "1". + #[serde(rename="seasonNumber")] + pub season_number: Option, + /// Timestamp when the Edit went live on the Store. + #[serde(rename="liveTime")] + pub live_time: Option, + /// Google-generated ID identifying the trailer linked to the Edit. Example: 'bhd_4e_cx' + #[serde(rename="trailerId")] + pub trailer_id: Option, + /// Name of the studio that owns the Edit ordered. + #[serde(rename="studioName")] + pub studio_name: Option, + /// Google-generated ID identifying the video linked to the Edit. Example: 'gtry456_xc' + #[serde(rename="videoId")] + pub video_id: Option, + /// Whether the Edit has a HD offer. + #[serde(rename="hasHdOffer")] + pub has_hd_offer: Option, + /// Whether the Edit has a VOD offer. + #[serde(rename="hasVodOffer")] + pub has_vod_offer: Option, + /// Edit-level EIDR ID. Example: "10.5240/1489-49A2-3956-4B2D-FE16-6". + #[serde(rename="editLevelEidr")] + pub edit_level_eidr: Option, + /// Subtitles available for this Edit. + pub subtitles: Option>, + /// The number assigned to the episode within a season. Only available on TV Edits. Example: "1". + #[serde(rename="episodeNumber")] + pub episode_number: Option, + /// Google-generated ID identifying the show linked to the Edit. Only available for TV Edits. Example: 'et2hsue_x' + #[serde(rename="showId")] + pub show_id: Option, + /// Default Edit name, usually in the language of the country of origin. Example: "Googlers, The". + pub name: Option, + /// Country where Edit is available in ISO 3166-1 alpha-2 country code. Example: "US". + pub country: Option, + /// Google-generated ID identifying the season linked to the Edit. Only available for TV Edits. Example: 'ster23ex' + #[serde(rename="seasonId")] + pub season_id: Option, + /// Knowledge Graph ID associated to this Edit, if available. This ID links the Edit to its knowledge entity, externally accessible at http://freebase.com. In the absense of Title EIDR or Edit EIDR, this ID helps link together multiple Edits across countries. Example: '/m/0ffx29' + pub mid: Option, + /// Whether the Edit has a 5.1 channel audio track. + #[serde(rename="hasAudio51")] + pub has_audio51: Option, + /// Default Season name, usually in the language of the country of origin. Only available for TV Edits Example: "Googlers, The - A Brave New World". + #[serde(rename="seasonName")] + pub season_name: Option, + /// Audio tracks available for this Edit. + #[serde(rename="audioTracks")] + pub audio_tracks: Option>, + /// Whether the Edit has info cards. + #[serde(rename="hasInfoCards")] + pub has_info_cards: Option, + /// Edit type, like Movie, Episode or Season. + #[serde(rename="type")] + pub type_: Option, + /// Default Show name, usually in the language of the country of origin. Only available for TV Edits Example: "Googlers, The". + #[serde(rename="showName")] + pub show_name: Option, +} + +impl ResponseResult for StoreInfo {} + + +/// Response to the 'ListAvails' 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*). +/// +/// * [avails list accounts](struct.AccountAvailListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ListAvailsResponse { + /// See _List methods rules_ for info about this field. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// List of Avails that match the request criteria. + pub avails: Option>, +} + +impl ResponseResult for ListAvailsResponse {} + + +/// An Order tracks the fulfillment of an Edit when delivered using the legacy, non-component-based delivery. Each Order is uniquely identified by an `order_id`, which is generated by Google. Externally, Orders can also be identified by partners using its `custom_id` (when provided). +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [orders get accounts](struct.AccountOrderGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Order { + /// ID internally generated by Google to uniquely identify an Order. Example: 'abcde12_x' + #[serde(rename="orderId")] + pub order_id: Option, + /// High-level status of the order. + pub status: Option, + /// YouTube Channel ID that should be used to fulfill the Order. Example: "UCRG64darCZhb". + #[serde(rename="channelId")] + pub channel_id: Option, + /// Name of the studio that owns the Edit ordered. + #[serde(rename="studioName")] + pub studio_name: Option, + /// Detailed status of the order + #[serde(rename="statusDetail")] + pub status_detail: Option, + /// Field explaining why an Order has been rejected. Example: "Trailer audio is 2ch mono, please re-deliver in stereo". + #[serde(rename="rejectionNote")] + pub rejection_note: Option, + /// Timestamp when the Order was approved. + #[serde(rename="approvedTime")] + pub approved_time: Option, + /// Google-generated ID identifying the video linked to this Order, once delivered. Example: 'gtry456_xc'. + #[serde(rename="videoId")] + pub video_id: Option, + /// Default Episode name, usually in the language of the country of origin. Only available for TV Edits Example: "Googlers, The - Pilot". + #[serde(rename="episodeName")] + pub episode_name: Option, + /// Default Edit name, usually in the language of the country of origin. Example: "Googlers, The". + pub name: Option, + /// Default Season name, usually in the language of the country of origin. Only available for TV Edits Example: "Googlers, The - A Brave New World". + #[serde(rename="seasonName")] + pub season_name: Option, + /// Timestamp of the earliest start date of the Avails linked to this Order. + #[serde(rename="earliestAvailStartTime")] + pub earliest_avail_start_time: Option, + /// Countries where the Order is available, using the "ISO 3166-1 alpha-2" format (example: "US"). + pub countries: Option>, + /// A simpler representation of the priority. + #[serde(rename="normalizedPriority")] + pub normalized_priority: Option, + /// Timestamp when the Order was fulfilled. + #[serde(rename="receivedTime")] + pub received_time: Option, + /// Timestamp when the Order was created. + #[serde(rename="orderedTime")] + pub ordered_time: Option, + /// Name of the post-production house that manages the Edit ordered. + #[serde(rename="pphName")] + pub pph_name: Option, + /// Order priority, as defined by Google. The higher the value, the higher the priority. Example: 90 + pub priority: Option, + /// Legacy Order priority, as defined by Google. Example: 'P0' + #[serde(rename="legacyPriority")] + pub legacy_priority: Option, + /// ID that can be used to externally identify an Order. This ID is provided by partners when submitting the Avails. Example: 'GOOGLER_2006' + #[serde(rename="customId")] + pub custom_id: Option, + /// YouTube Channel Name that should be used to fulfill the Order. Example: "Google_channel". + #[serde(rename="channelName")] + pub channel_name: Option, + /// Type of the Edit linked to the Order. + #[serde(rename="type")] + pub type_: Option, + /// Default Show name, usually in the language of the country of origin. Only available for TV Edits Example: "Googlers, The". + #[serde(rename="showName")] + pub show_name: Option, +} + +impl ResponseResult for Order {} + + + +// ################### +// MethodBuilders ### +// ################# + +/// A builder providing access to all methods supported on *account* resources. +/// It is not used directly, but through the `Playmoviespartner` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate yup_oauth2 as oauth2; +/// extern crate google_playmoviespartner1 as playmoviespartner1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use playmoviespartner1::Playmoviespartner; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Playmoviespartner::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `avails_list(...)`, `experience_locales_get(...)`, `experience_locales_list(...)`, `orders_get(...)`, `orders_list(...)`, `store_infos_country_get(...)` and `store_infos_list(...)` +/// // to build up your call. +/// let rb = hub.accounts(); +/// # } +/// ``` +pub struct AccountMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Playmoviespartner, +} + +impl<'a, C, A> MethodsBuilder for AccountMethods<'a, C, A> {} + +impl<'a, C, A> AccountMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// List Orders owned or managed by the partner. See _Authentication and Authorization rules_ and _List methods rules_ for more information about this method. + /// + /// # Arguments + /// + /// * `accountId` - REQUIRED. See _General rules_ for more information about this field. + pub fn orders_list(&self, account_id: &str) -> AccountOrderListCall<'a, C, A> { + AccountOrderListCall { + hub: self.hub, + _account_id: account_id.to_string(), + _studio_names: Default::default(), + _status: Default::default(), + _pph_names: Default::default(), + _page_token: Default::default(), + _page_size: Default::default(), + _name: Default::default(), + _custom_id: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Get a StoreInfo given its video id and country. See _Authentication and Authorization rules_ and _Get methods rules_ for more information about this method. + /// + /// # Arguments + /// + /// * `accountId` - REQUIRED. See _General rules_ for more information about this field. + /// * `videoId` - REQUIRED. Video ID. + /// * `country` - REQUIRED. Edit country. + pub fn store_infos_country_get(&self, account_id: &str, video_id: &str, country: &str) -> AccountStoreInfoCountryGetCall<'a, C, A> { + AccountStoreInfoCountryGetCall { + hub: self.hub, + _account_id: account_id.to_string(), + _video_id: video_id.to_string(), + _country: country.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Get an Order given its id. See _Authentication and Authorization rules_ and _Get methods rules_ for more information about this method. + /// + /// # Arguments + /// + /// * `accountId` - REQUIRED. See _General rules_ for more information about this field. + /// * `orderId` - REQUIRED. Order ID. + pub fn orders_get(&self, account_id: &str, order_id: &str) -> AccountOrderGetCall<'a, C, A> { + AccountOrderGetCall { + hub: self.hub, + _account_id: account_id.to_string(), + _order_id: order_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// List Avails owned or managed by the partner. See _Authentication and Authorization rules_ and _List methods rules_ for more information about this method. + /// + /// # Arguments + /// + /// * `accountId` - REQUIRED. See _General rules_ for more information about this field. + pub fn avails_list(&self, account_id: &str) -> AccountAvailListCall<'a, C, A> { + AccountAvailListCall { + hub: self.hub, + _account_id: account_id.to_string(), + _video_ids: Default::default(), + _title: Default::default(), + _territories: Default::default(), + _studio_names: Default::default(), + _pph_names: Default::default(), + _page_token: Default::default(), + _page_size: Default::default(), + _alt_id: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Get an ExperienceLocale given its id. See _Authentication and Authorization rules_ and _Get methods rules_ for more information about this method. + /// + /// # Arguments + /// + /// * `accountId` - REQUIRED. See _General rules_ for more information about this field. + /// * `elId` - REQUIRED. ExperienceLocale ID, as defined by Google. + pub fn experience_locales_get(&self, account_id: &str, el_id: &str) -> AccountExperienceLocaleGetCall<'a, C, A> { + AccountExperienceLocaleGetCall { + hub: self.hub, + _account_id: account_id.to_string(), + _el_id: el_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// List StoreInfos owned or managed by the partner. See _Authentication and Authorization rules_ and _List methods rules_ for more information about this method. + /// + /// # Arguments + /// + /// * `accountId` - REQUIRED. See _General rules_ for more information about this field. + pub fn store_infos_list(&self, account_id: &str) -> AccountStoreInfoListCall<'a, C, A> { + AccountStoreInfoListCall { + hub: self.hub, + _account_id: account_id.to_string(), + _video_ids: Default::default(), + _video_id: Default::default(), + _studio_names: Default::default(), + _pph_names: Default::default(), + _page_token: Default::default(), + _page_size: Default::default(), + _name: Default::default(), + _countries: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// List ExperienceLocales owned or managed by the partner. See _Authentication and Authorization rules_ and _List methods rules_ for more information about this method. + /// + /// # Arguments + /// + /// * `accountId` - REQUIRED. See _General rules_ for more information about this field. + pub fn experience_locales_list(&self, account_id: &str) -> AccountExperienceLocaleListCall<'a, C, A> { + AccountExperienceLocaleListCall { + hub: self.hub, + _account_id: account_id.to_string(), + _title_level_eidr: Default::default(), + _studio_names: Default::default(), + _status: Default::default(), + _pph_names: Default::default(), + _page_token: Default::default(), + _page_size: Default::default(), + _edit_level_eidr: Default::default(), + _custom_id: Default::default(), + _alt_cut_id: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + + + +// ################### +// CallBuilders ### +// ################# + +/// List Orders owned or managed by the partner. See _Authentication and Authorization rules_ and _List methods rules_ for more information about this method. +/// +/// A builder for the *orders.list* method supported by a *account* resource. +/// It is not used directly, but through a `AccountMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_playmoviespartner1 as playmoviespartner1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use playmoviespartner1::Playmoviespartner; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Playmoviespartner::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling 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().orders_list("accountId") +/// .add_studio_names("accusam") +/// .add_status("takimata") +/// .add_pph_names("justo") +/// .page_token("amet.") +/// .page_size(-81) +/// .name("labore") +/// .custom_id("sea") +/// .doit(); +/// # } +/// ``` +pub struct AccountOrderListCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Playmoviespartner, + _account_id: String, + _studio_names: Vec, + _status: Vec, + _pph_names: Vec, + _page_token: Option, + _page_size: Option, + _name: Option, + _custom_id: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for AccountOrderListCall<'a, C, A> {} + +impl<'a, C, A> AccountOrderListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ListOrdersResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "playmoviespartner.accounts.orders.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((10 + self._additional_params.len())); + params.push(("accountId", self._account_id.to_string())); + if self._studio_names.len() > 0 { + let mut s = String::new(); + for f in self._studio_names.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("studioNames", s)); + } + 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._pph_names.len() > 0 { + let mut s = String::new(); + for f in self._pph_names.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("pphNames", s)); + } + 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._name { + params.push(("name", value.to_string())); + } + if let Some(value) = self._custom_id { + params.push(("customId", value.to_string())); + } + for &field in ["alt", "accountId", "studioNames", "status", "pphNames", "pageToken", "pageSize", "name", "customId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://playmoviespartner.googleapis.com/v1/accounts/{accountId}/orders".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::PlaymovyPartnerReadonly.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// REQUIRED. See _General rules_ for more information about this field. + /// + /// 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. + pub fn account_id(mut self, new_value: &str) -> AccountOrderListCall<'a, C, A> { + self._account_id = new_value.to_string(); + self + } + /// See _List methods rules_ for info about this field. + /// + /// Append the given value to the *studio names* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + pub fn add_studio_names(mut self, new_value: &str) -> AccountOrderListCall<'a, C, A> { + self._studio_names.push(new_value.to_string()); + self + } + /// Filter Orders that match one of the given status. + /// + /// 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) -> AccountOrderListCall<'a, C, A> { + self._status.push(new_value.to_string()); + self + } + /// See _List methods rules_ for info about this field. + /// + /// Append the given value to the *pph names* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + pub fn add_pph_names(mut self, new_value: &str) -> AccountOrderListCall<'a, C, A> { + self._pph_names.push(new_value.to_string()); + self + } + /// See _List methods rules_ for info about this field. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> AccountOrderListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// See _List methods rules_ for info about this field. + /// + /// Sets the *page size* query property to the given value. + pub fn page_size(mut self, new_value: i32) -> AccountOrderListCall<'a, C, A> { + self._page_size = Some(new_value); + self + } + /// Filter Orders that match a title name (case-insensitive, sub-string match). + /// + /// Sets the *name* query property to the given value. + pub fn name(mut self, new_value: &str) -> AccountOrderListCall<'a, C, A> { + self._name = Some(new_value.to_string()); + self + } + /// Filter Orders that match a case-insensitive, partner-specific custom id. + /// + /// Sets the *custom id* query property to the given value. + pub fn custom_id(mut self, new_value: &str) -> AccountOrderListCall<'a, C, A> { + self._custom_id = Some(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountOrderListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> AccountOrderListCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::PlaymovyPartnerReadonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountOrderListCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Get a StoreInfo given its video id and country. See _Authentication and Authorization rules_ and _Get methods rules_ for more information about this method. +/// +/// A builder for the *storeInfos.country.get* method supported by a *account* resource. +/// It is not used directly, but through a `AccountMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_playmoviespartner1 as playmoviespartner1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use playmoviespartner1::Playmoviespartner; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Playmoviespartner::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling 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().store_infos_country_get("accountId", "videoId", "country") +/// .doit(); +/// # } +/// ``` +pub struct AccountStoreInfoCountryGetCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Playmoviespartner, + _account_id: String, + _video_id: String, + _country: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for AccountStoreInfoCountryGetCall<'a, C, A> {} + +impl<'a, C, A> AccountStoreInfoCountryGetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, StoreInfo)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "playmoviespartner.accounts.storeInfos.country.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(("videoId", self._video_id.to_string())); + params.push(("country", self._country.to_string())); + for &field in ["alt", "accountId", "videoId", "country"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://playmoviespartner.googleapis.com/v1/accounts/{accountId}/storeInfos/{videoId}/country/{country}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::PlaymovyPartnerReadonly.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{videoId}", "videoId"), ("{country}", "country")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + 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 ["country", "videoId", "accountId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// REQUIRED. See _General rules_ for more information about this field. + /// + /// 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. + pub fn account_id(mut self, new_value: &str) -> AccountStoreInfoCountryGetCall<'a, C, A> { + self._account_id = new_value.to_string(); + self + } + /// REQUIRED. Video ID. + /// + /// Sets the *video id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn video_id(mut self, new_value: &str) -> AccountStoreInfoCountryGetCall<'a, C, A> { + self._video_id = new_value.to_string(); + self + } + /// REQUIRED. Edit country. + /// + /// Sets the *country* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn country(mut self, new_value: &str) -> AccountStoreInfoCountryGetCall<'a, C, A> { + self._country = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountStoreInfoCountryGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> AccountStoreInfoCountryGetCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::PlaymovyPartnerReadonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountStoreInfoCountryGetCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Get an Order given its id. See _Authentication and Authorization rules_ and _Get methods rules_ for more information about this method. +/// +/// A builder for the *orders.get* method supported by a *account* resource. +/// It is not used directly, but through a `AccountMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_playmoviespartner1 as playmoviespartner1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use playmoviespartner1::Playmoviespartner; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Playmoviespartner::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling 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().orders_get("accountId", "orderId") +/// .doit(); +/// # } +/// ``` +pub struct AccountOrderGetCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Playmoviespartner, + _account_id: String, + _order_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for AccountOrderGetCall<'a, C, A> {} + +impl<'a, C, A> AccountOrderGetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Order)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "playmoviespartner.accounts.orders.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(("orderId", self._order_id.to_string())); + for &field in ["alt", "accountId", "orderId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://playmoviespartner.googleapis.com/v1/accounts/{accountId}/orders/{orderId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::PlaymovyPartnerReadonly.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{orderId}", "orderId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["orderId", "accountId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// REQUIRED. See _General rules_ for more information about this field. + /// + /// 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. + pub fn account_id(mut self, new_value: &str) -> AccountOrderGetCall<'a, C, A> { + self._account_id = new_value.to_string(); + self + } + /// REQUIRED. Order ID. + /// + /// Sets the *order id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn order_id(mut self, new_value: &str) -> AccountOrderGetCall<'a, C, A> { + self._order_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountOrderGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> AccountOrderGetCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::PlaymovyPartnerReadonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountOrderGetCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// List Avails owned or managed by the partner. See _Authentication and Authorization rules_ and _List methods rules_ for more information about this method. +/// +/// A builder for the *avails.list* method supported by a *account* resource. +/// It is not used directly, but through a `AccountMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_playmoviespartner1 as playmoviespartner1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use playmoviespartner1::Playmoviespartner; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Playmoviespartner::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling 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().avails_list("accountId") +/// .add_video_ids("no") +/// .title("justo") +/// .add_territories("justo") +/// .add_studio_names("et") +/// .add_pph_names("et") +/// .page_token("diam") +/// .page_size(-55) +/// .alt_id("Lorem") +/// .doit(); +/// # } +/// ``` +pub struct AccountAvailListCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Playmoviespartner, + _account_id: String, + _video_ids: Vec, + _title: Option, + _territories: Vec, + _studio_names: Vec, + _pph_names: Vec, + _page_token: Option, + _page_size: Option, + _alt_id: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for AccountAvailListCall<'a, C, A> {} + +impl<'a, C, A> AccountAvailListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ListAvailsResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "playmoviespartner.accounts.avails.list", + 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())); + if self._video_ids.len() > 0 { + let mut s = String::new(); + for f in self._video_ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("videoIds", s)); + } + if let Some(value) = self._title { + params.push(("title", value.to_string())); + } + if self._territories.len() > 0 { + let mut s = String::new(); + for f in self._territories.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("territories", s)); + } + if self._studio_names.len() > 0 { + let mut s = String::new(); + for f in self._studio_names.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("studioNames", s)); + } + if self._pph_names.len() > 0 { + let mut s = String::new(); + for f in self._pph_names.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("pphNames", s)); + } + 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._alt_id { + params.push(("altId", value.to_string())); + } + for &field in ["alt", "accountId", "videoIds", "title", "territories", "studioNames", "pphNames", "pageToken", "pageSize", "altId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://playmoviespartner.googleapis.com/v1/accounts/{accountId}/avails".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::PlaymovyPartnerReadonly.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// REQUIRED. See _General rules_ for more information about this field. + /// + /// 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. + pub fn account_id(mut self, new_value: &str) -> AccountAvailListCall<'a, C, A> { + self._account_id = new_value.to_string(); + self + } + /// Filter Avails that match any of the given `video_id`s. + /// + /// Append the given value to the *video ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + pub fn add_video_ids(mut self, new_value: &str) -> AccountAvailListCall<'a, C, A> { + self._video_ids.push(new_value.to_string()); + self + } + /// Filter Avails that match a case-insensitive substring of the default Title name. + /// + /// Sets the *title* query property to the given value. + pub fn title(mut self, new_value: &str) -> AccountAvailListCall<'a, C, A> { + self._title = Some(new_value.to_string()); + self + } + /// Filter Avails that match (case-insensitive) any of the given country codes, using the "ISO 3166-1 alpha-2" format (examples: "US", "us", "Us"). + /// + /// Append the given value to the *territories* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + pub fn add_territories(mut self, new_value: &str) -> AccountAvailListCall<'a, C, A> { + self._territories.push(new_value.to_string()); + self + } + /// See _List methods rules_ for info about this field. + /// + /// Append the given value to the *studio names* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + pub fn add_studio_names(mut self, new_value: &str) -> AccountAvailListCall<'a, C, A> { + self._studio_names.push(new_value.to_string()); + self + } + /// See _List methods rules_ for info about this field. + /// + /// Append the given value to the *pph names* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + pub fn add_pph_names(mut self, new_value: &str) -> AccountAvailListCall<'a, C, A> { + self._pph_names.push(new_value.to_string()); + self + } + /// See _List methods rules_ for info about this field. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> AccountAvailListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// See _List methods rules_ for info about this field. + /// + /// Sets the *page size* query property to the given value. + pub fn page_size(mut self, new_value: i32) -> AccountAvailListCall<'a, C, A> { + self._page_size = Some(new_value); + self + } + /// Filter Avails that match a case-insensitive, partner-specific custom id. + /// + /// Sets the *alt id* query property to the given value. + pub fn alt_id(mut self, new_value: &str) -> AccountAvailListCall<'a, C, A> { + self._alt_id = Some(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountAvailListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> AccountAvailListCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::PlaymovyPartnerReadonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountAvailListCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Get an ExperienceLocale given its id. See _Authentication and Authorization rules_ and _Get methods rules_ for more information about this method. +/// +/// A builder for the *experienceLocales.get* method supported by a *account* resource. +/// It is not used directly, but through a `AccountMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_playmoviespartner1 as playmoviespartner1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use playmoviespartner1::Playmoviespartner; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Playmoviespartner::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling 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().experience_locales_get("accountId", "elId") +/// .doit(); +/// # } +/// ``` +pub struct AccountExperienceLocaleGetCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Playmoviespartner, + _account_id: String, + _el_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for AccountExperienceLocaleGetCall<'a, C, A> {} + +impl<'a, C, A> AccountExperienceLocaleGetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ExperienceLocale)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "playmoviespartner.accounts.experienceLocales.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(("elId", self._el_id.to_string())); + for &field in ["alt", "accountId", "elId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://playmoviespartner.googleapis.com/v1/accounts/{accountId}/experienceLocales/{elId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::PlaymovyPartnerReadonly.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{elId}", "elId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["elId", "accountId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// REQUIRED. See _General rules_ for more information about this field. + /// + /// 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. + pub fn account_id(mut self, new_value: &str) -> AccountExperienceLocaleGetCall<'a, C, A> { + self._account_id = new_value.to_string(); + self + } + /// REQUIRED. ExperienceLocale ID, as defined by Google. + /// + /// Sets the *el id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn el_id(mut self, new_value: &str) -> AccountExperienceLocaleGetCall<'a, C, A> { + self._el_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountExperienceLocaleGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> AccountExperienceLocaleGetCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::PlaymovyPartnerReadonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountExperienceLocaleGetCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// List StoreInfos owned or managed by the partner. See _Authentication and Authorization rules_ and _List methods rules_ for more information about this method. +/// +/// A builder for the *storeInfos.list* method supported by a *account* resource. +/// It is not used directly, but through a `AccountMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_playmoviespartner1 as playmoviespartner1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use playmoviespartner1::Playmoviespartner; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Playmoviespartner::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling 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().store_infos_list("accountId") +/// .add_video_ids("sea") +/// .video_id("Lorem") +/// .add_studio_names("eos") +/// .add_pph_names("erat") +/// .page_token("sadipscing") +/// .page_size(-48) +/// .name("eirmod") +/// .add_countries("elitr") +/// .doit(); +/// # } +/// ``` +pub struct AccountStoreInfoListCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Playmoviespartner, + _account_id: String, + _video_ids: Vec, + _video_id: Option, + _studio_names: Vec, + _pph_names: Vec, + _page_token: Option, + _page_size: Option, + _name: Option, + _countries: Vec, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for AccountStoreInfoListCall<'a, C, A> {} + +impl<'a, C, A> AccountStoreInfoListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ListStoreInfosResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "playmoviespartner.accounts.storeInfos.list", + 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())); + if self._video_ids.len() > 0 { + let mut s = String::new(); + for f in self._video_ids.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("videoIds", s)); + } + if let Some(value) = self._video_id { + params.push(("videoId", value.to_string())); + } + if self._studio_names.len() > 0 { + let mut s = String::new(); + for f in self._studio_names.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("studioNames", s)); + } + if self._pph_names.len() > 0 { + let mut s = String::new(); + for f in self._pph_names.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("pphNames", s)); + } + 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._name { + params.push(("name", value.to_string())); + } + if self._countries.len() > 0 { + let mut s = String::new(); + for f in self._countries.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("countries", s)); + } + for &field in ["alt", "accountId", "videoIds", "videoId", "studioNames", "pphNames", "pageToken", "pageSize", "name", "countries"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://playmoviespartner.googleapis.com/v1/accounts/{accountId}/storeInfos".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::PlaymovyPartnerReadonly.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// REQUIRED. See _General rules_ for more information about this field. + /// + /// 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. + pub fn account_id(mut self, new_value: &str) -> AccountStoreInfoListCall<'a, C, A> { + self._account_id = new_value.to_string(); + self + } + /// Filter StoreInfos that match any of the given `video_id`s. + /// + /// Append the given value to the *video ids* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + pub fn add_video_ids(mut self, new_value: &str) -> AccountStoreInfoListCall<'a, C, A> { + self._video_ids.push(new_value.to_string()); + self + } + /// Filter StoreInfos that match a given `video_id`. NOTE: this field is deprecated and will be removed on V2; `video_ids` should be used instead. + /// + /// Sets the *video id* query property to the given value. + pub fn video_id(mut self, new_value: &str) -> AccountStoreInfoListCall<'a, C, A> { + self._video_id = Some(new_value.to_string()); + self + } + /// See _List methods rules_ for info about this field. + /// + /// Append the given value to the *studio names* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + pub fn add_studio_names(mut self, new_value: &str) -> AccountStoreInfoListCall<'a, C, A> { + self._studio_names.push(new_value.to_string()); + self + } + /// See _List methods rules_ for info about this field. + /// + /// Append the given value to the *pph names* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + pub fn add_pph_names(mut self, new_value: &str) -> AccountStoreInfoListCall<'a, C, A> { + self._pph_names.push(new_value.to_string()); + self + } + /// See _List methods rules_ for info about this field. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> AccountStoreInfoListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// See _List methods rules_ for info about this field. + /// + /// Sets the *page size* query property to the given value. + pub fn page_size(mut self, new_value: i32) -> AccountStoreInfoListCall<'a, C, A> { + self._page_size = Some(new_value); + self + } + /// Filter StoreInfos that match a case-insensitive substring of the default name. + /// + /// Sets the *name* query property to the given value. + pub fn name(mut self, new_value: &str) -> AccountStoreInfoListCall<'a, C, A> { + self._name = Some(new_value.to_string()); + self + } + /// Filter StoreInfos that match (case-insensitive) any of the given country codes, using the "ISO 3166-1 alpha-2" format (examples: "US", "us", "Us"). + /// + /// Append the given value to the *countries* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + pub fn add_countries(mut self, new_value: &str) -> AccountStoreInfoListCall<'a, C, A> { + self._countries.push(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountStoreInfoListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> AccountStoreInfoListCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::PlaymovyPartnerReadonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountStoreInfoListCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// List ExperienceLocales owned or managed by the partner. See _Authentication and Authorization rules_ and _List methods rules_ for more information about this method. +/// +/// A builder for the *experienceLocales.list* method supported by a *account* resource. +/// It is not used directly, but through a `AccountMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_playmoviespartner1 as playmoviespartner1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use playmoviespartner1::Playmoviespartner; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Playmoviespartner::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling 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().experience_locales_list("accountId") +/// .title_level_eidr("no") +/// .add_studio_names("labore") +/// .add_status("eirmod") +/// .add_pph_names("dolore") +/// .page_token("invidunt") +/// .page_size(-82) +/// .edit_level_eidr("accusam") +/// .custom_id("Lorem") +/// .alt_cut_id("sea") +/// .doit(); +/// # } +/// ``` +pub struct AccountExperienceLocaleListCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Playmoviespartner, + _account_id: String, + _title_level_eidr: Option, + _studio_names: Vec, + _status: Vec, + _pph_names: Vec, + _page_token: Option, + _page_size: Option, + _edit_level_eidr: Option, + _custom_id: Option, + _alt_cut_id: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for AccountExperienceLocaleListCall<'a, C, A> {} + +impl<'a, C, A> AccountExperienceLocaleListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ListExperienceLocalesResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "playmoviespartner.accounts.experienceLocales.list", + 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())); + if let Some(value) = self._title_level_eidr { + params.push(("titleLevelEidr", value.to_string())); + } + if self._studio_names.len() > 0 { + let mut s = String::new(); + for f in self._studio_names.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("studioNames", s)); + } + 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._pph_names.len() > 0 { + let mut s = String::new(); + for f in self._pph_names.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("pphNames", s)); + } + 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._edit_level_eidr { + params.push(("editLevelEidr", value.to_string())); + } + if let Some(value) = self._custom_id { + params.push(("customId", value.to_string())); + } + if let Some(value) = self._alt_cut_id { + params.push(("altCutId", value.to_string())); + } + for &field in ["alt", "accountId", "titleLevelEidr", "studioNames", "status", "pphNames", "pageToken", "pageSize", "editLevelEidr", "customId", "altCutId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://playmoviespartner.googleapis.com/v1/accounts/{accountId}/experienceLocales".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::PlaymovyPartnerReadonly.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// REQUIRED. See _General rules_ for more information about this field. + /// + /// 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. + pub fn account_id(mut self, new_value: &str) -> AccountExperienceLocaleListCall<'a, C, A> { + self._account_id = new_value.to_string(); + self + } + /// Filter ExperienceLocales that match a given title-level EIDR. + /// + /// Sets the *title level eidr* query property to the given value. + pub fn title_level_eidr(mut self, new_value: &str) -> AccountExperienceLocaleListCall<'a, C, A> { + self._title_level_eidr = Some(new_value.to_string()); + self + } + /// See _List methods rules_ for info about this field. + /// + /// Append the given value to the *studio names* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + pub fn add_studio_names(mut self, new_value: &str) -> AccountExperienceLocaleListCall<'a, C, A> { + self._studio_names.push(new_value.to_string()); + self + } + /// Filter ExperienceLocales that match one of the given status. + /// + /// 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) -> AccountExperienceLocaleListCall<'a, C, A> { + self._status.push(new_value.to_string()); + self + } + /// See _List methods rules_ for info about this field. + /// + /// Append the given value to the *pph names* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + pub fn add_pph_names(mut self, new_value: &str) -> AccountExperienceLocaleListCall<'a, C, A> { + self._pph_names.push(new_value.to_string()); + self + } + /// See _List methods rules_ for info about this field. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> AccountExperienceLocaleListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// See _List methods rules_ for info about this field. + /// + /// Sets the *page size* query property to the given value. + pub fn page_size(mut self, new_value: i32) -> AccountExperienceLocaleListCall<'a, C, A> { + self._page_size = Some(new_value); + self + } + /// Filter ExperienceLocales that match a given edit-level EIDR. + /// + /// Sets the *edit level eidr* query property to the given value. + pub fn edit_level_eidr(mut self, new_value: &str) -> AccountExperienceLocaleListCall<'a, C, A> { + self._edit_level_eidr = Some(new_value.to_string()); + self + } + /// Filter ExperienceLocales that match a case-insensitive, partner-specific custom id. + /// + /// Sets the *custom id* query property to the given value. + pub fn custom_id(mut self, new_value: &str) -> AccountExperienceLocaleListCall<'a, C, A> { + self._custom_id = Some(new_value.to_string()); + self + } + /// Filter ExperienceLocales that match a case-insensitive, partner-specific Alternative Cut ID. + /// + /// Sets the *alt cut id* query property to the given value. + pub fn alt_cut_id(mut self, new_value: &str) -> AccountExperienceLocaleListCall<'a, C, A> { + self._alt_cut_id = Some(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountExperienceLocaleListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> AccountExperienceLocaleListCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::PlaymovyPartnerReadonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountExperienceLocaleListCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + diff --git a/gen/plus1-cli/Cargo.toml b/gen/plus1-cli/Cargo.toml index 84b99e400a..6e88b34a0f 100644 --- a/gen/plus1-cli/Cargo.toml +++ b/gen/plus1-cli/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-plus1-cli" -version = "0.3.2+20150719" +version = "0.3.2+20151014" authors = ["Sebastian Thiel "] description = "A complete library to interact with plus (protocol v1)" repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/plus1-cli" diff --git a/gen/plus1-cli/README.md b/gen/plus1-cli/README.md index 29b834356d..414d431f8b 100644 --- a/gen/plus1-cli/README.md +++ b/gen/plus1-cli/README.md @@ -24,7 +24,7 @@ Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/ma # Usage -This documentation was generated from the *plus* API at revision *20150719*. The CLI is at version *0.3.2*. +This documentation was generated from the *plus* API at revision *20151014*. The CLI is at version *0.3.2*. ```bash plus1 [options] @@ -38,7 +38,6 @@ plus1 [options] moments insert (-r )... [-p ]... [-o ] list [-p ]... [-o ] - remove [-p ]... people get [-p ]... [-o ] list [-p ]... [-o ] diff --git a/gen/plus1-cli/mkdocs.yml b/gen/plus1-cli/mkdocs.yml index e994a185cc..40b90ad0e1 100644 --- a/gen/plus1-cli/mkdocs.yml +++ b/gen/plus1-cli/mkdocs.yml @@ -1,4 +1,4 @@ -site_name: plus v0.3.2+20150719 +site_name: plus v0.3.2+20151014 site_url: http://byron.github.io/google-apis-rs/google-plus1-cli site_description: Write integrating applications with bcore @@ -16,7 +16,6 @@ pages: - ['comments_list.md', 'Comments', 'List'] - ['moments_insert.md', 'Moments', 'Insert'] - ['moments_list.md', 'Moments', 'List'] -- ['moments_remove.md', 'Moments', 'Remove'] - ['people_get.md', 'People', 'Get'] - ['people_list.md', 'People', 'List'] - ['people_list-by-activity.md', 'People', 'List By Activity'] diff --git a/gen/plus1-cli/src/main.rs b/gen/plus1-cli/src/main.rs index c1ac81360e..1c57804573 100644 --- a/gen/plus1-cli/src/main.rs +++ b/gen/plus1-cli/src/main.rs @@ -612,50 +612,6 @@ impl<'n, 'a> Engine<'n, 'a> { } } - fn _moments_remove(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) - -> Result<(), DoitError> { - let mut call = self.hub.moments().remove(opt.value_of("id").unwrap_or("")); - for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { - let (key, value) = parse_kv_arg(&*parg, err, false); - match key { - _ => { - let mut found = false; - for param in &self.gp { - if key == *param { - found = true; - call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); - break; - } - } - if !found { - err.issues.push(CLIError::UnknownParameter(key.to_string(), - {let mut v = Vec::new(); - v.extend(self.gp.iter().map(|v|*v)); - v } )); - } - } - } - } - let protocol = CallType::Standard; - if dry_run { - Ok(()) - } else { - assert!(err.issues.len() == 0); - for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { - call = call.add_scope(scope); - } - match match protocol { - CallType::Standard => call.doit(), - _ => unreachable!() - } { - Err(api_err) => Err(DoitError::ApiError(api_err)), - Ok(mut response) => { - Ok(()) - } - } - } - } - fn _people_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) -> Result<(), DoitError> { let mut call = self.hub.people().get(opt.value_of("user-id").unwrap_or("")); @@ -935,9 +891,6 @@ impl<'n, 'a> Engine<'n, 'a> { ("list", Some(opt)) => { call_result = self._moments_list(opt, dry_run, &mut err); }, - ("remove", Some(opt)) => { - call_result = self._moments_remove(opt, dry_run, &mut err); - }, _ => { err.issues.push(CLIError::MissingMethodError("moments".to_string())); writeln!(io::stderr(), "{}\n", opt.usage()).ok(); @@ -1168,7 +1121,7 @@ fn main() { ]), ]), - ("moments", "methods: 'insert', 'list' and 'remove'", vec![ + ("moments", "methods: 'insert' and 'list'", vec![ ("insert", Some(r##"Record a moment representing a user's action such as making a purchase or commenting on a blog."##), "Details at http://byron.github.io/google-apis-rs/google_plus1_cli/moments_insert", @@ -1231,22 +1184,6 @@ fn main() { Some(false), Some(false)), ]), - ("remove", - Some(r##"Delete a moment."##), - "Details at http://byron.github.io/google-apis-rs/google_plus1_cli/moments_remove", - vec![ - (Some(r##"id"##), - None, - Some(r##"The ID of the moment to delete."##), - Some(true), - Some(false)), - - (Some(r##"v"##), - Some(r##"p"##), - Some(r##"Set various optional parameters, matching the key=value form"##), - Some(false), - Some(true)), - ]), ]), ("people", "methods: 'get', 'list', 'list-by-activity' and 'search'", vec![ @@ -1356,7 +1293,7 @@ fn main() { let mut app = App::new("plus1") .author("Sebastian Thiel ") - .version("0.3.2+20150719") + .version("0.3.2+20151014") .about("The Google+ API enables developers to build on top of the Google+ platform.") .after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_plus1_cli") .arg(Arg::with_name("url") diff --git a/gen/plus1/Cargo.toml b/gen/plus1/Cargo.toml index bd4b5601d0..5c45a5b204 100644 --- a/gen/plus1/Cargo.toml +++ b/gen/plus1/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-plus1" -version = "0.1.9+20150719" +version = "0.1.9+20151014" authors = ["Sebastian Thiel "] description = "A complete library to interact with plus (protocol v1)" repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/plus1" diff --git a/gen/plus1/README.md b/gen/plus1/README.md index c5339f5090..f200840d68 100644 --- a/gen/plus1/README.md +++ b/gen/plus1/README.md @@ -5,7 +5,7 @@ DO NOT EDIT ! --> The `google-plus1` library allows access to all features of the *Google plus* service. -This documentation was generated from *plus* crate version *0.1.9+20150719*, where *20150719* is the exact revision of the *plus:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +This documentation was generated from *plus* crate version *0.1.9+20151014*, where *20151014* is the exact revision of the *plus:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. Everything else about the *plus* *v1* API can be found at the [official documentation site](https://developers.google.com/+/api/). @@ -18,7 +18,7 @@ Handle the following *Resources* with ease from the central [hub](http://byron.g * [comments](http://byron.github.io/google-apis-rs/google_plus1/struct.Comment.html) * [*get*](http://byron.github.io/google-apis-rs/google_plus1/struct.CommentGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google_plus1/struct.CommentListCall.html) * [moments](http://byron.github.io/google-apis-rs/google_plus1/struct.Moment.html) - * [*insert*](http://byron.github.io/google-apis-rs/google_plus1/struct.MomentInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google_plus1/struct.MomentListCall.html) and [*remove*](http://byron.github.io/google-apis-rs/google_plus1/struct.MomentRemoveCall.html) + * [*insert*](http://byron.github.io/google-apis-rs/google_plus1/struct.MomentInsertCall.html) and [*list*](http://byron.github.io/google-apis-rs/google_plus1/struct.MomentListCall.html) * people * [*get*](http://byron.github.io/google-apis-rs/google_plus1/struct.PeopleGetCall.html), [*list*](http://byron.github.io/google-apis-rs/google_plus1/struct.PeopleListCall.html), [*list by activity*](http://byron.github.io/google-apis-rs/google_plus1/struct.PeopleListByActivityCall.html) and [*search*](http://byron.github.io/google-apis-rs/google_plus1/struct.PeopleSearchCall.html) diff --git a/gen/plus1/src/lib.rs b/gen/plus1/src/lib.rs index feb9756a54..ddf3384490 100644 --- a/gen/plus1/src/lib.rs +++ b/gen/plus1/src/lib.rs @@ -2,7 +2,7 @@ // This file was generated automatically from 'src/mako/api/lib.rs.mako' // DO NOT EDIT ! -//! This documentation was generated from *plus* crate version *0.1.9+20150719*, where *20150719* is the exact revision of the *plus:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +//! This documentation was generated from *plus* crate version *0.1.9+20151014*, where *20151014* is the exact revision of the *plus:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. //! //! Everything else about the *plus* *v1* API can be found at the //! [official documentation site](https://developers.google.com/+/api/). @@ -16,7 +16,7 @@ //! * [comments](struct.Comment.html) //! * [*get*](struct.CommentGetCall.html) and [*list*](struct.CommentListCall.html) //! * [moments](struct.Moment.html) -//! * [*insert*](struct.MomentInsertCall.html), [*list*](struct.MomentListCall.html) and [*remove*](struct.MomentRemoveCall.html) +//! * [*insert*](struct.MomentInsertCall.html) and [*list*](struct.MomentListCall.html) //! * people //! * [*get*](struct.PeopleGetCall.html), [*list*](struct.PeopleListCall.html), [*list by activity*](struct.PeopleListByActivityCall.html) and [*search*](struct.PeopleSearchCall.html) //! @@ -102,9 +102,9 @@ //! // execute the final call using `doit()`. //! // Values shown here are possibly random and not representative ! //! let result = hub.people().list("userId", "collection") -//! .page_token("et") -//! .order_by("eirmod") -//! .max_results(43) +//! .page_token("duo") +//! .order_by("et") +//! .max_results(61) //! .doit(); //! //! match result { diff --git a/gen/plus1/src/lib.rs.in b/gen/plus1/src/lib.rs.in index cb6f2d050a..a6b9bbab6a 100644 --- a/gen/plus1/src/lib.rs.in +++ b/gen/plus1/src/lib.rs.in @@ -326,22 +326,110 @@ impl NestedType for PersonOrganizations {} impl Part for PersonOrganizations {} -/// Comments in reply to this activity. +/// 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 activities](struct.ActivityGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Activity { + /// Name of the place where this activity occurred. + #[serde(rename="placeName")] + pub place_name: Option, + /// The time at which this activity was last updated. Formatted as an RFC 3339 timestamp. + pub updated: Option, + /// The object of this activity. + pub object: Option, + /// This activity's verb, which indicates the action that was performed. Possible values include, but are not limited to, the following values: + /// - "post" - Publish content to the stream. + /// - "share" - Reshare an activity. + pub verb: Option, + /// Radius, in meters, of the region where this activity occurred, centered at the latitude and longitude identified in geocode. + pub radius: Option, + /// ETag of this response for caching purposes. + pub etag: Option, + /// Street address where this activity occurred. + pub address: Option, + /// Additional content added by the person who shared this activity, applicable only when resharing an activity. + pub annotation: Option, + /// Identifies this resource as an activity. Value: "plus#activity". + pub kind: Option, + /// Title of this activity. + pub title: Option, + /// The link to this activity. + pub url: Option, + /// ID of the place where this activity occurred. + #[serde(rename="placeId")] + pub place_id: Option, + /// The person who performed this activity. + pub actor: Option, + /// The ID of this activity. + pub id: Option, + /// Identifies who has access to see this activity. + pub access: Option, + /// Latitude and longitude where this activity occurred. Format is latitude followed by longitude, space separated. + pub geocode: Option, + /// The location where this activity occurred. + pub location: Option, + /// The service provider that initially published this activity. + pub provider: Option, + /// If this activity is a crosspost from another system, this property specifies the ID of the original activity. + #[serde(rename="crosspostSource")] + pub crosspost_source: Option, + /// The time at which this activity was initially published. Formatted as an RFC 3339 timestamp. + pub published: Option, +} + +impl ResponseResult for Activity {} + + +/// Actor info specific to YouTube clients. /// /// This type is not used in any activity, and only used as *part* of another schema. /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] -pub struct ActivityObjectReplies { - /// Total number of comments on this activity. - #[serde(rename="totalItems")] - pub total_items: Option, - /// The URL for the collection of comments in reply to this activity. - #[serde(rename="selfLink")] - pub self_link: Option, +pub struct ActivityActorClientSpecificActorInfoYoutubeActorInfo { + /// ID of the YouTube channel owned by the Actor. + #[serde(rename="channelId")] + pub channel_id: Option, } -impl NestedType for ActivityObjectReplies {} -impl Part for ActivityObjectReplies {} +impl NestedType for ActivityActorClientSpecificActorInfoYoutubeActorInfo {} +impl Part for ActivityActorClientSpecificActorInfoYoutubeActorInfo {} + + +/// Actor info specific to particular clients. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ActivityActorClientSpecificActorInfo { + /// Actor info specific to YouTube clients. + #[serde(rename="youtubeActorInfo")] + pub youtube_actor_info: Option, +} + +impl NestedType for ActivityActorClientSpecificActorInfo {} +impl Part for ActivityActorClientSpecificActorInfo {} + + +/// Verification status of actor. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ActivityActorVerification { + /// Verification for one-time or manual processes. + #[serde(rename="adHocVerified")] + pub ad_hoc_verified: Option, +} + +impl NestedType for ActivityActorVerification {} +impl Part for ActivityActorVerification {} /// If the attachment is a video, the embeddable link. @@ -652,13 +740,18 @@ impl ResponseResult for PeopleFeed {} /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct CommentActor { + /// The name of this actor, suitable for display. + #[serde(rename="displayName")] + pub display_name: Option, + /// Verification status of actor. + pub verification: Option, /// A link to the Person resource for this actor. pub url: Option, /// The image representation of this actor. pub image: Option, - /// The name of this actor, suitable for display. - #[serde(rename="displayName")] - pub display_name: Option, + /// Actor info specific to particular clients. + #[serde(rename="clientSpecificActorInfo")] + pub client_specific_actor_info: Option, /// The ID of the actor. pub id: Option, } @@ -667,23 +760,43 @@ impl NestedType for CommentActor {} impl Part for CommentActor {} +/// Actor info specific to YouTube clients. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ActivityObjectActorClientSpecificActorInfoYoutubeActorInfo { + /// ID of the YouTube channel owned by the Actor. + #[serde(rename="channelId")] + pub channel_id: Option, +} + +impl NestedType for ActivityObjectActorClientSpecificActorInfoYoutubeActorInfo {} +impl Part for ActivityObjectActorClientSpecificActorInfoYoutubeActorInfo {} + + /// The person who performed this 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 ActivityActor { + /// The name of the actor, suitable for display. + #[serde(rename="displayName")] + pub display_name: Option, + /// An object representation of the individual components of name. + pub name: Option, /// The link to the actor's Google profile. pub url: Option, /// The image representation of the actor. pub image: Option, - /// The name of the actor, suitable for display. - #[serde(rename="displayName")] - pub display_name: Option, + /// Actor info specific to particular clients. + #[serde(rename="clientSpecificActorInfo")] + pub client_specific_actor_info: Option, /// The ID of the actor's Person resource. pub id: Option, - /// An object representation of the individual components of name. - pub name: Option, + /// Verification status of actor. + pub verification: Option, } impl NestedType for ActivityActor {} @@ -704,6 +817,21 @@ impl NestedType for ActivityProvider {} impl Part for ActivityProvider {} +/// Actor info specific to particular clients. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct CommentActorClientSpecificActorInfo { + /// Actor info specific to YouTube clients. + #[serde(rename="youtubeActorInfo")] + pub youtube_actor_info: Option, +} + +impl NestedType for CommentActorClientSpecificActorInfo {} +impl Part for CommentActorClientSpecificActorInfo {} + + /// The position of the place. /// /// This type is not used in any activity, and only used as *part* of another schema. @@ -765,7 +893,6 @@ impl Part for PersonCoverCoverInfo {} /// /// * [list moments](struct.MomentListCall.html) (none) /// * [insert moments](struct.MomentInsertCall.html) (request|response) -/// * [remove moments](struct.MomentRemoveCall.html) (none) /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct Moment { @@ -893,6 +1020,21 @@ impl NestedType for PersonCoverCoverPhoto {} impl Part for PersonCoverCoverPhoto {} +/// Verification status of actor. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ActivityObjectActorVerification { + /// Verification for one-time or manual processes. + #[serde(rename="adHocVerified")] + pub ad_hoc_verified: Option, +} + +impl NestedType for ActivityObjectActorVerification {} +impl Part for ActivityObjectActorVerification {} + + /// The full image URL for photo attachments. /// /// This type is not used in any activity, and only used as *part* of another schema. @@ -1059,13 +1201,18 @@ impl ResponseResult for Person {} /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct ActivityObjectActor { + /// The original actor's name, which is suitable for display. + #[serde(rename="displayName")] + pub display_name: Option, + /// Verification status of actor. + pub verification: Option, /// A link to the original actor's Google profile. pub url: Option, /// The image representation of the original actor. pub image: Option, - /// The original actor's name, which is suitable for display. - #[serde(rename="displayName")] - pub display_name: Option, + /// Actor info specific to particular clients. + #[serde(rename="clientSpecificActorInfo")] + pub client_specific_actor_info: Option, /// ID of the original actor. pub id: Option, } @@ -1074,6 +1221,21 @@ impl NestedType for ActivityObjectActor {} impl Part for ActivityObjectActor {} +/// Actor info specific to YouTube clients. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct CommentActorClientSpecificActorInfoYoutubeActorInfo { + /// ID of the YouTube channel owned by the Actor. + #[serde(rename="channelId")] + pub channel_id: Option, +} + +impl NestedType for CommentActorClientSpecificActorInfoYoutubeActorInfo {} +impl Part for CommentActorClientSpecificActorInfoYoutubeActorInfo {} + + /// There is no detailed description. /// /// # Activities @@ -1109,65 +1271,19 @@ pub struct MomentsFeed { impl ResponseResult for MomentsFeed {} -/// There is no detailed description. +/// Verification status of actor. /// -/// # Activities -/// -/// This type is used in activities, which are methods you may call on this type or where 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 activities](struct.ActivityGetCall.html) (response) +/// This type is not used in any activity, and only used as *part* of another schema. /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] -pub struct Activity { - /// Name of the place where this activity occurred. - #[serde(rename="placeName")] - pub place_name: Option, - /// The time at which this activity was last updated. Formatted as an RFC 3339 timestamp. - pub updated: Option, - /// The object of this activity. - pub object: Option, - /// This activity's verb, which indicates the action that was performed. Possible values include, but are not limited to, the following values: - /// - "post" - Publish content to the stream. - /// - "share" - Reshare an activity. - pub verb: Option, - /// Radius, in meters, of the region where this activity occurred, centered at the latitude and longitude identified in geocode. - pub radius: Option, - /// ETag of this response for caching purposes. - pub etag: Option, - /// Street address where this activity occurred. - pub address: Option, - /// Additional content added by the person who shared this activity, applicable only when resharing an activity. - pub annotation: Option, - /// Identifies this resource as an activity. Value: "plus#activity". - pub kind: Option, - /// Title of this activity. - pub title: Option, - /// The link to this activity. - pub url: Option, - /// ID of the place where this activity occurred. - #[serde(rename="placeId")] - pub place_id: Option, - /// The person who performed this activity. - pub actor: Option, - /// The ID of this activity. - pub id: Option, - /// Identifies who has access to see this activity. - pub access: Option, - /// Latitude and longitude where this activity occurred. Format is latitude followed by longitude, space separated. - pub geocode: Option, - /// The location where this activity occurred. - pub location: Option, - /// The service provider that initially published this activity. - pub provider: Option, - /// If this activity is a crosspost from another system, this property specifies the ID of the original activity. - #[serde(rename="crosspostSource")] - pub crosspost_source: Option, - /// The time at which this activity was initially published. Formatted as an RFC 3339 timestamp. - pub published: Option, +pub struct CommentActorVerification { + /// Verification for one-time or manual processes. + #[serde(rename="adHocVerified")] + pub ad_hoc_verified: Option, } -impl ResponseResult for Activity {} +impl NestedType for CommentActorVerification {} +impl Part for CommentActorVerification {} /// There is no detailed description. @@ -1435,6 +1551,39 @@ pub struct Place { impl Part for Place {} +/// Comments in reply to this 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 ActivityObjectReplies { + /// Total number of comments on this activity. + #[serde(rename="totalItems")] + pub total_items: Option, + /// The URL for the collection of comments in reply to this activity. + #[serde(rename="selfLink")] + pub self_link: Option, +} + +impl NestedType for ActivityObjectReplies {} +impl Part for ActivityObjectReplies {} + + +/// Actor info specific to particular clients. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ActivityObjectActorClientSpecificActorInfo { + /// Actor info specific to YouTube clients. + #[serde(rename="youtubeActorInfo")] + pub youtube_actor_info: Option, +} + +impl NestedType for ActivityObjectActorClientSpecificActorInfo {} +impl Part for ActivityObjectActorClientSpecificActorInfo {} + + // ################### // MethodBuilders ### @@ -1463,7 +1612,7 @@ impl Part for Place {} /// ::default(), None); /// let mut hub = Plus::new(hyper::Client::new(), auth); /// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* -/// // like `insert(...)`, `list(...)` and `remove(...)` +/// // like `insert(...)` and `list(...)` /// // to build up your call. /// let rb = hub.moments(); /// # } @@ -1522,23 +1671,6 @@ impl<'a, C, A> MomentMethods<'a, C, A> { _additional_params: Default::default(), } } - - /// Create a builder to help you perform the following task: - /// - /// Delete a moment. - /// - /// # Arguments - /// - /// * `id` - The ID of the moment to delete. - pub fn remove(&self, id: &str) -> MomentRemoveCall<'a, C, A> { - MomentRemoveCall { - hub: self.hub, - _id: id.to_string(), - _delegate: Default::default(), - _scopes: Default::default(), - _additional_params: Default::default(), - } - } } @@ -2435,231 +2567,6 @@ impl<'a, C, A> MomentListCall<'a, C, A> where C: BorrowMut, A: oa } -/// Delete a moment. -/// -/// A builder for the *remove* method supported by a *moment* resource. -/// It is not used directly, but through a `MomentMethods` instance. -/// -/// # Example -/// -/// Instantiate a resource method builder -/// -/// ```test_harness,no_run -/// # extern crate hyper; -/// # extern crate yup_oauth2 as oauth2; -/// # extern crate google_plus1 as plus1; -/// # #[test] fn egal() { -/// # use std::default::Default; -/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; -/// # use plus1::Plus; -/// -/// # let secret: ApplicationSecret = Default::default(); -/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, -/// # hyper::Client::new(), -/// # ::default(), None); -/// # let mut hub = Plus::new(hyper::Client::new(), auth); -/// // You can configure optional parameters by calling the respective setters at will, and -/// // execute the final call using `doit()`. -/// // Values shown here are possibly random and not representative ! -/// let result = hub.moments().remove("id") -/// .doit(); -/// # } -/// ``` -pub struct MomentRemoveCall<'a, C, A> - where C: 'a, A: 'a { - - hub: &'a Plus, - _id: String, - _delegate: Option<&'a mut Delegate>, - _additional_params: HashMap, - _scopes: BTreeMap -} - -impl<'a, C, A> CallBuilder for MomentRemoveCall<'a, C, A> {} - -impl<'a, C, A> MomentRemoveCall<'a, C, A> where 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: "plus.moments.remove", - http_method: hyper::method::Method::Delete }); - let mut params: Vec<(&str, String)> = Vec::with_capacity((2 + self._additional_params.len())); - params.push(("id", self._id.to_string())); - for &field in ["id"].iter() { - if self._additional_params.contains_key(field) { - dlg.finished(false); - return Err(Error::FieldClash(field)); - } - } - for (name, value) in self._additional_params.iter() { - params.push((&name, value.clone())); - } - - - let mut url = "https://www.googleapis.com/plus/v1/moments/{id}".to_string(); - if self._scopes.len() == 0 { - self._scopes.insert(Scope::Login.as_ref().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() { - if let Some(index) = params.iter().position(|t| &t.0 == param_name) { - indices_for_removal.push(index); - } - } - for &index in indices_for_removal.iter() { - params.remove(index); - } - } - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_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) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = res; - - dlg.finished(true); - return Ok(result_value) - } - } - } - } - - - /// The ID of the moment to delete. - /// - /// 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. - pub fn id(mut self, new_value: &str) -> MomentRemoveCall<'a, C, A> { - self._id = new_value.to_string(); - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> MomentRemoveCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. - /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. - /// * *alt* (query-string) - Data format for the response. - pub fn param(mut self, name: T, value: T) -> MomentRemoveCall<'a, C, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::Login`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be - /// sufficient, a read-write scope will do as well. - pub fn add_scope(mut self, scope: T) -> MomentRemoveCall<'a, C, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().to_string(), ()); - self - } -} - - /// Search public activities. /// /// A builder for the *search* method supported by a *activity* resource. @@ -2687,9 +2594,9 @@ impl<'a, C, A> MomentRemoveCall<'a, C, A> where C: BorrowMut, A: /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.activities().search("query") -/// .page_token("justo") +/// .page_token("no") /// .order_by("justo") -/// .max_results(67) +/// .max_results(80) /// .language("et") /// .doit(); /// # } @@ -3186,8 +3093,8 @@ impl<'a, C, A> ActivityGetCall<'a, C, A> where C: BorrowMut, A: o /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.activities().list("userId", "collection") -/// .page_token("et") -/// .max_results(31) +/// .page_token("Lorem") +/// .max_results(80) /// .doit(); /// # } /// ``` @@ -3458,9 +3365,9 @@ impl<'a, C, A> ActivityListCall<'a, C, A> where C: BorrowMut, A: /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.comments().list("activityId") -/// .sort_order("sea") -/// .page_token("Lorem") -/// .max_results(26) +/// .sort_order("aliquyam") +/// .page_token("sea") +/// .max_results(46) /// .doit(); /// # } /// ``` @@ -3966,9 +3873,9 @@ impl<'a, C, A> CommentGetCall<'a, C, A> where C: BorrowMut, A: oa /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.people().search("query") -/// .page_token("dolor") -/// .max_results(62) -/// .language("elitr") +/// .page_token("sadipscing") +/// .max_results(53) +/// .language("eirmod") /// .doit(); /// # } /// ``` @@ -4217,8 +4124,8 @@ impl<'a, C, A> PeopleSearchCall<'a, C, A> where C: BorrowMut, A: /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.people().list_by_activity("activityId", "collection") -/// .page_token("labore") -/// .max_results(62) +/// .page_token("no") +/// .max_results(65) /// .doit(); /// # } /// ``` @@ -4489,9 +4396,9 @@ impl<'a, C, A> PeopleListByActivityCall<'a, C, A> where C: BorrowMut"] description = "A complete library to interact with plusDomains (protocol v1)" repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/plusdomains1-cli" diff --git a/gen/plusdomains1-cli/README.md b/gen/plusdomains1-cli/README.md index 45c89b39d1..8764d575f2 100644 --- a/gen/plusdomains1-cli/README.md +++ b/gen/plusdomains1-cli/README.md @@ -24,7 +24,7 @@ Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/ma # Usage -This documentation was generated from the *plusDomains* API at revision *20150719*. The CLI is at version *0.3.2*. +This documentation was generated from the *plusDomains* API at revision *20151014*. The CLI is at version *0.3.2*. ```bash plusdomains1 [options] diff --git a/gen/plusdomains1-cli/mkdocs.yml b/gen/plusdomains1-cli/mkdocs.yml index 5e52f52a3e..22dba92cb5 100644 --- a/gen/plusdomains1-cli/mkdocs.yml +++ b/gen/plusdomains1-cli/mkdocs.yml @@ -1,4 +1,4 @@ -site_name: plusDomains v0.3.2+20150719 +site_name: plusDomains v0.3.2+20151014 site_url: http://byron.github.io/google-apis-rs/google-plusdomains1-cli site_description: Write integrating applications with bcore diff --git a/gen/plusdomains1-cli/src/main.rs b/gen/plusdomains1-cli/src/main.rs index e5ec090c74..c466264ad5 100644 --- a/gen/plusdomains1-cli/src/main.rs +++ b/gen/plusdomains1-cli/src/main.rs @@ -131,9 +131,11 @@ impl<'n, 'a> Engine<'n, 'a> { "object.original-content" => Some(("object.originalContent", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "object.plusoners.total-items" => Some(("object.plusoners.totalItems", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), "object.plusoners.self-link" => Some(("object.plusoners.selfLink", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "object.actor.display-name" => Some(("object.actor.displayName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "object.actor.url" => Some(("object.actor.url", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "object.actor.image.url" => Some(("object.actor.image.url", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), - "object.actor.display-name" => Some(("object.actor.displayName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "object.actor.client-specific-actor-info.youtube-actor-info.channel-id" => Some(("object.actor.clientSpecificActorInfo.youtubeActorInfo.channelId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "object.actor.verification.ad-hoc-verified" => Some(("object.actor.verification.adHocVerified", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "object.actor.id" => Some(("object.actor.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "object.content" => Some(("object.content", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "object.url" => Some(("object.url", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), @@ -147,12 +149,14 @@ impl<'n, 'a> Engine<'n, 'a> { "object.id" => Some(("object.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "object.object-type" => Some(("object.objectType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), - "actor.url" => Some(("actor.url", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), - "actor.image.url" => Some(("actor.image.url", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "actor.display-name" => Some(("actor.displayName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), - "actor.id" => Some(("actor.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "actor.name.given-name" => Some(("actor.name.givenName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "actor.name.family-name" => Some(("actor.name.familyName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "actor.url" => Some(("actor.url", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "actor.image.url" => Some(("actor.image.url", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "actor.client-specific-actor-info.youtube-actor-info.channel-id" => Some(("actor.clientSpecificActorInfo.youtubeActorInfo.channelId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "actor.verification.ad-hoc-verified" => Some(("actor.verification.adHocVerified", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "actor.id" => Some(("actor.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "place-id" => Some(("placeId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "access.kind" => Some(("access.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "access.description" => Some(("access.description", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), @@ -172,7 +176,7 @@ impl<'n, 'a> Engine<'n, 'a> { "address" => Some(("address", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "published" => Some(("published", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), _ => { - let suggestion = FieldCursor::did_you_mean(key, &vec!["access", "actor", "address", "annotation", "can-comment", "can-plusone", "can-update", "content", "crosspost-source", "description", "display-name", "domain-restricted", "etag", "family-name", "formatted", "geocode", "given-name", "id", "image", "is-plus-oned", "kind", "latitude", "location", "longitude", "name", "object", "object-type", "original-content", "place-id", "place-name", "plusoners", "position", "provider", "published", "radius", "replies", "resharers", "resharing-disabled", "self-link", "status-for-viewer", "title", "total-items", "updated", "url", "verb"]); + let suggestion = FieldCursor::did_you_mean(key, &vec!["access", "actor", "ad-hoc-verified", "address", "annotation", "can-comment", "can-plusone", "can-update", "channel-id", "client-specific-actor-info", "content", "crosspost-source", "description", "display-name", "domain-restricted", "etag", "family-name", "formatted", "geocode", "given-name", "id", "image", "is-plus-oned", "kind", "latitude", "location", "longitude", "name", "object", "object-type", "original-content", "place-id", "place-name", "plusoners", "position", "provider", "published", "radius", "replies", "resharers", "resharing-disabled", "self-link", "status-for-viewer", "title", "total-items", "updated", "url", "verb", "verification", "youtube-actor-info"]); err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); None } @@ -973,9 +977,11 @@ impl<'n, 'a> Engine<'n, 'a> { "object.original-content" => Some(("object.originalContent", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "object.object-type" => Some(("object.objectType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "updated" => Some(("updated", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "actor.display-name" => Some(("actor.displayName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "actor.url" => Some(("actor.url", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "actor.image.url" => Some(("actor.image.url", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), - "actor.display-name" => Some(("actor.displayName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "actor.client-specific-actor-info.youtube-actor-info.channel-id" => Some(("actor.clientSpecificActorInfo.youtubeActorInfo.channelId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "actor.verification.ad-hoc-verified" => Some(("actor.verification.adHocVerified", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "actor.id" => Some(("actor.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "verb" => Some(("verb", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "etag" => Some(("etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), @@ -983,7 +989,7 @@ impl<'n, 'a> Engine<'n, 'a> { "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "self-link" => Some(("selfLink", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), _ => { - let suggestion = FieldCursor::did_you_mean(key, &vec!["actor", "content", "display-name", "etag", "id", "image", "kind", "object", "object-type", "original-content", "plusoners", "published", "self-link", "total-items", "updated", "url", "verb"]); + let suggestion = FieldCursor::did_you_mean(key, &vec!["actor", "ad-hoc-verified", "channel-id", "client-specific-actor-info", "content", "display-name", "etag", "id", "image", "kind", "object", "object-type", "original-content", "plusoners", "published", "self-link", "total-items", "updated", "url", "verb", "verification", "youtube-actor-info"]); err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); None } @@ -2157,7 +2163,7 @@ fn main() { let mut app = App::new("plusdomains1") .author("Sebastian Thiel ") - .version("0.3.2+20150719") + .version("0.3.2+20151014") .about("The Google+ API enables developers to build on top of the Google+ platform.") .after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_plusdomains1_cli") .arg(Arg::with_name("url") diff --git a/gen/plusdomains1/Cargo.toml b/gen/plusdomains1/Cargo.toml index 3035d9ebe1..a24f7d5b9e 100644 --- a/gen/plusdomains1/Cargo.toml +++ b/gen/plusdomains1/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-plusdomains1" -version = "0.1.9+20150719" +version = "0.1.9+20151014" authors = ["Sebastian Thiel "] description = "A complete library to interact with plusDomains (protocol v1)" repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/plusdomains1" diff --git a/gen/plusdomains1/README.md b/gen/plusdomains1/README.md index 20816dd559..68f53729f4 100644 --- a/gen/plusdomains1/README.md +++ b/gen/plusdomains1/README.md @@ -5,7 +5,7 @@ DO NOT EDIT ! --> The `google-plusdomains1` library allows access to all features of the *Google plusDomains* service. -This documentation was generated from *plusDomains* crate version *0.1.9+20150719*, where *20150719* is the exact revision of the *plusDomains:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +This documentation was generated from *plusDomains* crate version *0.1.9+20151014*, where *20151014* is the exact revision of the *plusDomains:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. Everything else about the *plusDomains* *v1* API can be found at the [official documentation site](https://developers.google.com/+/domains/). diff --git a/gen/plusdomains1/src/lib.rs b/gen/plusdomains1/src/lib.rs index aa355d5bde..1bd21fce19 100644 --- a/gen/plusdomains1/src/lib.rs +++ b/gen/plusdomains1/src/lib.rs @@ -2,7 +2,7 @@ // This file was generated automatically from 'src/mako/api/lib.rs.mako' // DO NOT EDIT ! -//! This documentation was generated from *plusDomains* crate version *0.1.9+20150719*, where *20150719* is the exact revision of the *plusDomains:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +//! This documentation was generated from *plusDomains* crate version *0.1.9+20151014*, where *20151014* is the exact revision of the *plusDomains:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. //! //! Everything else about the *plusDomains* *v1* API can be found at the //! [official documentation site](https://developers.google.com/+/domains/). diff --git a/gen/plusdomains1/src/lib.rs.in b/gen/plusdomains1/src/lib.rs.in index 0449e1d4bb..6aa8cf6b2b 100644 --- a/gen/plusdomains1/src/lib.rs.in +++ b/gen/plusdomains1/src/lib.rs.in @@ -411,22 +411,82 @@ impl NestedType for PersonOrganizations {} impl Part for PersonOrganizations {} -/// Comments in reply to this activity. +/// 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 activities](struct.ActivityInsertCall.html) (request|response) +/// * [get activities](struct.ActivityGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Activity { + /// Name of the place where this activity occurred. + #[serde(rename="placeName")] + pub place_name: Option, + /// The time at which this activity was last updated. Formatted as an RFC 3339 timestamp. + pub updated: Option, + /// The object of this activity. + pub object: Option, + /// This activity's verb, which indicates the action that was performed. Possible values include, but are not limited to, the following values: + /// - "post" - Publish content to the stream. + /// - "share" - Reshare an activity. + pub verb: Option, + /// Radius, in meters, of the region where this activity occurred, centered at the latitude and longitude identified in geocode. + pub radius: Option, + /// ETag of this response for caching purposes. + pub etag: Option, + /// Street address where this activity occurred. + pub address: Option, + /// Additional content added by the person who shared this activity, applicable only when resharing an activity. + pub annotation: Option, + /// Identifies this resource as an activity. Value: "plus#activity". + pub kind: Option, + /// Title of this activity. + pub title: Option, + /// The link to this activity. + pub url: Option, + /// ID of the place where this activity occurred. + #[serde(rename="placeId")] + pub place_id: Option, + /// The person who performed this activity. + pub actor: Option, + /// The ID of this activity. + pub id: Option, + /// Identifies who has access to see this activity. + pub access: Option, + /// Latitude and longitude where this activity occurred. Format is latitude followed by longitude, space separated. + pub geocode: Option, + /// The location where this activity occurred. + pub location: Option, + /// The service provider that initially published this activity. + pub provider: Option, + /// If this activity is a crosspost from another system, this property specifies the ID of the original activity. + #[serde(rename="crosspostSource")] + pub crosspost_source: Option, + /// The time at which this activity was initially published. Formatted as an RFC 3339 timestamp. + pub published: Option, +} + +impl RequestValue for Activity {} +impl ResponseResult for Activity {} + + +/// Actor info specific to YouTube clients. /// /// This type is not used in any activity, and only used as *part* of another schema. /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] -pub struct ActivityObjectReplies { - /// Total number of comments on this activity. - #[serde(rename="totalItems")] - pub total_items: Option, - /// The URL for the collection of comments in reply to this activity. - #[serde(rename="selfLink")] - pub self_link: Option, +pub struct ActivityActorClientSpecificActorInfoYoutubeActorInfo { + /// ID of the YouTube channel owned by the Actor. + #[serde(rename="channelId")] + pub channel_id: Option, } -impl NestedType for ActivityObjectReplies {} -impl Part for ActivityObjectReplies {} +impl NestedType for ActivityActorClientSpecificActorInfoYoutubeActorInfo {} +impl Part for ActivityActorClientSpecificActorInfoYoutubeActorInfo {} /// An object representation of the individual components of name. @@ -638,6 +698,21 @@ impl NestedType for CommentInReplyTo {} impl Part for CommentInReplyTo {} +/// Actor info specific to particular clients. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ActivityActorClientSpecificActorInfo { + /// Actor info specific to YouTube clients. + #[serde(rename="youtubeActorInfo")] + pub youtube_actor_info: Option, +} + +impl NestedType for ActivityActorClientSpecificActorInfo {} +impl Part for ActivityActorClientSpecificActorInfo {} + + /// There is no detailed description. /// /// # Activities @@ -679,13 +754,18 @@ impl ResponseResult for PeopleFeed {} /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct CommentActor { + /// The name of this actor, suitable for display. + #[serde(rename="displayName")] + pub display_name: Option, + /// Verification status of actor. + pub verification: Option, /// A link to the Person resource for this actor. pub url: Option, /// The image representation of this actor. pub image: Option, - /// The name of this actor, suitable for display. - #[serde(rename="displayName")] - pub display_name: Option, + /// Actor info specific to particular clients. + #[serde(rename="clientSpecificActorInfo")] + pub client_specific_actor_info: Option, /// The ID of the actor. pub id: Option, } @@ -694,6 +774,21 @@ impl NestedType for CommentActor {} impl Part for CommentActor {} +/// Actor info specific to YouTube clients. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ActivityObjectActorClientSpecificActorInfoYoutubeActorInfo { + /// ID of the YouTube channel owned by the Actor. + #[serde(rename="channelId")] + pub channel_id: Option, +} + +impl NestedType for ActivityObjectActorClientSpecificActorInfoYoutubeActorInfo {} +impl Part for ActivityObjectActorClientSpecificActorInfoYoutubeActorInfo {} + + /// Extra information about the cover photo. /// /// This type is not used in any activity, and only used as *part* of another schema. @@ -749,6 +844,21 @@ impl NestedType for ActivityProvider {} impl Part for ActivityProvider {} +/// Actor info specific to particular clients. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct CommentActorClientSpecificActorInfo { + /// Actor info specific to YouTube clients. + #[serde(rename="youtubeActorInfo")] + pub youtube_actor_info: Option, +} + +impl NestedType for CommentActorClientSpecificActorInfo {} +impl Part for CommentActorClientSpecificActorInfo {} + + /// The position of the place. /// /// This type is not used in any activity, and only used as *part* of another schema. @@ -929,19 +1039,39 @@ impl NestedType for PersonCoverCoverPhoto {} impl Part for PersonCoverCoverPhoto {} +/// Verification status of actor. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ActivityObjectActorVerification { + /// Verification for one-time or manual processes. + #[serde(rename="adHocVerified")] + pub ad_hoc_verified: Option, +} + +impl NestedType for ActivityObjectActorVerification {} +impl Part for ActivityObjectActorVerification {} + + /// If this activity's object is itself another activity, such as when a person reshares an activity, this property specifies the original activity's actor. /// /// This type is not used in any activity, and only used as *part* of another schema. /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct ActivityObjectActor { + /// The original actor's name, which is suitable for display. + #[serde(rename="displayName")] + pub display_name: Option, + /// Verification status of actor. + pub verification: Option, /// A link to the original actor's Google profile. pub url: Option, /// The image representation of the original actor. pub image: Option, - /// The original actor's name, which is suitable for display. - #[serde(rename="displayName")] - pub display_name: Option, + /// Actor info specific to particular clients. + #[serde(rename="clientSpecificActorInfo")] + pub client_specific_actor_info: Option, /// ID of the original actor. pub id: Option, } @@ -992,6 +1122,24 @@ impl NestedType for PersonCover {} impl Part for PersonCover {} +/// Comments in reply to this 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 ActivityObjectReplies { + /// Total number of comments on this activity. + #[serde(rename="totalItems")] + pub total_items: Option, + /// The URL for the collection of comments in reply to this activity. + #[serde(rename="selfLink")] + pub self_link: Option, +} + +impl NestedType for ActivityObjectReplies {} +impl Part for ActivityObjectReplies {} + + /// There is no detailed description. /// /// This type is not used in any activity, and only used as *part* of another schema. @@ -1138,6 +1286,21 @@ pub struct Audience { impl Resource for Audience {} +/// Actor info specific to YouTube clients. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct CommentActorClientSpecificActorInfoYoutubeActorInfo { + /// ID of the YouTube channel owned by the Actor. + #[serde(rename="channelId")] + pub channel_id: Option, +} + +impl NestedType for CommentActorClientSpecificActorInfoYoutubeActorInfo {} +impl Part for CommentActorClientSpecificActorInfoYoutubeActorInfo {} + + /// There is no detailed description. /// /// This type is not used in any activity, and only used as *part* of another schema. @@ -1174,67 +1337,19 @@ impl NestedType for ActivityObjectAttachmentsPreviewThumbnails {} impl Part for ActivityObjectAttachmentsPreviewThumbnails {} -/// There is no detailed description. +/// Verification status of actor. /// -/// # Activities -/// -/// This type is used in activities, which are methods you may call on this type or where 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 activities](struct.ActivityInsertCall.html) (request|response) -/// * [get activities](struct.ActivityGetCall.html) (response) +/// This type is not used in any activity, and only used as *part* of another schema. /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] -pub struct Activity { - /// Name of the place where this activity occurred. - #[serde(rename="placeName")] - pub place_name: Option, - /// The time at which this activity was last updated. Formatted as an RFC 3339 timestamp. - pub updated: Option, - /// The object of this activity. - pub object: Option, - /// This activity's verb, which indicates the action that was performed. Possible values include, but are not limited to, the following values: - /// - "post" - Publish content to the stream. - /// - "share" - Reshare an activity. - pub verb: Option, - /// Radius, in meters, of the region where this activity occurred, centered at the latitude and longitude identified in geocode. - pub radius: Option, - /// ETag of this response for caching purposes. - pub etag: Option, - /// Street address where this activity occurred. - pub address: Option, - /// Additional content added by the person who shared this activity, applicable only when resharing an activity. - pub annotation: Option, - /// Identifies this resource as an activity. Value: "plus#activity". - pub kind: Option, - /// Title of this activity. - pub title: Option, - /// The link to this activity. - pub url: Option, - /// ID of the place where this activity occurred. - #[serde(rename="placeId")] - pub place_id: Option, - /// The person who performed this activity. - pub actor: Option, - /// The ID of this activity. - pub id: Option, - /// Identifies who has access to see this activity. - pub access: Option, - /// Latitude and longitude where this activity occurred. Format is latitude followed by longitude, space separated. - pub geocode: Option, - /// The location where this activity occurred. - pub location: Option, - /// The service provider that initially published this activity. - pub provider: Option, - /// If this activity is a crosspost from another system, this property specifies the ID of the original activity. - #[serde(rename="crosspostSource")] - pub crosspost_source: Option, - /// The time at which this activity was initially published. Formatted as an RFC 3339 timestamp. - pub published: Option, +pub struct CommentActorVerification { + /// Verification for one-time or manual processes. + #[serde(rename="adHocVerified")] + pub ad_hoc_verified: Option, } -impl RequestValue for Activity {} -impl ResponseResult for Activity {} +impl NestedType for CommentActorVerification {} +impl Part for CommentActorVerification {} /// The person who performed this activity. @@ -1243,17 +1358,22 @@ impl ResponseResult for Activity {} /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct ActivityActor { + /// The name of the actor, suitable for display. + #[serde(rename="displayName")] + pub display_name: Option, + /// An object representation of the individual components of name. + pub name: Option, /// The link to the actor's Google profile. pub url: Option, /// The image representation of the actor. pub image: Option, - /// The name of the actor, suitable for display. - #[serde(rename="displayName")] - pub display_name: Option, + /// Actor info specific to particular clients. + #[serde(rename="clientSpecificActorInfo")] + pub client_specific_actor_info: Option, /// The ID of the actor's Person resource. pub id: Option, - /// An object representation of the individual components of name. - pub name: Option, + /// Verification status of actor. + pub verification: Option, } impl NestedType for ActivityActor {} @@ -1553,6 +1673,36 @@ pub struct CircleFeed { impl ResponseResult for CircleFeed {} +/// Actor info specific to particular clients. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ActivityObjectActorClientSpecificActorInfo { + /// Actor info specific to YouTube clients. + #[serde(rename="youtubeActorInfo")] + pub youtube_actor_info: Option, +} + +impl NestedType for ActivityObjectActorClientSpecificActorInfo {} +impl Part for ActivityObjectActorClientSpecificActorInfo {} + + +/// Verification status of actor. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ActivityActorVerification { + /// Verification for one-time or manual processes. + #[serde(rename="adHocVerified")] + pub ad_hoc_verified: Option, +} + +impl NestedType for ActivityActorVerification {} +impl Part for ActivityActorVerification {} + + // ################### // MethodBuilders ### @@ -6373,10 +6523,10 @@ impl<'a, C, A> MediaInsertCall<'a, C, A> where C: BorrowMut, A: o self.doit(stream, mime_type, "simple") } /// Upload media in a resumable fashion. - /// Even if the upload fails or is interrupted, it can be resumed for a + /// Even if the upload fails or is interrupted, it can be resumed for a /// certain amount of time as the server maintains state temporarily. /// - /// The delegate will be asked for an `upload_url()`, and if not provided, will be asked to store an upload URL + /// The delegate will be asked for an `upload_url()`, and if not provided, will be asked to store an upload URL /// that was provided by the server, using `store_upload_url(...)`. The upload will be done in chunks, the delegate /// may specify the `chunk_size()` and may cancel the operation before each chunk is uploaded, using /// `cancel_chunk_upload(...)`. diff --git a/gen/proximitybeacon1_beta1-cli/Cargo.toml b/gen/proximitybeacon1_beta1-cli/Cargo.toml new file mode 100644 index 0000000000..9ef06e1a39 --- /dev/null +++ b/gen/proximitybeacon1_beta1-cli/Cargo.toml @@ -0,0 +1,35 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-proximitybeacon1_beta1-cli" +version = "0.3.2+20150729" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with proximitybeacon (protocol v1beta1)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/proximitybeacon1_beta1-cli" +homepage = "https://developers.google.com/beacons/proximity/" +documentation = "http://byron.github.io/google-apis-rs/google_proximitybeacon1_beta1_cli" +license = "MIT" +keywords = ["proximitybeacon", "google", "cli"] + +[[bin]] +name = "proximitybeacon1-beta1" + +[dependencies] +hyper = ">= 0.6.8" +mime = "0.1.0" +serde = ">= 0.6.0" +serde_json = ">= 0.6.0" +yup-oauth2 = "*" +strsim = "*" +yup-hyper-mock = ">=1.0.0" +clap = ">= 1.0.3" + +[build-dependencies] +syntex = { version = "*" } +serde_codegen = { version = "*" } + + +[dependencies.google-proximitybeacon1_beta1] +path = "../proximitybeacon1_beta1" diff --git a/gen/proximitybeacon1_beta1-cli/LICENSE.md b/gen/proximitybeacon1_beta1-cli/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/proximitybeacon1_beta1-cli/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/proximitybeacon1_beta1-cli/README.md b/gen/proximitybeacon1_beta1-cli/README.md new file mode 100644 index 0000000000..fed5042516 --- /dev/null +++ b/gen/proximitybeacon1_beta1-cli/README.md @@ -0,0 +1,124 @@ + +The `proximitybeacon1-beta1` command-line interface *(CLI)* allows to use most features of the *Google proximitybeacon* service from the comfort of your terminal. + +By default all output is printed to standard out, but flags can be set to direct it into a file independent of your shell's +capabilities. Errors will be printed to standard error, and cause the program's exit code to be non-zero. + +If data-structures are requested, these will be returned as pretty-printed JSON, to be useful as input to other tools. + +Everything else about the *proximitybeacon* API can be found at the +[official documentation site](https://developers.google.com/beacons/proximity/). + +# Downloads + +You can download the pre-compiled 64bit binaries for the following platforms: + +* ![icon](http://megaicons.net/static/img/icons_sizes/6/140/16/ubuntu-icon.png) [ubuntu](http://dl.byronimo.de/google.rs/cli/0.3.2/ubuntu/proximitybeacon1-beta1.tar.gz) +* ![icon](http://hydra-media.cursecdn.com/wow.gamepedia.com/a/a2/Apple-icon-16x16.png?version=25ddd67ac3dd3b634478e3978b76cb74) [osx](http://dl.byronimo.de/google.rs/cli/0.3.2/osx/proximitybeacon1-beta1.tar.gz) + +Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/proximitybeacon1_beta1-cli). + +# Usage + +This documentation was generated from the *proximitybeacon* API at revision *20150729*. The CLI is at version *0.3.2*. + +```bash +proximitybeacon1-beta1 [options] + beaconinfo + getforobserved (-r )... [-p ]... [-o ] + beacons + activate [-p ]... [-o ] + attachments-batch-delete [-p ]... [-o ] + attachments-create (-r )... [-p ]... [-o ] + attachments-delete [-p ]... [-o ] + attachments-list [-p ]... [-o ] + deactivate [-p ]... [-o ] + decommission [-p ]... [-o ] + diagnostics-list [-p ]... [-o ] + get [-p ]... [-o ] + list [-p ]... [-o ] + register (-r )... [-p ]... [-o ] + update (-r )... [-p ]... [-o ] + namespaces + list [-p ]... [-o ] + proximitybeacon1-beta1 --help + +Configuration: + --config-dir + A directory into which we will store our persistent data. Defaults to + a user-writable directory that we will create during the first invocation. + [default: ~/.google-service-cli] + --debug + Output all server communication to standard error. `tx` and `rx` are placed + into the same stream. + --debug-auth + Output all communication related to authentication to standard error. `tx` + and `rx` are placed into the same stream. + +``` + +# Configuration + +The program will store all persistent data in the `~/.google-service-cli` directory in *JSON* files prefixed with `proximitybeacon1-beta1-`. You can change the directory used to store configuration with the `--config-dir` flag on a per-invocation basis. + +More information about the various kinds of persistent data are given in the following paragraphs. + +# Authentication + +Most APIs require a user to authenticate any request. If this is the case, the [scope][scopes] determines the +set of permissions granted. The granularity of these is usually no more than *read-only* or *full-access*. + +If not set, the system will automatically select the smallest feasible scope, e.g. when invoking a +method that is read-only, it will ask only for a read-only scope. +You may use the `--scope` flag to specify a scope directly. +All applicable scopes are documented in the respective method's CLI documentation. + +The first time a scope is used, the user is asked for permission. Follow the instructions given +by the CLI to grant permissions, or to decline. + +If a scope was authenticated by the user, the respective information will be stored as *JSON* in the configuration +directory, e.g. `~/.google-service-cli/proximitybeacon1-beta1-token-.json`. No manual management of these tokens +is necessary. + +To revoke granted authentication, please refer to the [official documentation][revoke-access]. + +# Application Secrets + +In order to allow any application to use Google services, it will need to be registered using the +[Google Developer Console][google-dev-console]. APIs the application may use are then enabled for it +one by one. Most APIs can be used for free and have a daily quota. + +To allow more comfortable usage of the CLI without forcing anyone to register an own application, the CLI +comes with a default application secret that is configured accordingly. This also means that heavy usage +all around the world may deplete the daily quota. + +You can workaround this limitation by putting your own secrets file at this location: +`~/.google-service-cli/proximitybeacon1-beta1-secret.json`, assuming that the required *proximitybeacon* API +was enabled for it. Such a secret file can be downloaded in the *Google Developer Console* at +*APIs & auth -> Credentials -> Download JSON* and used as is. + +Learn more about how to setup Google projects and enable APIs using the [official documentation][google-project-new]. + + +# Debugging + +Even though the CLI does its best to provide usable error messages, sometimes it might be desirable to know +what exactly led to a particular issue. This is done by allowing all client-server communication to be +output to standard error *as-is*. + +The `--debug` flag will print all client-server communication to standard error, whereas the `--debug-auth` flag +will cause all communication related to authentication to standard error. +If the `--debug` flag is set, error-results will be debug-printed, possibly yielding more information about the +issue at hand. + +You may consider redirecting standard error into a file for ease of use, e.g. `proximitybeacon1-beta1 --debug [options] 2>debug.txt`. + + +[scopes]: https://developers.google.com/+/api/oauth#scopes +[revoke-access]: http://webapps.stackexchange.com/a/30849 +[google-dev-console]: https://console.developers.google.com/ +[google-project-new]: https://developers.google.com/console/help/new/ \ No newline at end of file diff --git a/gen/proximitybeacon1_beta1-cli/mkdocs.yml b/gen/proximitybeacon1_beta1-cli/mkdocs.yml new file mode 100644 index 0000000000..21fb324dc6 --- /dev/null +++ b/gen/proximitybeacon1_beta1-cli/mkdocs.yml @@ -0,0 +1,30 @@ +site_name: proximitybeacon v0.3.2+20150729 +site_url: http://byron.github.io/google-apis-rs/google-proximitybeacon1_beta1-cli +site_description: Write integrating applications with bcore + +repo_url: https://github.com/Byron/google-apis-rs/tree/master/gen/proximitybeacon1_beta1-cli + +docs_dir: docs +site_dir: build_html + +pages: +- ['index.md', 'Home'] +- ['beaconinfo_getforobserved.md', 'Beaconinfo', 'Getforobserved'] +- ['beacons_activate.md', 'Beacons', 'Activate'] +- ['beacons_attachments-batch-delete.md', 'Beacons', 'Attachments Batch Delete'] +- ['beacons_attachments-create.md', 'Beacons', 'Attachments Create'] +- ['beacons_attachments-delete.md', 'Beacons', 'Attachments Delete'] +- ['beacons_attachments-list.md', 'Beacons', 'Attachments List'] +- ['beacons_deactivate.md', 'Beacons', 'Deactivate'] +- ['beacons_decommission.md', 'Beacons', 'Decommission'] +- ['beacons_diagnostics-list.md', 'Beacons', 'Diagnostics List'] +- ['beacons_get.md', 'Beacons', 'Get'] +- ['beacons_list.md', 'Beacons', 'List'] +- ['beacons_register.md', 'Beacons', 'Register'] +- ['beacons_update.md', 'Beacons', 'Update'] +- ['namespaces_list.md', 'Namespaces', 'List'] + +theme: readthedocs + +copyright: Copyright © 2015, `Sebastian Thiel` + diff --git a/gen/proximitybeacon1_beta1-cli/src/cmn.rs b/gen/proximitybeacon1_beta1-cli/src/cmn.rs new file mode 100644 index 0000000000..8358f156fa --- /dev/null +++ b/gen/proximitybeacon1_beta1-cli/src/cmn.rs @@ -0,0 +1,721 @@ +// COPY OF 'src/rust/cli/cmn.rs' +// DO NOT EDIT +use oauth2::{ApplicationSecret, ConsoleApplicationSecret, TokenStorage, Token}; +use serde_json as json; +use serde_json::value::Value; +use mime::Mime; +use clap::{App, SubCommand}; +use strsim; + +use std::fs; +use std::env; +use std::io; +use std::fmt; +use std::path::{Path, PathBuf}; +use std::str::FromStr; +use std::string::ToString; +use std::io::{Write, Read, stdout}; + +use std::default::Default; + +const FIELD_SEP: char = '.'; + + +pub enum ComplexType { + Pod, + Vec, + Map, +} + + // Null, + // Bool(bool), + // I64(i64), + // U64(u64), + // F64(f64), + // String(String), + +pub enum JsonType { + Boolean, + Int, + Uint, + Float, + String, +} + +pub struct JsonTypeInfo { + pub jtype: JsonType, + pub ctype: ComplexType, +} + +// Based on @erickt user comment. Thanks for the idea ! +// Remove all keys whose values are null from given value (changed in place) +pub fn remove_json_null_values(value: &mut Value) { + match *value { + Value::Object(ref mut map) => { + let mut for_removal = Vec::new(); + + for (key, mut value) in map.iter_mut() { + if value.is_null() { + for_removal.push(key.clone()); + } else { + remove_json_null_values(&mut value); + } + } + + for key in &for_removal { + map.remove(key); + } + } + _ => {} + } +} + +fn did_you_mean<'a>(v: &str, possible_values: &[&'a str]) -> Option<&'a str> { + + let mut candidate: Option<(f64, &str)> = None; + for pv in possible_values { + let confidence = strsim::jaro_winkler(v, pv); + if confidence > 0.8 && (candidate.is_none() || (candidate.as_ref().unwrap().0 < confidence)) { + candidate = Some((confidence, pv)); + } + } + match candidate { + None => None, + Some((_, candidate)) => Some(candidate), + } +} + +pub enum CallType { + Upload(UploadProtocol), + Standard, +} + +arg_enum!{ + pub enum UploadProtocol { + Simple, + Resumable + } +} + +impl AsRef for UploadProtocol { + fn as_ref(&self) -> &str { + match *self { + UploadProtocol::Simple => "simple", + UploadProtocol::Resumable => "resumable" + } + } +} + +impl AsRef for CallType { + fn as_ref(&self) -> &str { + match *self { + CallType::Upload(ref proto) => proto.as_ref(), + CallType::Standard => "standard-request" + } + } +} + +#[derive(Clone, Default)] +pub struct FieldCursor(Vec); + +impl ToString for FieldCursor { + fn to_string(&self) -> String { + self.0.join(".") + } +} + +impl From<&'static str> for FieldCursor { + fn from(value: &'static str) -> FieldCursor { + let mut res = FieldCursor::default(); + res.set(value).unwrap(); + res + } +} + +impl FieldCursor { + pub fn set(&mut self, value: &str) -> Result<(), CLIError> { + if value.len() == 0 { + return Err(CLIError::Field(FieldError::Empty)) + } + + let mut first_is_field_sep = false; + let mut char_count: usize = 0; + let mut last_c = FIELD_SEP; + let mut num_conscutive_field_seps = 0; + + let mut field = String::new(); + let mut fields = self.0.clone(); + + let push_field = |fs: &mut Vec, f: &mut String| { + if f.len() > 0 { + fs.push(f.clone()); + f.truncate(0); + } + }; + + for (cid, c) in value.chars().enumerate() { + char_count += 1; + + if c == FIELD_SEP { + if cid == 0 { + first_is_field_sep = true; + } + num_conscutive_field_seps += 1; + if cid > 0 && last_c == FIELD_SEP { + if fields.pop().is_none() { + return Err(CLIError::Field(FieldError::PopOnEmpty(value.to_string()))) + } + } else { + push_field(&mut fields, &mut field); + } + } else { + num_conscutive_field_seps = 0; + if cid == 1 { + if first_is_field_sep { + fields.truncate(0); + } + } + field.push(c); + } + + last_c = c; + } + + push_field(&mut fields, &mut field); + + if char_count == 1 && first_is_field_sep { + fields.truncate(0); + } + if char_count > 1 && num_conscutive_field_seps == 1 { + return Err(CLIError::Field(FieldError::TrailingFieldSep(value.to_string()))) + } + + self.0 = fields; + Ok(()) + } + + pub fn did_you_mean(value: &str, possible_values: &[&str]) -> Option { + if value.len() == 0 { + return None + } + + let mut last_c = FIELD_SEP; + + let mut field = String::new(); + let mut output = String::new(); + + let push_field = |fs: &mut String, f: &mut String| { + if f.len() > 0 { + fs.push_str( + match did_you_mean(&f, possible_values) { + Some(candidate) => candidate, + None => &f, + }); + f.truncate(0); + } + }; + + for (cid, c) in value.chars().enumerate() { + if c == FIELD_SEP { + if last_c != FIELD_SEP { + push_field(&mut output, &mut field); + } + output.push(c); + } else { + field.push(c); + } + + last_c = c; + } + + push_field(&mut output, &mut field); + + if &output == value { + None + } else { + Some(output) + } + } + + pub fn set_json_value(&self, mut object: &mut Value, + value: &str, type_info: JsonTypeInfo, + err: &mut InvalidOptionsError, + orig_cursor: &FieldCursor) { + assert!(self.0.len() > 0); + + for field in &self.0[..self.0.len()-1] { + let tmp = object; + object = + match *tmp { + Value::Object(ref mut mapping) => { + mapping.entry(field.to_owned()).or_insert( + Value::Object(Default::default()) + ) + }, + _ => panic!("We don't expect non-object Values here ...") + }; + } + + match *object { + Value::Object(ref mut mapping) => { + let field = &self.0[self.0.len()-1]; + let to_jval = + |value: &str, jtype: JsonType, err: &mut InvalidOptionsError| + -> Value { + match jtype { + JsonType::Boolean => + Value::Bool(arg_from_str(value, err, &field, "boolean")), + JsonType::Int => + Value::I64(arg_from_str(value, err, &field, "int")), + JsonType::Uint => + Value::U64(arg_from_str(value, err, &field, "uint")), + JsonType::Float => + Value::F64(arg_from_str(value, err, &field, "float")), + JsonType::String => + Value::String(value.to_owned()), + } + }; + + match type_info.ctype { + ComplexType::Pod => { + if mapping.insert(field.to_owned(), to_jval(value, type_info.jtype, err)).is_some() { + err.issues.push(CLIError::Field(FieldError::Duplicate(orig_cursor.to_string()))); + } + }, + ComplexType::Vec => { + match *mapping.entry(field.to_owned()) + .or_insert(Value::Array(Default::default())) { + Value::Array(ref mut values) => values.push(to_jval(value, type_info.jtype, err)), + _ => unreachable!() + } + }, + ComplexType::Map => { + let (key, value) = parse_kv_arg(value, err, true); + let jval = to_jval(value.unwrap_or(""), type_info.jtype, err); + + match *mapping.entry(field.to_owned()) + .or_insert(Value::Object(Default::default())) { + Value::Object(ref mut value_map) => { + if value_map.insert(key.to_owned(), jval).is_some() { + err.issues.push(CLIError::Field(FieldError::Duplicate(orig_cursor.to_string()))); + } + } + _ => unreachable!() + } + } + } + }, + _ => unreachable!() + } + } + + pub fn num_fields(&self) -> usize { + self.0.len() + } +} + +pub fn parse_kv_arg<'a>(kv: &'a str, err: &mut InvalidOptionsError, for_hashmap: bool) + -> (&'a str, Option<&'a str>) { + let mut add_err = || err.issues.push(CLIError::InvalidKeyValueSyntax(kv.to_string(),for_hashmap)); + match kv.find('=') { + None => { + add_err(); + return (kv, None) + }, + Some(pos) => { + let key = &kv[..pos]; + if kv.len() <= pos + 1 { + add_err(); + return (key, Some("")) + } + (key, Some(&kv[pos+1..])) + } + } +} + +pub fn calltype_from_str(name: &str, valid_protocols: Vec, err: &mut InvalidOptionsError) -> CallType { + CallType::Upload( + match UploadProtocol::from_str(name) { + Ok(up) => up, + Err(msg) => { + err.issues.push(CLIError::InvalidUploadProtocol(name.to_string(), valid_protocols)); + UploadProtocol::Simple + } + }) +} + +pub fn input_file_from_opts(file_path: &str, err: &mut InvalidOptionsError) -> Option { + match fs::File::open(file_path) { + Ok(f) => Some(f), + Err(io_err) => { + err.issues.push(CLIError::Input(InputError::IOError((file_path.to_string(), io_err)))); + None + } + } +} + +pub fn input_mime_from_opts(mime: &str, err: &mut InvalidOptionsError) -> Option { + match mime.parse() { + Ok(m) => Some(m), + Err(_) => { + err.issues.push(CLIError::Input(InputError::Mime(mime.to_string()))); + None + } + } +} + +pub fn writer_from_opts(arg: Option<&str>) -> Result, io::Error> { + let f = arg.unwrap_or("-"); + match f { + "-" => Ok(Box::new(stdout())), + _ => match fs::OpenOptions::new().create(true).write(true).open(f) { + Ok(f) => Ok(Box::new(f)), + Err(io_err) => Err(io_err), + } + } +} + + +pub fn arg_from_str<'a, T>(arg: &str, err: &mut InvalidOptionsError, + arg_name: &'a str, + arg_type: &'a str) -> T + where T: FromStr + Default, + ::Err: fmt::Display { + match FromStr::from_str(arg) { + Err(perr) => { + err.issues.push( + CLIError::ParseError(arg_name.to_owned(), arg_type.to_owned(), arg.to_string(), format!("{}", perr)) + ); + Default::default() + }, + Ok(v) => v, + } +} + +pub struct JsonTokenStorage { + pub program_name: &'static str, + pub db_dir: String, +} + +impl JsonTokenStorage { + fn path(&self, scope_hash: u64) -> PathBuf { + Path::new(&self.db_dir).join(&format!("{}-token-{}.json", self.program_name, scope_hash)) + } +} + +impl TokenStorage for JsonTokenStorage { + type Error = json::Error; + + // NOTE: logging might be interesting, currently we swallow all errors + fn set(&mut self, scope_hash: u64, _: &Vec<&str>, token: Option) -> Result<(), json::Error> { + match token { + None => { + match fs::remove_file(self.path(scope_hash)) { + Err(err) => + match err.kind() { + io::ErrorKind::NotFound => Ok(()), + _ => Err(json::Error::IoError(err)) + }, + Ok(_) => Ok(()), + } + } + Some(token) => { + match fs::OpenOptions::new().create(true).write(true).open(&self.path(scope_hash)) { + Ok(mut f) => { + match json::to_writer_pretty(&mut f, &token) { + Ok(_) => Ok(()), + Err(serde_err) => Err(serde_err), + } + }, + Err(io_err) => Err(json::Error::IoError(io_err)) + } + } + } + } + + fn get(&self, scope_hash: u64, _: &Vec<&str>) -> Result, json::Error> { + match fs::File::open(&self.path(scope_hash)) { + Ok(mut f) => { + match json::de::from_reader(f) { + Ok(token) => Ok(Some(token)), + Err(err) => Err(err), + } + }, + Err(io_err) => { + match io_err.kind() { + io::ErrorKind::NotFound => Ok(None), + _ => Err(json::Error::IoError(io_err)) + } + } + } + } +} + + +#[derive(Debug)] +pub enum ApplicationSecretError { + DecoderError((String, json::Error)), + FormatError(String), +} + +impl fmt::Display for ApplicationSecretError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + ApplicationSecretError::DecoderError((ref path, ref err)) + => writeln!(f, "Could not decode file at '{}' with error: {}.", + path, err), + ApplicationSecretError::FormatError(ref path) + => writeln!(f, "'installed' field is unset in secret file at '{}'.", + path), + } + } +} + +#[derive(Debug)] +pub enum ConfigurationError { + DirectoryCreationFailed((String, io::Error)), + DirectoryUnset, + HomeExpansionFailed(String), + Secret(ApplicationSecretError), + IOError((String, io::Error)), +} + +impl fmt::Display for ConfigurationError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + ConfigurationError::DirectoryCreationFailed((ref dir, ref err)) + => writeln!(f, "Directory '{}' could not be created with error: {}.", dir, err), + ConfigurationError::DirectoryUnset + => writeln!(f, "--config-dir was unset or empty."), + ConfigurationError::HomeExpansionFailed(ref dir) + => writeln!(f, "Couldn't find HOME directory of current user, failed to expand '{}'.", dir), + ConfigurationError::Secret(ref err) + => writeln!(f, "Secret -> {}", err), + ConfigurationError::IOError((ref path, ref err)) + => writeln!(f, "IO operation failed on path '{}' with error: {}.", path, err), + } + } +} + +#[derive(Debug)] +pub enum InputError { + IOError((String, io::Error)), + Mime(String), +} + +impl fmt::Display for InputError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + InputError::IOError((ref file_path, ref io_err)) + => writeln!(f, "Failed to open '{}' for reading with error: {}.", file_path, io_err), + InputError::Mime(ref mime) + => writeln!(f, "'{}' is not a known mime-type.", mime), + } + } +} + +#[derive(Debug)] +pub enum FieldError { + PopOnEmpty(String), + TrailingFieldSep(String), + Unknown(String, Option, Option), + Duplicate(String), + Empty, +} + + +impl fmt::Display for FieldError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + FieldError::PopOnEmpty(ref field) + => writeln!(f, "'{}': Cannot move up on empty field cursor.", field), + FieldError::TrailingFieldSep(ref field) + => writeln!(f, "'{}': Single field separator may not be last character.", field), + FieldError::Unknown(ref field, ref suggestion, ref value) => { + let suffix = + match *suggestion { + Some(ref s) => { + let kv = + match *value { + Some(ref v) => format!("{}={}", s, v), + None => s.clone(), + }; + format!(" Did you mean '{}' ?", kv) + }, + None => String::new(), + }; + writeln!(f, "Field '{}' does not exist.{}", field, suffix) + }, + FieldError::Duplicate(ref cursor) + => writeln!(f, "Value at '{}' was already set", cursor), + FieldError::Empty + => writeln!(f, "Field names must not be empty."), + } + } +} + + +#[derive(Debug)] +pub enum CLIError { + Configuration(ConfigurationError), + ParseError(String, String, String, String), + UnknownParameter(String, Vec<&'static str>), + InvalidUploadProtocol(String, Vec), + InvalidKeyValueSyntax(String, bool), + Input(InputError), + Field(FieldError), + MissingCommandError, + MissingMethodError(String), +} + +impl fmt::Display for CLIError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + CLIError::Configuration(ref err) => write!(f, "Configuration -> {}", err), + CLIError::Input(ref err) => write!(f, "Input -> {}", err), + CLIError::Field(ref err) => write!(f, "Field -> {}", err), + CLIError::InvalidUploadProtocol(ref proto_name, ref valid_names) + => writeln!(f, "'{}' is not a valid upload protocol. Choose from one of {}.", proto_name, valid_names.join(", ")), + CLIError::ParseError(ref arg_name, ref type_name, ref value, ref err_desc) + => writeln!(f, "Failed to parse argument '{}' with value '{}' as {} with error: {}.", + arg_name, value, type_name, err_desc), + CLIError::UnknownParameter(ref param_name, ref possible_values) => { + let mut suffix = + match did_you_mean(param_name, &possible_values) { + Some(v) => format!(" Did you mean '{}' ?", v), + None => String::new(), + }; + write!(f, "Parameter '{}' is unknown.{}\n", param_name, suffix) + }, + CLIError::InvalidKeyValueSyntax(ref kv, is_hashmap) => { + let hashmap_info = if is_hashmap { "hashmap " } else { "" }; + writeln!(f, "'{}' does not match {}pattern =.", kv, hashmap_info) + }, + CLIError::MissingCommandError => writeln!(f, "Please specify the main sub-command."), + CLIError::MissingMethodError(ref cmd) => writeln!(f, "Please specify the method to call on the '{}' command.", cmd), + } + } +} + +#[derive(Debug)] +pub struct InvalidOptionsError { + pub issues: Vec, + pub exit_code: i32, +} + +impl fmt::Display for InvalidOptionsError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + for issue in &self.issues { + try!(issue.fmt(f)); + } + Ok(()) + } +} + +impl InvalidOptionsError { + pub fn single(err: CLIError, exit_code: i32) -> InvalidOptionsError { + InvalidOptionsError { + issues: vec![err], + exit_code: exit_code, + } + } + + pub fn new() -> InvalidOptionsError { + InvalidOptionsError { + issues: Vec::new(), + exit_code: 1, + } + } +} + +pub fn assure_config_dir_exists(dir: &str) -> Result { + let trdir = dir.trim(); + if trdir.len() == 0 { + return Err(CLIError::Configuration(ConfigurationError::DirectoryUnset)) + } + + let expanded_config_dir = + if trdir.as_bytes()[0] == b'~' { + match env::var("HOME").ok().or(env::var("UserProfile").ok()) { + None => return Err(CLIError::Configuration(ConfigurationError::HomeExpansionFailed(trdir.to_string()))), + Some(mut user) => { + user.push_str(&trdir[1..]); + user + } + } + } else { + trdir.to_string() + }; + + if let Err(err) = fs::create_dir(&expanded_config_dir) { + if err.kind() != io::ErrorKind::AlreadyExists { + return Err(CLIError::Configuration( + ConfigurationError::DirectoryCreationFailed((expanded_config_dir, err)))) + } + } + + Ok(expanded_config_dir) +} + +pub fn application_secret_from_directory(dir: &str, + secret_basename: &str, + json_console_secret: &str) + -> Result { + let secret_path = Path::new(dir).join(secret_basename); + let secret_str = || secret_path.as_path().to_str().unwrap().to_string(); + let secret_io_error = |io_err: io::Error| { + Err(CLIError::Configuration(ConfigurationError::IOError( + (secret_str(), io_err) + ))) + }; + + for _ in 0..2 { + match fs::File::open(&secret_path) { + Err(mut err) => { + if err.kind() == io::ErrorKind::NotFound { + // Write our built-in one - user may adjust the written file at will + + err = match fs::OpenOptions::new().create(true).write(true).open(&secret_path) { + Err(cfe) => cfe, + Ok(mut f) => { + // Assure we convert 'ugly' json string into pretty one + let console_secret: ConsoleApplicationSecret + = json::from_str(json_console_secret).unwrap(); + match json::to_writer_pretty(&mut f, &console_secret) { + Err(serde_err) => match serde_err { + json::Error::IoError(err) => err, + _ => panic!("Unexpected serde error: {:#?}", serde_err) + }, + Ok(_) => continue, + } + } + }; + // fall through to IO error handling + } + return secret_io_error(err) + }, + Ok(mut f) => { + match json::de::from_reader::<_, ConsoleApplicationSecret>(f) { + Err(json::Error::IoError(err)) => + return secret_io_error(err), + Err(json_err) => + return Err(CLIError::Configuration( + ConfigurationError::Secret( + ApplicationSecretError::DecoderError( + (secret_str(), json_err) + )))), + Ok(console_secret) => + match console_secret.installed { + Some(secret) => return Ok(secret), + None => return Err( + CLIError::Configuration( + ConfigurationError::Secret( + ApplicationSecretError::FormatError(secret_str()) + ))) + }, + } + } + } + } + unreachable!(); +} diff --git a/gen/proximitybeacon1_beta1-cli/src/main.rs b/gen/proximitybeacon1_beta1-cli/src/main.rs new file mode 100644 index 0000000000..e30e62fc37 --- /dev/null +++ b/gen/proximitybeacon1_beta1-cli/src/main.rs @@ -0,0 +1,1484 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/cli/main.rs.mako' +// DO NOT EDIT ! +#![allow(unused_variables, unused_imports, dead_code, unused_mut)] + +#[macro_use] +extern crate clap; +extern crate yup_oauth2 as oauth2; +extern crate yup_hyper_mock as mock; +extern crate serde; +extern crate serde_json; +extern crate hyper; +extern crate mime; +extern crate strsim; +extern crate google_proximitybeacon1_beta1 as api; + +use std::env; +use std::io::{self, Write}; +use clap::{App, SubCommand, Arg}; + +mod cmn; + +use cmn::{InvalidOptionsError, CLIError, JsonTokenStorage, arg_from_str, writer_from_opts, parse_kv_arg, + input_file_from_opts, input_mime_from_opts, FieldCursor, FieldError, CallType, UploadProtocol, + calltype_from_str, remove_json_null_values, ComplexType, JsonType, JsonTypeInfo}; + +use std::default::Default; +use std::str::FromStr; + +use oauth2::{Authenticator, DefaultAuthenticatorDelegate}; +use serde_json as json; +use clap::ArgMatches; + +enum DoitError { + IoError(String, io::Error), + ApiError(api::Error), +} + +struct Engine<'n, 'a> { + opt: ArgMatches<'n, 'a>, + hub: api::Proximitybeacon>, + gp: Vec<&'static str>, + gpm: Vec<(&'static str, &'static str)>, +} + + +impl<'n, 'a> Engine<'n, 'a> { + fn _beaconinfo_getforobserved(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "namespaced-types" => Some(("namespacedTypes", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["namespaced-types"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::GetInfoForObservedBeaconsRequest = json::value::from_value(object).unwrap(); + let mut call = self.hub.beaconinfo().getforobserved(request); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _beacons_activate(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.beacons().activate(opt.value_of("beacon-name").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _beacons_attachments_batch_delete(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.beacons().attachments_batch_delete(opt.value_of("beacon-name").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "namespaced-type" => { + call = call.namespaced_type(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["namespaced-type"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _beacons_attachments_create(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "data" => Some(("data", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "attachment-name" => Some(("attachmentName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "namespaced-type" => Some(("namespacedType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["attachment-name", "data", "namespaced-type"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::BeaconAttachment = json::value::from_value(object).unwrap(); + let mut call = self.hub.beacons().attachments_create(request, opt.value_of("beacon-name").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _beacons_attachments_delete(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.beacons().attachments_delete(opt.value_of("attachment-name").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _beacons_attachments_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.beacons().attachments_list(opt.value_of("beacon-name").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "namespaced-type" => { + call = call.namespaced_type(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["namespaced-type"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _beacons_deactivate(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.beacons().deactivate(opt.value_of("beacon-name").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _beacons_decommission(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.beacons().decommission(opt.value_of("beacon-name").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _beacons_diagnostics_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.beacons().diagnostics_list(opt.value_of("beacon-name").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "page-size" => { + call = call.page_size(arg_from_str(value.unwrap_or("-0"), err, "page-size", "integer")); + }, + "alert-filter" => { + call = call.alert_filter(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["page-token", "alert-filter", "page-size"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _beacons_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.beacons().get(opt.value_of("beacon-name").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _beacons_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.beacons().list(); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "q" => { + call = call.q(value.unwrap_or("")); + }, + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "page-size" => { + call = call.page_size(arg_from_str(value.unwrap_or("-0"), err, "page-size", "integer")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["q", "page-token", "page-size"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _beacons_register(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "status" => Some(("status", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "description" => Some(("description", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "indoor-level.name" => Some(("indoorLevel.name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "lat-lng.latitude" => Some(("latLng.latitude", JsonTypeInfo { jtype: JsonType::Float, ctype: ComplexType::Pod })), + "lat-lng.longitude" => Some(("latLng.longitude", JsonTypeInfo { jtype: JsonType::Float, ctype: ComplexType::Pod })), + "place-id" => Some(("placeId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertised-id.type" => Some(("advertisedId.type", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertised-id.id" => Some(("advertisedId.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "beacon-name" => Some(("beaconName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "expected-stability" => Some(("expectedStability", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "properties" => Some(("properties", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Map })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["advertised-id", "beacon-name", "description", "expected-stability", "id", "indoor-level", "lat-lng", "latitude", "longitude", "name", "place-id", "properties", "status", "type"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::Beacon = json::value::from_value(object).unwrap(); + let mut call = self.hub.beacons().register(request); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _beacons_update(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "status" => Some(("status", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "description" => Some(("description", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "indoor-level.name" => Some(("indoorLevel.name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "lat-lng.latitude" => Some(("latLng.latitude", JsonTypeInfo { jtype: JsonType::Float, ctype: ComplexType::Pod })), + "lat-lng.longitude" => Some(("latLng.longitude", JsonTypeInfo { jtype: JsonType::Float, ctype: ComplexType::Pod })), + "place-id" => Some(("placeId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertised-id.type" => Some(("advertisedId.type", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "advertised-id.id" => Some(("advertisedId.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "beacon-name" => Some(("beaconName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "expected-stability" => Some(("expectedStability", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "properties" => Some(("properties", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Map })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["advertised-id", "beacon-name", "description", "expected-stability", "id", "indoor-level", "lat-lng", "latitude", "longitude", "name", "place-id", "properties", "status", "type"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::Beacon = json::value::from_value(object).unwrap(); + let mut call = self.hub.beacons().update(request, opt.value_of("beacon-name").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _namespaces_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.namespaces().list(); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _doit(&self, dry_run: bool) -> Result, Option> { + let mut err = InvalidOptionsError::new(); + let mut call_result: Result<(), DoitError> = Ok(()); + let mut err_opt: Option = None; + match self.opt.subcommand() { + ("beaconinfo", Some(opt)) => { + match opt.subcommand() { + ("getforobserved", Some(opt)) => { + call_result = self._beaconinfo_getforobserved(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("beaconinfo".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("beacons", Some(opt)) => { + match opt.subcommand() { + ("activate", Some(opt)) => { + call_result = self._beacons_activate(opt, dry_run, &mut err); + }, + ("attachments-batch-delete", Some(opt)) => { + call_result = self._beacons_attachments_batch_delete(opt, dry_run, &mut err); + }, + ("attachments-create", Some(opt)) => { + call_result = self._beacons_attachments_create(opt, dry_run, &mut err); + }, + ("attachments-delete", Some(opt)) => { + call_result = self._beacons_attachments_delete(opt, dry_run, &mut err); + }, + ("attachments-list", Some(opt)) => { + call_result = self._beacons_attachments_list(opt, dry_run, &mut err); + }, + ("deactivate", Some(opt)) => { + call_result = self._beacons_deactivate(opt, dry_run, &mut err); + }, + ("decommission", Some(opt)) => { + call_result = self._beacons_decommission(opt, dry_run, &mut err); + }, + ("diagnostics-list", Some(opt)) => { + call_result = self._beacons_diagnostics_list(opt, dry_run, &mut err); + }, + ("get", Some(opt)) => { + call_result = self._beacons_get(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._beacons_list(opt, dry_run, &mut err); + }, + ("register", Some(opt)) => { + call_result = self._beacons_register(opt, dry_run, &mut err); + }, + ("update", Some(opt)) => { + call_result = self._beacons_update(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("beacons".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("namespaces", Some(opt)) => { + match opt.subcommand() { + ("list", Some(opt)) => { + call_result = self._namespaces_list(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("namespaces".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + _ => { + err.issues.push(CLIError::MissingCommandError); + writeln!(io::stderr(), "{}\n", self.opt.usage()).ok(); + } + } + + if dry_run { + if err.issues.len() > 0 { + err_opt = Some(err); + } + Err(err_opt) + } else { + Ok(call_result) + } + } + + // Please note that this call will fail if any part of the opt can't be handled + fn new(opt: ArgMatches<'a, 'n>) -> Result, InvalidOptionsError> { + let (config_dir, secret) = { + let config_dir = match cmn::assure_config_dir_exists(opt.value_of("folder").unwrap_or("~/.google-service-cli")) { + Err(e) => return Err(InvalidOptionsError::single(e, 3)), + Ok(p) => p, + }; + + match cmn::application_secret_from_directory(&config_dir, "proximitybeacon1-beta1-secret.json", + "{\"installed\":{\"auth_uri\":\"https://accounts.google.com/o/oauth2/auth\",\"client_secret\":\"hCsslbCUyfehWMmbkG8vTYxG\",\"token_uri\":\"https://accounts.google.com/o/oauth2/token\",\"client_email\":\"\",\"redirect_uris\":[\"urn:ietf:wg:oauth:2.0:oob\",\"oob\"],\"client_x509_cert_url\":\"\",\"client_id\":\"620010449518-9ngf7o4dhs0dka470npqvor6dc5lqb9b.apps.googleusercontent.com\",\"auth_provider_x509_cert_url\":\"https://www.googleapis.com/oauth2/v1/certs\"}}") { + Ok(secret) => (config_dir, secret), + Err(e) => return Err(InvalidOptionsError::single(e, 4)) + } + }; + + let auth = Authenticator::new( &secret, DefaultAuthenticatorDelegate, + if opt.is_present("debug-auth") { + hyper::Client::with_connector(mock::TeeConnector { + connector: hyper::net::HttpsConnector::::default() + }) + } else { + hyper::Client::new() + }, + JsonTokenStorage { + program_name: "proximitybeacon1-beta1", + db_dir: config_dir.clone(), + }, None); + + let client = + if opt.is_present("debug") { + hyper::Client::with_connector(mock::TeeConnector { + connector: hyper::net::HttpsConnector::::default() + }) + } else { + hyper::Client::new() + }; + let engine = Engine { + opt: opt, + hub: api::Proximitybeacon::new(client, auth), + gp: vec!["$-xgafv", "access-token", "alt", "bearer-token", "callback", "fields", "key", "oauth-token", "pp", "pretty-print", "quota-user", "upload-type", "upload-protocol"], + gpm: vec![ + ("$-xgafv", "$.xgafv"), + ("access-token", "access_token"), + ("bearer-token", "bearer_token"), + ("oauth-token", "oauth_token"), + ("pretty-print", "prettyPrint"), + ("quota-user", "quotaUser"), + ("upload-type", "uploadType"), + ("upload-protocol", "upload_protocol"), + ] + }; + + match engine._doit(true) { + Err(Some(err)) => Err(err), + Err(None) => Ok(engine), + Ok(_) => unreachable!(), + } + } + + fn doit(&self) -> Result<(), DoitError> { + match self._doit(false) { + Ok(res) => res, + Err(_) => unreachable!(), + } + } +} + +fn main() { + let mut exit_status = 0i32; + let arg_data = [ + ("beaconinfo", "methods: 'getforobserved'", vec![ + ("getforobserved", + Some(r##"Given one or more beacon observations, returns any beacon information and attachments accessible to your application."##), + "Details at http://byron.github.io/google-apis-rs/google_proximitybeacon1_beta1_cli/beaconinfo_getforobserved", + vec![ + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("beacons", "methods: 'activate', 'attachments-batch-delete', 'attachments-create', 'attachments-delete', 'attachments-list', 'deactivate', 'decommission', 'diagnostics-list', 'get', 'list', 'register' and 'update'", vec![ + ("activate", + Some(r##"(Re)activates a beacon. A beacon that is active will return information and attachment data when queried via `beaconinfo.getforobserved`. Calling this method on an already active beacon will do nothing (but will return a successful response code)."##), + "Details at http://byron.github.io/google-apis-rs/google_proximitybeacon1_beta1_cli/beacons_activate", + vec![ + (Some(r##"beacon-name"##), + None, + Some(r##"The beacon to activate. Required."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("attachments-batch-delete", + Some(r##"Deletes multiple attachments on a given beacon. This operation is permanent and cannot be undone. You can optionally specify `namespacedType` to choose which attachments should be deleted. If you do not specify `namespacedType`, all your attachments on the given beacon will be deleted. You also may explicitly specify `*/*` to delete all."##), + "Details at http://byron.github.io/google-apis-rs/google_proximitybeacon1_beta1_cli/beacons_attachments-batch-delete", + vec![ + (Some(r##"beacon-name"##), + None, + Some(r##"The beacon whose attachments are to be deleted. Required."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("attachments-create", + Some(r##"Associates the given data with the specified beacon. Attachment data must contain two parts: + - A namespaced type. + - The actual attachment data itself. The namespaced type consists of two parts, the namespace and the type. The namespace must be one of the values returned by the `namespaces` endpoint, while the type can be a string of any characters except for the forward slash (`/`) up to 100 characters in length. Attachment data can be up to 1024 bytes long."##), + "Details at http://byron.github.io/google-apis-rs/google_proximitybeacon1_beta1_cli/beacons_attachments-create", + vec![ + (Some(r##"beacon-name"##), + None, + Some(r##"The beacon on which the attachment should be created. Required."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("attachments-delete", + Some(r##"Deletes the specified attachment for the given beacon. Each attachment has a unique attachment name (`attachmentName`) which is returned when you fetch the attachment data via this API. You specify this with the delete request to control which attachment is removed. This operation cannot be undone."##), + "Details at http://byron.github.io/google-apis-rs/google_proximitybeacon1_beta1_cli/beacons_attachments-delete", + vec![ + (Some(r##"attachment-name"##), + None, + Some(r##"The attachment name (`attachmentName`) of the attachment to remove. For example: `beacons/3!893737abc9/attachments/c5e937-af0-494-959-ec49d12738` Required."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("attachments-list", + Some(r##"Returns the attachments for the specified beacon that match the specified namespaced-type pattern. To control which namespaced types are returned, you add the `namespacedType` query parameter to the request. You must either use `*/*`, to return all attachments, or the namespace must be one of the ones returned from the `namespaces` endpoint."##), + "Details at http://byron.github.io/google-apis-rs/google_proximitybeacon1_beta1_cli/beacons_attachments-list", + vec![ + (Some(r##"beacon-name"##), + None, + Some(r##"The beacon whose attachments are to be fetched. Required."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("deactivate", + Some(r##"Deactivates a beacon. Once deactivated, the API will not return information nor attachment data for the beacon when queried via `beaconinfo.getforobserved`. Calling this method on an already inactive beacon will do nothing (but will return a successful response code)."##), + "Details at http://byron.github.io/google-apis-rs/google_proximitybeacon1_beta1_cli/beacons_deactivate", + vec![ + (Some(r##"beacon-name"##), + None, + Some(r##"The beacon name of this beacon."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("decommission", + Some(r##"Decommissions the specified beacon in the service. This beacon will no longer be returned from `beaconinfo.getforobserved`. This operation is permanent -- you will not be able to re-register a beacon with this ID again."##), + "Details at http://byron.github.io/google-apis-rs/google_proximitybeacon1_beta1_cli/beacons_decommission", + vec![ + (Some(r##"beacon-name"##), + None, + Some(r##"Beacon that should be decommissioned. Required."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("diagnostics-list", + Some(r##"List the diagnostics for a single beacon. You can also list diagnostics for all the beacons owned by your Google Developers Console project by using the beacon name `beacons/-`."##), + "Details at http://byron.github.io/google-apis-rs/google_proximitybeacon1_beta1_cli/beacons_diagnostics-list", + vec![ + (Some(r##"beacon-name"##), + None, + Some(r##"Beacon that the diagnostics are for."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("get", + Some(r##"Returns detailed information about the specified beacon."##), + "Details at http://byron.github.io/google-apis-rs/google_proximitybeacon1_beta1_cli/beacons_get", + vec![ + (Some(r##"beacon-name"##), + None, + Some(r##"Beacon that is requested."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Searches the beacon registry for beacons that match the given search criteria. Only those beacons that the client has permission to list will be returned."##), + "Details at http://byron.github.io/google-apis-rs/google_proximitybeacon1_beta1_cli/beacons_list", + vec![ + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("register", + Some(r##"Registers a previously unregistered beacon given its `advertisedId`. These IDs are unique within the system. An ID can be registered only once."##), + "Details at http://byron.github.io/google-apis-rs/google_proximitybeacon1_beta1_cli/beacons_register", + vec![ + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("update", + Some(r##"Updates the information about the specified beacon. **Any field that you do not populate in the submitted beacon will be permanently erased**, so you should follow the "read, modify, write" pattern to avoid inadvertently destroying data. Changes to the beacon status via this method will be silently ignored. To update beacon status, use the separate methods on this API for (de)activation and decommissioning."##), + "Details at http://byron.github.io/google-apis-rs/google_proximitybeacon1_beta1_cli/beacons_update", + vec![ + (Some(r##"beacon-name"##), + None, + Some(r##"Resource name of this beacon. A beacon name has the format "beacons/N!beaconId" where the beaconId is the base16 ID broadcast by the beacon and N is a code for the beacon's type. Possible values are `3` for Eddystone, `1` for iBeacon, or `5` for AltBeacon. This field must be left empty when registering. After reading a beacon, clients can use the name for future operations."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("namespaces", "methods: 'list'", vec![ + ("list", + Some(r##"Lists all attachment namespaces owned by your Google Developers Console project. Attachment data associated with a beacon must include a namespaced type, and the namespace must be owned by your project."##), + "Details at http://byron.github.io/google-apis-rs/google_proximitybeacon1_beta1_cli/namespaces_list", + vec![ + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ]; + + let mut app = App::new("proximitybeacon1-beta1") + .author("Sebastian Thiel ") + .version("0.3.2+20150729") + .about("This API provides services to register, manage, index, and search beacons.") + .after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_proximitybeacon1_beta1_cli") + .arg(Arg::with_name("folder") + .long("config-dir") + .help("A directory into which we will store our persistent data. Defaults to a user-writable directory that we will create during the first invocation.[default: ~/.google-service-cli") + .multiple(false) + .takes_value(true)) + .arg(Arg::with_name("debug") + .long("debug") + .help("Output all server communication to standard error. `tx` and `rx` are placed into the same stream.") + .multiple(false) + .takes_value(false)) + .arg(Arg::with_name("debug-auth") + .long("debug-auth") + .help("Output all communication related to authentication to standard error. `tx` and `rx` are placed into the same stream.") + .multiple(false) + .takes_value(false)); + + for &(main_command_name, ref about, ref subcommands) in arg_data.iter() { + let mut mcmd = SubCommand::with_name(main_command_name).about(about); + + for &(sub_command_name, ref desc, url_info, ref args) in subcommands { + let mut scmd = SubCommand::with_name(sub_command_name); + if let &Some(desc) = desc { + scmd = scmd.about(desc); + } + scmd = scmd.after_help(url_info); + + for &(ref arg_name, ref flag, ref desc, ref required, ref multi) in args { + let arg_name_str = + match (arg_name, flag) { + (&Some(an), _ ) => an, + (_ , &Some(f)) => f, + _ => unreachable!(), + }; + let mut arg = Arg::with_name(arg_name_str) + .empty_values(false); + if let &Some(short_flag) = flag { + arg = arg.short(short_flag); + } + if let &Some(desc) = desc { + arg = arg.help(desc); + } + if arg_name.is_some() && flag.is_some() { + arg = arg.takes_value(true); + } + if let &Some(required) = required { + arg = arg.required(required); + } + if let &Some(multi) = multi { + arg = arg.multiple(multi); + } + scmd = scmd.arg(arg); + } + mcmd = mcmd.subcommand(scmd); + } + app = app.subcommand(mcmd); + } + + let matches = app.get_matches(); + + let debug = matches.is_present("debug"); + match Engine::new(matches) { + Err(err) => { + exit_status = err.exit_code; + writeln!(io::stderr(), "{}", err).ok(); + }, + Ok(engine) => { + if let Err(doit_err) = engine.doit() { + exit_status = 1; + match doit_err { + DoitError::IoError(path, err) => { + writeln!(io::stderr(), "Failed to open output file '{}': {}", path, err).ok(); + }, + DoitError::ApiError(err) => { + if debug { + writeln!(io::stderr(), "{:#?}", err).ok(); + } else { + writeln!(io::stderr(), "{}", err).ok(); + } + } + } + } + } + } + + std::process::exit(exit_status); +} \ No newline at end of file diff --git a/gen/proximitybeacon1_beta1/Cargo.toml b/gen/proximitybeacon1_beta1/Cargo.toml new file mode 100644 index 0000000000..f3fddaf0dc --- /dev/null +++ b/gen/proximitybeacon1_beta1/Cargo.toml @@ -0,0 +1,29 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-proximitybeacon1_beta1" +version = "0.1.9+20150729" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with proximitybeacon (protocol v1beta1)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/proximitybeacon1_beta1" +homepage = "https://developers.google.com/beacons/proximity/" +documentation = "http://byron.github.io/google-apis-rs/google_proximitybeacon1_beta1" +license = "MIT" +keywords = ["proximitybeacon", "google", "protocol", "web", "api"] +build = "src/build.rs" + + +[dependencies] +hyper = ">= 0.6.8" +mime = "0.1.0" +serde = ">= 0.6.0" +serde_json = ">= 0.6.0" +yup-oauth2 = "*" +url = "*" + +[build-dependencies] +syntex = { version = "*" } +serde_codegen = { version = "*" } + diff --git a/gen/proximitybeacon1_beta1/LICENSE.md b/gen/proximitybeacon1_beta1/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/proximitybeacon1_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/proximitybeacon1_beta1/README.md b/gen/proximitybeacon1_beta1/README.md new file mode 100644 index 0000000000..a760a52f2c --- /dev/null +++ b/gen/proximitybeacon1_beta1/README.md @@ -0,0 +1,191 @@ + +The `google-proximitybeacon1_beta1` library allows access to all features of the *Google proximitybeacon* service. + +This documentation was generated from *proximitybeacon* crate version *0.1.9+20150729*, where *20150729* is the exact revision of the *proximitybeacon:v1beta1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. + +Everything else about the *proximitybeacon* *v1_beta1* API can be found at the +[official documentation site](https://developers.google.com/beacons/proximity/). +# Features + +Handle the following *Resources* with ease from the central [hub](http://byron.github.io/google-apis-rs/google_proximitybeacon1_beta1/struct.Proximitybeacon.html) ... + +* beaconinfo + * [*getforobserved*](http://byron.github.io/google-apis-rs/google_proximitybeacon1_beta1/struct.BeaconinfoGetforobservedCall.html) +* [beacons](http://byron.github.io/google-apis-rs/google_proximitybeacon1_beta1/struct.Beacon.html) + * [*activate*](http://byron.github.io/google-apis-rs/google_proximitybeacon1_beta1/struct.BeaconActivateCall.html), [*attachments batch delete*](http://byron.github.io/google-apis-rs/google_proximitybeacon1_beta1/struct.BeaconAttachmentBatchDeleteCall.html), [*attachments create*](http://byron.github.io/google-apis-rs/google_proximitybeacon1_beta1/struct.BeaconAttachmentCreateCall.html), [*attachments delete*](http://byron.github.io/google-apis-rs/google_proximitybeacon1_beta1/struct.BeaconAttachmentDeleteCall.html), [*attachments list*](http://byron.github.io/google-apis-rs/google_proximitybeacon1_beta1/struct.BeaconAttachmentListCall.html), [*deactivate*](http://byron.github.io/google-apis-rs/google_proximitybeacon1_beta1/struct.BeaconDeactivateCall.html), [*decommission*](http://byron.github.io/google-apis-rs/google_proximitybeacon1_beta1/struct.BeaconDecommissionCall.html), [*diagnostics list*](http://byron.github.io/google-apis-rs/google_proximitybeacon1_beta1/struct.BeaconDiagnosticListCall.html), [*get*](http://byron.github.io/google-apis-rs/google_proximitybeacon1_beta1/struct.BeaconGetCall.html), [*list*](http://byron.github.io/google-apis-rs/google_proximitybeacon1_beta1/struct.BeaconListCall.html), [*register*](http://byron.github.io/google-apis-rs/google_proximitybeacon1_beta1/struct.BeaconRegisterCall.html) and [*update*](http://byron.github.io/google-apis-rs/google_proximitybeacon1_beta1/struct.BeaconUpdateCall.html) +* [namespaces](http://byron.github.io/google-apis-rs/google_proximitybeacon1_beta1/struct.Namespace.html) + * [*list*](http://byron.github.io/google-apis-rs/google_proximitybeacon1_beta1/struct.NamespaceListCall.html) + + + + +# Structure of this Library + +The API is structured into the following primary items: + +* **[Hub](http://byron.github.io/google-apis-rs/google_proximitybeacon1_beta1/struct.Proximitybeacon.html)** + * a central object to maintain state and allow accessing all *Activities* + * creates [*Method Builders*](http://byron.github.io/google-apis-rs/google_proximitybeacon1_beta1/trait.MethodsBuilder.html) which in turn + allow access to individual [*Call Builders*](http://byron.github.io/google-apis-rs/google_proximitybeacon1_beta1/trait.CallBuilder.html) +* **[Resources](http://byron.github.io/google-apis-rs/google_proximitybeacon1_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_proximitybeacon1_beta1/trait.Part.html)** + * a collection of properties + * never directly used in *Activities* +* **[Activities](http://byron.github.io/google-apis-rs/google_proximitybeacon1_beta1/trait.CallBuilder.html)** + * operations to apply to *Resources* + +All *structures* are marked with applicable traits to further categorize them and ease browsing. + +Generally speaking, you can invoke *Activities* like this: + +```Rust,ignore +let r = hub.resource().activity(...).doit() +``` + +Or specifically ... + +```ignore +let r = hub.beacons().attachments_list(...).doit() +let r = hub.beacons().get(...).doit() +let r = hub.beacons().attachments_create(...).doit() +let r = hub.beacons().decommission(...).doit() +let r = hub.beacons().activate(...).doit() +let r = hub.beacons().list(...).doit() +let r = hub.beacons().update(...).doit() +let r = hub.beacons().attachments_delete(...).doit() +let r = hub.beacons().deactivate(...).doit() +let r = hub.beacons().register(...).doit() +let r = hub.beacons().diagnostics_list(...).doit() +let r = hub.beacons().attachments_batch_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-proximitybeacon1_beta1 = "*" +``` + +## A complete example + +```Rust +extern crate hyper; +extern crate yup_oauth2 as oauth2; +extern crate google_proximitybeacon1_beta1 as proximitybeacon1_beta1; +use proximitybeacon1_beta1::{Result, Error}; +use std::default::Default; +use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +use proximitybeacon1_beta1::Proximitybeacon; + +// 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 = Proximitybeacon::new(hyper::Client::new(), auth); +// You can configure optional parameters by calling the respective setters at will, and +// execute the final call using `doit()`. +// Values shown here are possibly random and not representative ! +let result = hub.beacons().diagnostics_list("beaconName") + .page_token("sit") + .page_size(-65) + .alert_filter("sed") + .doit(); + +match result { + Err(e) => match e { + // The Error enum provides details about what exactly happened. + // You can also just use its `Debug`, `Display` or `Error` traits + Error::HttpError(_) + |Error::MissingAPIKey + |Error::MissingToken(_) + |Error::Cancelled + |Error::UploadSizeLimitExceeded(_, _) + |Error::Failure(_) + |Error::BadRequest(_) + |Error::FieldClash(_) + |Error::JsonDecodeError(_, _) => println!("{}", e), + }, + Ok(res) => println!("Success: {:?}", res), +} + +``` +## Handling Errors + +All errors produced by the system are provided either as [Result](http://byron.github.io/google-apis-rs/google_proximitybeacon1_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_proximitybeacon1_beta1/trait.Delegate.html), or the [Authenticator Delegate](http://byron.github.io/google-apis-rs/google_proximitybeacon1_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 Downloads +If a method supports downloads, the response body, which is part of the [Result](http://byron.github.io/google-apis-rs/google_proximitybeacon1_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_proximitybeacon1_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_proximitybeacon1_beta1/trait.Delegate.html) to the +[Method Builder](http://byron.github.io/google-apis-rs/google_proximitybeacon1_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_proximitybeacon1_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_proximitybeacon1_beta1/trait.RequestValue.html) and +[decodable](http://byron.github.io/google-apis-rs/google_proximitybeacon1_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_proximitybeacon1_beta1/trait.Part.html) which are identifiable 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_proximitybeacon1_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_proximitybeacon1_beta1/trait.RequestValue.html) are moved + +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 **proximitybeacon1_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/proximitybeacon1_beta1/src/build.rs b/gen/proximitybeacon1_beta1/src/build.rs new file mode 100644 index 0000000000..6f5f433cf9 --- /dev/null +++ b/gen/proximitybeacon1_beta1/src/build.rs @@ -0,0 +1,16 @@ +extern crate syntex; +extern crate serde_codegen; + +use std::env; +use std::path::Path; + +pub fn main() { + let out_dir = env::var_os("OUT_DIR").unwrap(); + + let src = Path::new("src/lib.rs.in"); + let dst = Path::new(&out_dir).join("lib.rs"); + + let mut registry = syntex::Registry::new(); + serde_codegen::register(&mut registry); + registry.expand("google-proximitybeacon1_beta1", &src, &dst).unwrap(); +} diff --git a/gen/proximitybeacon1_beta1/src/cmn.rs b/gen/proximitybeacon1_beta1/src/cmn.rs new file mode 100644 index 0000000000..0e31353ba3 --- /dev/null +++ b/gen/proximitybeacon1_beta1/src/cmn.rs @@ -0,0 +1,762 @@ +// COPY OF 'src/rust/api/cmn.rs' +// DO NOT EDIT +use std::io::{self, Read, Seek, Cursor, Write, SeekFrom}; +use std; +use std::fmt::{self, Display}; +use std::str::FromStr; +use std::error; +use std::thread::sleep_ms; + +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::h1::LINE_ENDING; +use hyper::method::Method; +use hyper::status::StatusCode; + +use serde_json as json; + +/// 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 {} + +/// Identifies types for building methods of a particular resource type +pub trait MethodsBuilder {} + +/// Identifies types which represent builders for a particular resource method +pub trait CallBuilder {} + +/// Identifies types which can be inserted and deleted. +/// Types with this trait are most commonly used by clients of this API. +pub trait Resource {} + +/// Identifies types which are used in API responses. +pub trait ResponseResult {} + +/// Identifies types which are used in API requests. +pub trait RequestValue {} + +/// Identifies types which are not actually used by the API +/// This might be a bug within the google API schema. +pub trait UnusedType {} + +/// Identifies types which are only used as part of other types, which +/// usually are carrying the `Resource` trait. +pub trait Part {} + +/// 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 {} + +/// 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 +} + +/// A utility to represent detailed errors we might see in case there are BadRequests. +/// The latter happen if the sent parameters or request structures are unsound +#[derive(Deserialize, Serialize, Debug)] +pub struct ErrorResponse { + error: ServerError, +} + +#[derive(Deserialize, Serialize, Debug)] +pub struct ServerError { + errors: Vec, + code: u16, + message: String, +} + +#[derive(Deserialize, Serialize, Debug)] +pub struct ServerMessage { + domain: String, + reason: String, + message: String, + #[serde(rename="locationType")] + location_type: Option, + location: 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 successful. That way, the delegate 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. + /// + /// If you choose to retry after a duration, the duration should be chosen using the + /// [exponential backoff algorithm](http://en.wikipedia.org/wiki/Exponential_backoff). + /// + /// Return retry information. + fn http_error(&mut self, &hyper::Error) -> 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 it as a general information about the + /// impending failure. + /// The given Error provides information about why the token couldn't be acquired in the + /// first place + fn token(&mut self, err: &error::Error) -> Option { + let _ = err; + 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/canceled, 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()`. + /// It will also be called with None after a successful upload, which allows the delegate + /// to forget the URL. That way, we will not attempt to resume an upload that has already + /// finished. + fn store_upload_url(&mut self, url: Option<&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: &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. + /// + /// If you choose to retry after a duration, the duration should be chosen using the + /// [exponential backoff algorithm](http://en.wikipedia.org/wiki/Exponential_backoff). + fn http_failure(&mut self, _: &hyper::client::Response, Option, _: 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 {} + + +#[derive(Debug)] +pub enum Error { + /// The http connection failed + HttpError(hyper::Error), + + /// 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), + + /// Represents information about a request that was not understood by the server. + /// Details are included. + BadRequest(ErrorResponse), + + /// 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(Box), + + /// 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(String, json::Error), + + /// Indicates an HTTP repsonse with a non-success status code + Failure(hyper::client::Response), +} + + +impl Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + Error::HttpError(ref err) => err.fmt(f), + Error::UploadSizeLimitExceeded(ref resource_size, ref max_size) => + writeln!(f, "The media size {} exceeds the maximum allowed upload size of {}" + , resource_size, max_size), + Error::MissingAPIKey => { + (writeln!(f, "The application's API key was not found in the configuration")).ok(); + writeln!(f, "It is used as there are no Scopes defined for this method.") + }, + Error::BadRequest(ref err) => { + try!(writeln!(f, "Bad Requst ({}): {}", err.error.code, err.error.message)); + for err in err.error.errors.iter() { + try!(writeln!(f, " {}: {}, {}{}", + err.domain, + err.message, + err.reason, + match &err.location { + &Some(ref loc) => format!("@{}", loc), + &None => String::new(), + })); + } + Ok(()) + }, + Error::MissingToken(ref err) => + writeln!(f, "Token retrieval failed with error: {}", err), + Error::Cancelled => + writeln!(f, "Operation cancelled by delegate"), + Error::FieldClash(field) => + writeln!(f, "The custom parameter '{}' is already provided natively by the CallBuilder.", field), + Error::JsonDecodeError(ref json_str, ref err) + => writeln!(f, "{}: {}", err, json_str), + Error::Failure(ref response) => + writeln!(f, "Http status indicates failure: {:?}", response), + } + } +} + +impl error::Error for Error { + fn description(&self) -> &str { + match *self { + Error::HttpError(ref err) => err.description(), + Error::JsonDecodeError(_, ref err) => err.description(), + _ => "NO DESCRIPTION POSSIBLE - use `Display.fmt()` instead" + } + } + + fn cause(&self) -> Option<&error::Error> { + match *self { + Error::HttpError(ref err) => err.cause(), + Error::JsonDecodeError(_, ref err) => err.cause(), + _ => None + } + } +} + +/// A universal result type used as return for all calls. +pub type Result = std::result::Result; + +/// 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 + 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 following macro invocation needs to be expanded, as `include!` +// doens't support external macros +// header!{ +// #[doc="The `X-Upload-Content-Type` header."] +// (XUploadContentType, "X-Upload-Content-Type") => [Mime] + +// xupload_content_type { +// test_header!( +// test1, +// vec![b"text/plain"], +// Some(HeaderField( +// vec![Mime(TopLevel::Text, SubLevel::Plain, Vec::new())] +// ))); + +// } +// } + +/// The `X-Upload-Content-Type` header. +/// +/// Generated via rustc --pretty expanded -Z unstable-options, and manually +/// processed to be more readable. +#[derive(PartialEq, Debug, Clone)] +pub struct XUploadContentType(pub Mime); + +impl ::std::ops::Deref for XUploadContentType { + type Target = Mime; + fn deref<'a>(&'a self) -> &'a Mime { &self.0 } +} +impl ::std::ops::DerefMut for XUploadContentType { + fn deref_mut<'a>(&'a mut self) -> &'a mut Mime { &mut self.0 } +} +impl Header for XUploadContentType { + fn header_name() -> &'static str { "X-Upload-Content-Type" } + fn parse_header(raw: &[Vec]) -> hyper::error::Result { + hyper::header::parsing::from_one_raw_str(raw).map(XUploadContentType) + } +} +impl HeaderFormat for XUploadContentType { + fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { + Display::fmt(&**self, f) + } +} +impl Display for XUploadContentType { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Display::fmt(&**self, f) + } +} + +#[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]) -> hyper::error::Result { + Err(hyper::error::Error::Method) + } +} + + +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]) -> hyper::error::Result { + if raw.len() > 0 { + let v = &raw[0]; + if let Ok(s) = std::str::from_utf8(v) { + const PREFIX: &'static str = "bytes "; + if s.starts_with(PREFIX) { + if let Ok(c) = ::from_str(&s[PREFIX.len()..]) { + return Ok(RangeResponseHeader(c)) + } + } + } + } + Err(hyper::error::Error::Method) + } +} + +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, 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, A> ResumableUploadHelper<'a, A> + where A: oauth2::GetToken { + + fn query_transfer_status(&mut self) -> std::result::Result> { + 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, None) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + return Err(Ok(r)) + } + }; + return Ok(h.0.last) + } + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + return Err(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() { + Ok(s) => s, + Err(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 + }; + + self.reader.seek(SeekFrom::Start(start)).unwrap(); + loop { + let request_size = match self.content_length - start { + rs if rs > chunk_size => chunk_size, + rs => rs + }; + + 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 + } + // workaround https://github.com/rust-lang/rust/issues/22252 + let res = 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(); + match res { + 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, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + } + return Some(Ok(res)) + }, + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + return Some(Err(err)) + } + } + } + } +} + +// Copy of src/rust/cli/cmn.rs +// TODO(ST): Allow sharing common code between program types +pub fn remove_json_null_values(value: &mut json::value::Value) { + match *value { + json::value::Value::Object(ref mut map) => { + let mut for_removal = Vec::new(); + + for (key, mut value) in map.iter_mut() { + if value.is_null() { + for_removal.push(key.clone()); + } else { + remove_json_null_values(&mut value); + } + } + + for key in &for_removal { + map.remove(key); + } + } + _ => {} + } +} diff --git a/gen/proximitybeacon1_beta1/src/lib.rs b/gen/proximitybeacon1_beta1/src/lib.rs new file mode 100644 index 0000000000..292eb034b0 --- /dev/null +++ b/gen/proximitybeacon1_beta1/src/lib.rs @@ -0,0 +1,195 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/api/lib.rs.mako' +// DO NOT EDIT ! + +//! This documentation was generated from *proximitybeacon* crate version *0.1.9+20150729*, where *20150729* is the exact revision of the *proximitybeacon:v1beta1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +//! +//! Everything else about the *proximitybeacon* *v1_beta1* API can be found at the +//! [official documentation site](https://developers.google.com/beacons/proximity/). +//! The original source code is [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/proximitybeacon1_beta1). +//! # Features +//! +//! Handle the following *Resources* with ease from the central [hub](struct.Proximitybeacon.html) ... +//! +//! * beaconinfo +//! * [*getforobserved*](struct.BeaconinfoGetforobservedCall.html) +//! * [beacons](struct.Beacon.html) +//! * [*activate*](struct.BeaconActivateCall.html), [*attachments batch delete*](struct.BeaconAttachmentBatchDeleteCall.html), [*attachments create*](struct.BeaconAttachmentCreateCall.html), [*attachments delete*](struct.BeaconAttachmentDeleteCall.html), [*attachments list*](struct.BeaconAttachmentListCall.html), [*deactivate*](struct.BeaconDeactivateCall.html), [*decommission*](struct.BeaconDecommissionCall.html), [*diagnostics list*](struct.BeaconDiagnosticListCall.html), [*get*](struct.BeaconGetCall.html), [*list*](struct.BeaconListCall.html), [*register*](struct.BeaconRegisterCall.html) and [*update*](struct.BeaconUpdateCall.html) +//! * [namespaces](struct.Namespace.html) +//! * [*list*](struct.NamespaceListCall.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.Proximitybeacon.html)** +//! * a central object to maintain state and allow accessing all *Activities* +//! * creates [*Method Builders*](trait.MethodsBuilder.html) which in turn +//! allow access to individual [*Call Builders*](trait.CallBuilder.html) +//! * **[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* +//! +//! All *structures* are marked with applicable traits to further categorize them and ease browsing. +//! +//! Generally speaking, you can invoke *Activities* like this: +//! +//! ```Rust,ignore +//! let r = hub.resource().activity(...).doit() +//! ``` +//! +//! Or specifically ... +//! +//! ```ignore +//! let r = hub.beacons().attachments_list(...).doit() +//! let r = hub.beacons().get(...).doit() +//! let r = hub.beacons().attachments_create(...).doit() +//! let r = hub.beacons().decommission(...).doit() +//! let r = hub.beacons().activate(...).doit() +//! let r = hub.beacons().list(...).doit() +//! let r = hub.beacons().update(...).doit() +//! let r = hub.beacons().attachments_delete(...).doit() +//! let r = hub.beacons().deactivate(...).doit() +//! let r = hub.beacons().register(...).doit() +//! let r = hub.beacons().diagnostics_list(...).doit() +//! let r = hub.beacons().attachments_batch_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-proximitybeacon1_beta1 = "*" +//! ``` +//! +//! ## A complete example +//! +//! ```test_harness,no_run +//! extern crate hyper; +//! extern crate yup_oauth2 as oauth2; +//! extern crate google_proximitybeacon1_beta1 as proximitybeacon1_beta1; +//! use proximitybeacon1_beta1::{Result, Error}; +//! # #[test] fn egal() { +//! use std::default::Default; +//! use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +//! use proximitybeacon1_beta1::Proximitybeacon; +//! +//! // 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 = Proximitybeacon::new(hyper::Client::new(), auth); +//! // You can configure optional parameters by calling the respective setters at will, and +//! // execute the final call using `doit()`. +//! // Values shown here are possibly random and not representative ! +//! let result = hub.beacons().diagnostics_list("beaconName") +//! .page_token("Lorem") +//! .page_size(-21) +//! .alert_filter("duo") +//! .doit(); +//! +//! match result { +//! Err(e) => match e { +//! // The Error enum provides details about what exactly happened. +//! // You can also just use its `Debug`, `Display` or `Error` traits +//! Error::HttpError(_) +//! |Error::MissingAPIKey +//! |Error::MissingToken(_) +//! |Error::Cancelled +//! |Error::UploadSizeLimitExceeded(_, _) +//! |Error::Failure(_) +//! |Error::BadRequest(_) +//! |Error::FieldClash(_) +//! |Error::JsonDecodeError(_, _) => println!("{}", e), +//! }, +//! Ok(res) => println!("Success: {:?}", res), +//! } +//! # } +//! ``` +//! ## 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 Downloads +//! 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 identifiable 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 moved +//! +//! 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 +//! +//! + +// 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)] + +include!(concat!(env!("OUT_DIR"), "/lib.rs")); \ No newline at end of file diff --git a/gen/proximitybeacon1_beta1/src/lib.rs.in b/gen/proximitybeacon1_beta1/src/lib.rs.in new file mode 100644 index 0000000000..f463c7e1e4 --- /dev/null +++ b/gen/proximitybeacon1_beta1/src/lib.rs.in @@ -0,0 +1,4089 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/api/lib.rs.in.mako' +// DO NOT EDIT ! + +extern crate hyper; +extern crate serde; +extern crate serde_json; +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 serde_json as json; +use std::io; +use std::fs; +use std::thread::sleep_ms; + +pub use cmn::{MultiPartReader, ToParts, MethodInfo, Result, Error, CallBuilder, Hub, ReadSeek, Part, + ResponseResult, RequestValue, NestedType, Delegate, DefaultDelegate, MethodsBuilder, + Resource, ErrorResponse, remove_json_null_values}; + + +// ############## +// UTILITIES ### +// ############ + + + + +// ######## +// HUB ### +// ###### + +/// Central instance to access all Proximitybeacon related resource activities +/// +/// # Examples +/// +/// Instantiate a new hub +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate yup_oauth2 as oauth2; +/// extern crate google_proximitybeacon1_beta1 as proximitybeacon1_beta1; +/// use proximitybeacon1_beta1::{Result, Error}; +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use proximitybeacon1_beta1::Proximitybeacon; +/// +/// // 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 = Proximitybeacon::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.beacons().diagnostics_list("beaconName") +/// .page_token("dolores") +/// .page_size(-63) +/// .alert_filter("accusam") +/// .doit(); +/// +/// match result { +/// Err(e) => match e { +/// // The Error enum provides details about what exactly happened. +/// // You can also just use its `Debug`, `Display` or `Error` traits +/// Error::HttpError(_) +/// |Error::MissingAPIKey +/// |Error::MissingToken(_) +/// |Error::Cancelled +/// |Error::UploadSizeLimitExceeded(_, _) +/// |Error::Failure(_) +/// |Error::BadRequest(_) +/// |Error::FieldClash(_) +/// |Error::JsonDecodeError(_, _) => println!("{}", e), +/// }, +/// Ok(res) => println!("Success: {:?}", res), +/// } +/// # } +/// ``` +pub struct Proximitybeacon { + client: RefCell, + auth: RefCell, + _user_agent: String, +} + +impl<'a, C, A> Hub for Proximitybeacon {} + +impl<'a, C, A> Proximitybeacon + where C: BorrowMut, A: oauth2::GetToken { + + pub fn new(client: C, authenticator: A) -> Proximitybeacon { + Proximitybeacon { + client: RefCell::new(client), + auth: RefCell::new(authenticator), + _user_agent: "google-api-rust-client/0.1.9".to_string(), + } + } + + pub fn beaconinfo(&'a self) -> BeaconinfoMethods<'a, C, A> { + BeaconinfoMethods { hub: &self } + } + pub fn beacons(&'a self) -> BeaconMethods<'a, C, A> { + BeaconMethods { hub: &self } + } + pub fn namespaces(&'a self) -> NamespaceMethods<'a, C, A> { + NamespaceMethods { 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.9`. + /// + /// 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 ### +// ########## +/// Project-specific data associated with a beacon. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [attachments create beacons](struct.BeaconAttachmentCreateCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct BeaconAttachment { + /// Resource name of this attachment. Attachment names have the format: beacons/beacon_id/attachments/attachment_id. Leave this empty on creation. + #[serde(rename="attachmentName")] + pub attachment_name: Option, + /// An opaque data container for client-provided data. Must be [base64](http://tools.ietf.org/html/rfc4648#section-4) encoded in HTTP requests, and will be so encoded (with padding) in responses. Required. + pub data: Option, + /// Specifies what kind of attachment this is. Tells a client how to interpret the `data` field. Format is namespace/type. Namespace provides type separation between clients. Type describes the type of `data`, for use by the client when parsing the `data` field. Required. + #[serde(rename="namespacedType")] + pub namespaced_type: Option, +} + +impl RequestValue for BeaconAttachment {} +impl ResponseResult for BeaconAttachment {} + + +/// Represents one beacon observed once. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Observation { + /// The ID advertised by the beacon the client has encountered. Required. + #[serde(rename="advertisedId")] + pub advertised_id: Option, + /// The array of telemetry bytes received from the beacon. The server is responsible for parsing it. This field may frequently be empty, as with a beacon that transmits telemetry only occasionally. + pub telemetry: Option, + /// Time when the beacon was observed. Being sourced from a mobile device, this time may be suspect. + #[serde(rename="timestampMs")] + pub timestamp_ms: Option, +} + +impl Part for Observation {} + + +/// Indoor level, a human-readable string as returned by Google Maps APIs, useful to indicate which floor of a building a beacon is located 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 IndoorLevel { + /// The name of this level. + pub name: Option, +} + +impl Part for IndoorLevel {} + + +/// Response that contains list beacon results and pagination help. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where 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 beacons](struct.BeaconListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ListBeaconsResponse { + /// The beacons that matched the search criteria. + pub beacons: Option>, + /// An opaque pagination token that the client may provide in their next request to retrieve the next page of results. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// Estimate of the total number of beacons matched by the query. Higher values may be less accurate. + #[serde(rename="totalCount")] + pub total_count: Option, +} + +impl ResponseResult for ListBeaconsResponse {} + + +/// Request for beacon and attachment information about beacons that a mobile client has encountered "in the wild". +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [getforobserved beaconinfo](struct.BeaconinfoGetforobservedCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct GetInfoForObservedBeaconsRequest { + /// The beacons that the client has encountered. At least one must be given. + pub observations: Option>, + /// Specifies what kind of attachments to include in the response. When given, the response will include only attachments of the given types. When empty, no attachments will be returned. Must be in the format namespace/type. Accepts `*` to specify all types in all namespaces. Optional. + #[serde(rename="namespacedTypes")] + pub namespaced_types: Option>, +} + +impl RequestValue for GetInfoForObservedBeaconsRequest {} + + +/// An attachment namespace defines read and write access for all the attachments created under it. Each namespace is globally unique, and owned by one project which is the only project that can create attachments under it. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where 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 namespaces](struct.NamespaceListCall.html) (none) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Namespace { + /// Resource name of this namespace. Namespaces names have the format: namespaces/namespace. + #[serde(rename="namespaceName")] + pub namespace_name: Option, + /// Specifies what clients may receive attachments under this namespace via `beaconinfo.getforobserved`. + #[serde(rename="servingVisibility")] + pub serving_visibility: Option, +} + +impl Resource for Namespace {} + + +/// A subset of attachment information served via the `beaconinfo.getforobserved` method, used when your users encounter your beacons. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct AttachmentInfo { + /// An opaque data container for client-provided data. + pub data: Option, + /// Specifies what kind of attachment this is. Tells a client how to interpret the `data` field. Format is namespace/type, for example scrupulous-wombat-12345/welcome-message + #[serde(rename="namespacedType")] + pub namespaced_type: Option, +} + +impl Part for AttachmentInfo {} + + +/// Defines a unique identifier of a beacon as broadcast by the device. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct AdvertisedId { + /// Specifies the identifier type. Required. + #[serde(rename="type")] + pub type_: Option, + /// The actual beacon identifier, as broadcast by the beacon hardware. Must be [base64](http://tools.ietf.org/html/rfc4648#section-4) encoded in HTTP requests, and will be so encoded (with padding) in responses. The base64 encoding should be of the binary byte-stream and not any textual (such as hex) representation thereof. Required. + pub id: Option, +} + +impl Part for AdvertisedId {} + + +/// Diagnostics for a single beacon. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Diagnostics { + /// The date when the battery is expected to be low. If the value is missing then there is no estimate for when the battery will be low. This value is only an estimate, not an exact date. + #[serde(rename="estimatedLowBatteryDate")] + pub estimated_low_battery_date: Option, + /// An unordered list of Alerts that the beacon has. + pub alerts: Option>, + /// Resource name of the beacon. + #[serde(rename="beaconName")] + pub beacon_name: Option, +} + +impl Part for Diagnostics {} + + +/// A subset of beacon information served via the `beaconinfo.getforobserved` method, which you call when users of your app encounter your beacons. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct BeaconInfo { + /// The ID advertised by the beacon. + #[serde(rename="advertisedId")] + pub advertised_id: Option, + /// The name under which the beacon is registered. + #[serde(rename="beaconName")] + pub beacon_name: Option, + /// Free text used to identify or describe the beacon in a registered establishment. For example: "entrance", "room 101", etc. May be empty. + pub description: Option, + /// Attachments matching the type(s) requested. May be empty if no attachment types were requested, or if none matched. + pub attachments: Option>, +} + +impl Part for BeaconInfo {} + + +/// A generic empty message that you can re-use to avoid defining duplicated empty messages in your APIs. A typical example is to use it as the request or the response type of an API method. For instance: service Foo { rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); } The JSON representation for `Empty` is empty JSON object `{}`. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [decommission beacons](struct.BeaconDecommissionCall.html) (response) +/// * [attachments delete beacons](struct.BeaconAttachmentDeleteCall.html) (response) +/// * [deactivate beacons](struct.BeaconDeactivateCall.html) (response) +/// * [activate beacons](struct.BeaconActivateCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Empty; + +impl ResponseResult for Empty {} + + +/// An object representing a latitude/longitude pair. This is expressed as a pair of doubles representing degrees latitude and degrees longitude. Unless specified otherwise, this must conform to the WGS84 standard. Values must be within normalized ranges. Example of normalization code in Python: def NormalizeLongitude(longitude): """Wrapsdecimal degrees longitude to [-180.0, 180.0].""" q, r = divmod(longitude, 360.0) if r > 180.0 or (r == 180.0 and q <= -1.0): return r - 360.0 return r def NormalizeLatLng(latitude, longitude): """Wraps decimal degrees latitude and longitude to [-180.0, 180.0] and [-90.0, 90.0], respectively.""" r = latitude % 360.0 if r = 270.0: return r - 360, NormalizeLongitude(longitude) else: return 180 - r, NormalizeLongitude(longitude + 180.0) assert 180.0 == NormalizeLongitude(180.0) assert -180.0 == NormalizeLongitude(-180.0) assert -179.0 == NormalizeLongitude(181.0) assert (0.0, 0.0) == NormalizeLatLng(360.0, 0.0) assert (0.0, 0.0) == NormalizeLatLng(-360.0, 0.0) assert (85.0, 180.0) == NormalizeLatLng(95.0, 0.0) assert (-85.0, -170.0) == NormalizeLatLng(-95.0, 10.0) assert (90.0, 10.0) == NormalizeLatLng(90.0, 10.0) assert (-90.0, -10.0) == NormalizeLatLng(-90.0, -10.0) assert (0.0, -170.0) == NormalizeLatLng(-180.0, 10.0) assert (0.0, -170.0) == NormalizeLatLng(180.0, 10.0) assert (-90.0, 10.0) == NormalizeLatLng(270.0, 10.0) assert (90.0, 10.0) == NormalizeLatLng(-270.0, 10.0) +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct LatLng { + /// The latitude in degrees. It must be in the range [-90.0, +90.0]. + pub latitude: Option, + /// The longitude in degrees. It must be in the range [-180.0, +180.0]. + pub longitude: Option, +} + +impl Part for LatLng {} + + +/// Response to ListBeaconAttachments that contains the requested attachments. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [attachments list beacons](struct.BeaconAttachmentListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ListBeaconAttachmentsResponse { + /// The attachments that corresponded to the request params. + pub attachments: Option>, +} + +impl ResponseResult for ListBeaconAttachmentsResponse {} + + +/// Response to ListNamespacesRequest that contains all the project's namespaces. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where 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 namespaces](struct.NamespaceListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ListNamespacesResponse { + /// The attachments that corresponded to the request params. + pub namespaces: Option>, +} + +impl ResponseResult for ListNamespacesResponse {} + + +/// Details of a beacon 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*). +/// +/// * [attachments list beacons](struct.BeaconAttachmentListCall.html) (none) +/// * [get beacons](struct.BeaconGetCall.html) (response) +/// * [attachments create beacons](struct.BeaconAttachmentCreateCall.html) (none) +/// * [decommission beacons](struct.BeaconDecommissionCall.html) (none) +/// * [activate beacons](struct.BeaconActivateCall.html) (none) +/// * [list beacons](struct.BeaconListCall.html) (none) +/// * [update beacons](struct.BeaconUpdateCall.html) (request|response) +/// * [attachments delete beacons](struct.BeaconAttachmentDeleteCall.html) (none) +/// * [deactivate beacons](struct.BeaconDeactivateCall.html) (none) +/// * [register beacons](struct.BeaconRegisterCall.html) (request|response) +/// * [diagnostics list beacons](struct.BeaconDiagnosticListCall.html) (none) +/// * [attachments batch delete beacons](struct.BeaconAttachmentBatchDeleteCall.html) (none) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Beacon { + /// Current status of the beacon. Required. + pub status: Option, + /// Free text used to identify and describe the beacon. Maximum length 140 characters. Optional. + pub description: Option, + /// The indoor level information for this beacon, if known. As returned by the Google Maps API. Optional. + #[serde(rename="indoorLevel")] + pub indoor_level: Option, + /// The location of the beacon, expressed as a latitude and longitude pair. This location is given when the beacon is registered or updated. It does not necessarily indicate the actual current location of the beacon. Optional. + #[serde(rename="latLng")] + pub lat_lng: Option, + /// The [Google Places API](/places/place-id) Place ID of the place where the beacon is deployed. This is given when the beacon is registered or updated, not automatically detected in any way. Optional. + #[serde(rename="placeId")] + pub place_id: Option, + /// The identifier of a beacon as advertised by it. This field must be populated when registering. It may be empty when updating a beacon record because it is ignored in updates. + #[serde(rename="advertisedId")] + pub advertised_id: Option, + /// Resource name of this beacon. A beacon name has the format "beacons/N!beaconId" where the beaconId is the base16 ID broadcast by the beacon and N is a code for the beacon's type. Possible values are `3` for Eddystone, `1` for iBeacon, or `5` for AltBeacon. This field must be left empty when registering. After reading a beacon, clients can use the name for future operations. + #[serde(rename="beaconName")] + pub beacon_name: Option, + /// Expected location stability. This is set when the beacon is registered or updated, not automatically detected in any way. Optional. + #[serde(rename="expectedStability")] + pub expected_stability: Option, + /// Properties of the beacon device, for example battery type or firmware version. Optional. + pub properties: Option>, +} + +impl RequestValue for Beacon {} +impl Resource for Beacon {} +impl ResponseResult for Beacon {} + + +/// Information about the requested beacons, optionally including attachment 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*). +/// +/// * [getforobserved beaconinfo](struct.BeaconinfoGetforobservedCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct GetInfoForObservedBeaconsResponse { + /// Public information about beacons. May be empty if the request matched no beacons. + pub beacons: Option>, +} + +impl ResponseResult for GetInfoForObservedBeaconsResponse {} + + +/// Response that contains the requested diagnostics. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [diagnostics list beacons](struct.BeaconDiagnosticListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ListDiagnosticsResponse { + /// Token that can be used for pagination. Returned only if the request matches more beacons than can be returned in this response. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// The diagnostics matching the given request. + pub diagnostics: Option>, +} + +impl ResponseResult for ListDiagnosticsResponse {} + + +/// Represents a whole calendar date, e.g. date of birth. The time of day and time zone are either specified elsewhere or are not significant. The date is relative to the Proleptic Gregorian Calendar. The day may be 0 to represent a year and month where the day is not significant, e.g. credit card expiration date. The year may be 0 to represent a month and day independent of year, e.g. anniversary date. Related types are [google.type.TimeOfDay][] and `google.protobuf.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 Date { + /// Year of date. Must be from 1 to 9,999, or 0 if specifying a date without a year. + pub year: Option, + /// Day of month. Must be from 1 to 31 and valid for the year and month, or 0 if specifying a year/month where the day is not sigificant. + pub day: Option, + /// Month of year of date. Must be from 1 to 12. + pub month: Option, +} + +impl Part for Date {} + + +/// Response for a request to delete attachments. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [attachments batch delete beacons](struct.BeaconAttachmentBatchDeleteCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct DeleteAttachmentsResponse { + /// The number of attachments that were deleted. + #[serde(rename="numDeleted")] + pub num_deleted: Option, +} + +impl ResponseResult for DeleteAttachmentsResponse {} + + + +// ################### +// MethodBuilders ### +// ################# + +/// A builder providing access to all methods supported on *beacon* resources. +/// It is not used directly, but through the `Proximitybeacon` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate yup_oauth2 as oauth2; +/// extern crate google_proximitybeacon1_beta1 as proximitybeacon1_beta1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use proximitybeacon1_beta1::Proximitybeacon; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Proximitybeacon::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `activate(...)`, `attachments_batch_delete(...)`, `attachments_create(...)`, `attachments_delete(...)`, `attachments_list(...)`, `deactivate(...)`, `decommission(...)`, `diagnostics_list(...)`, `get(...)`, `list(...)`, `register(...)` and `update(...)` +/// // to build up your call. +/// let rb = hub.beacons(); +/// # } +/// ``` +pub struct BeaconMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Proximitybeacon, +} + +impl<'a, C, A> MethodsBuilder for BeaconMethods<'a, C, A> {} + +impl<'a, C, A> BeaconMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Returns the attachments for the specified beacon that match the specified namespaced-type pattern. To control which namespaced types are returned, you add the `namespacedType` query parameter to the request. You must either use `*/*`, to return all attachments, or the namespace must be one of the ones returned from the `namespaces` endpoint. + /// + /// # Arguments + /// + /// * `beaconName` - The beacon whose attachments are to be fetched. Required. + pub fn attachments_list(&self, beacon_name: &str) -> BeaconAttachmentListCall<'a, C, A> { + BeaconAttachmentListCall { + hub: self.hub, + _beacon_name: beacon_name.to_string(), + _namespaced_type: Default::default(), + _delegate: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Returns detailed information about the specified beacon. + /// + /// # Arguments + /// + /// * `beaconName` - Beacon that is requested. + pub fn get(&self, beacon_name: &str) -> BeaconGetCall<'a, C, A> { + BeaconGetCall { + hub: self.hub, + _beacon_name: beacon_name.to_string(), + _delegate: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Associates the given data with the specified beacon. Attachment data must contain two parts: + /// - A namespaced type. + /// - The actual attachment data itself. The namespaced type consists of two parts, the namespace and the type. The namespace must be one of the values returned by the `namespaces` endpoint, while the type can be a string of any characters except for the forward slash (`/`) up to 100 characters in length. Attachment data can be up to 1024 bytes long. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `beaconName` - The beacon on which the attachment should be created. Required. + pub fn attachments_create(&self, request: BeaconAttachment, beacon_name: &str) -> BeaconAttachmentCreateCall<'a, C, A> { + BeaconAttachmentCreateCall { + hub: self.hub, + _request: request, + _beacon_name: beacon_name.to_string(), + _delegate: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Decommissions the specified beacon in the service. This beacon will no longer be returned from `beaconinfo.getforobserved`. This operation is permanent -- you will not be able to re-register a beacon with this ID again. + /// + /// # Arguments + /// + /// * `beaconName` - Beacon that should be decommissioned. Required. + pub fn decommission(&self, beacon_name: &str) -> BeaconDecommissionCall<'a, C, A> { + BeaconDecommissionCall { + hub: self.hub, + _beacon_name: beacon_name.to_string(), + _delegate: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// (Re)activates a beacon. A beacon that is active will return information and attachment data when queried via `beaconinfo.getforobserved`. Calling this method on an already active beacon will do nothing (but will return a successful response code). + /// + /// # Arguments + /// + /// * `beaconName` - The beacon to activate. Required. + pub fn activate(&self, beacon_name: &str) -> BeaconActivateCall<'a, C, A> { + BeaconActivateCall { + hub: self.hub, + _beacon_name: beacon_name.to_string(), + _delegate: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Searches the beacon registry for beacons that match the given search criteria. Only those beacons that the client has permission to list will be returned. + pub fn list(&self) -> BeaconListCall<'a, C, A> { + BeaconListCall { + hub: self.hub, + _q: Default::default(), + _page_token: Default::default(), + _page_size: Default::default(), + _delegate: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Updates the information about the specified beacon. **Any field that you do not populate in the submitted beacon will be permanently erased**, so you should follow the "read, modify, write" pattern to avoid inadvertently destroying data. Changes to the beacon status via this method will be silently ignored. To update beacon status, use the separate methods on this API for (de)activation and decommissioning. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `beaconName` - Resource name of this beacon. A beacon name has the format "beacons/N!beaconId" where the beaconId is the base16 ID broadcast by the beacon and N is a code for the beacon's type. Possible values are `3` for Eddystone, `1` for iBeacon, or `5` for AltBeacon. This field must be left empty when registering. After reading a beacon, clients can use the name for future operations. + pub fn update(&self, request: Beacon, beacon_name: &str) -> BeaconUpdateCall<'a, C, A> { + BeaconUpdateCall { + hub: self.hub, + _request: request, + _beacon_name: beacon_name.to_string(), + _delegate: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Deletes the specified attachment for the given beacon. Each attachment has a unique attachment name (`attachmentName`) which is returned when you fetch the attachment data via this API. You specify this with the delete request to control which attachment is removed. This operation cannot be undone. + /// + /// # Arguments + /// + /// * `attachmentName` - The attachment name (`attachmentName`) of the attachment to remove. For example: `beacons/3!893737abc9/attachments/c5e937-af0-494-959-ec49d12738` Required. + pub fn attachments_delete(&self, attachment_name: &str) -> BeaconAttachmentDeleteCall<'a, C, A> { + BeaconAttachmentDeleteCall { + hub: self.hub, + _attachment_name: attachment_name.to_string(), + _delegate: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Deactivates a beacon. Once deactivated, the API will not return information nor attachment data for the beacon when queried via `beaconinfo.getforobserved`. Calling this method on an already inactive beacon will do nothing (but will return a successful response code). + /// + /// # Arguments + /// + /// * `beaconName` - The beacon name of this beacon. + pub fn deactivate(&self, beacon_name: &str) -> BeaconDeactivateCall<'a, C, A> { + BeaconDeactivateCall { + hub: self.hub, + _beacon_name: beacon_name.to_string(), + _delegate: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Registers a previously unregistered beacon given its `advertisedId`. These IDs are unique within the system. An ID can be registered only once. + /// + /// # Arguments + /// + /// * `request` - No description provided. + pub fn register(&self, request: Beacon) -> BeaconRegisterCall<'a, C, A> { + BeaconRegisterCall { + hub: self.hub, + _request: request, + _delegate: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// List the diagnostics for a single beacon. You can also list diagnostics for all the beacons owned by your Google Developers Console project by using the beacon name `beacons/-`. + /// + /// # Arguments + /// + /// * `beaconName` - Beacon that the diagnostics are for. + pub fn diagnostics_list(&self, beacon_name: &str) -> BeaconDiagnosticListCall<'a, C, A> { + BeaconDiagnosticListCall { + hub: self.hub, + _beacon_name: beacon_name.to_string(), + _page_token: Default::default(), + _page_size: Default::default(), + _alert_filter: Default::default(), + _delegate: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Deletes multiple attachments on a given beacon. This operation is permanent and cannot be undone. You can optionally specify `namespacedType` to choose which attachments should be deleted. If you do not specify `namespacedType`, all your attachments on the given beacon will be deleted. You also may explicitly specify `*/*` to delete all. + /// + /// # Arguments + /// + /// * `beaconName` - The beacon whose attachments are to be deleted. Required. + pub fn attachments_batch_delete(&self, beacon_name: &str) -> BeaconAttachmentBatchDeleteCall<'a, C, A> { + BeaconAttachmentBatchDeleteCall { + hub: self.hub, + _beacon_name: beacon_name.to_string(), + _namespaced_type: Default::default(), + _delegate: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *beaconinfo* resources. +/// It is not used directly, but through the `Proximitybeacon` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate yup_oauth2 as oauth2; +/// extern crate google_proximitybeacon1_beta1 as proximitybeacon1_beta1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use proximitybeacon1_beta1::Proximitybeacon; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Proximitybeacon::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `getforobserved(...)` +/// // to build up your call. +/// let rb = hub.beaconinfo(); +/// # } +/// ``` +pub struct BeaconinfoMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Proximitybeacon, +} + +impl<'a, C, A> MethodsBuilder for BeaconinfoMethods<'a, C, A> {} + +impl<'a, C, A> BeaconinfoMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Given one or more beacon observations, returns any beacon information and attachments accessible to your application. + /// + /// # Arguments + /// + /// * `request` - No description provided. + pub fn getforobserved(&self, request: GetInfoForObservedBeaconsRequest) -> BeaconinfoGetforobservedCall<'a, C, A> { + BeaconinfoGetforobservedCall { + hub: self.hub, + _request: request, + _delegate: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *namespace* resources. +/// It is not used directly, but through the `Proximitybeacon` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate yup_oauth2 as oauth2; +/// extern crate google_proximitybeacon1_beta1 as proximitybeacon1_beta1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use proximitybeacon1_beta1::Proximitybeacon; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Proximitybeacon::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.namespaces(); +/// # } +/// ``` +pub struct NamespaceMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Proximitybeacon, +} + +impl<'a, C, A> MethodsBuilder for NamespaceMethods<'a, C, A> {} + +impl<'a, C, A> NamespaceMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Lists all attachment namespaces owned by your Google Developers Console project. Attachment data associated with a beacon must include a namespaced type, and the namespace must be owned by your project. + pub fn list(&self) -> NamespaceListCall<'a, C, A> { + NamespaceListCall { + hub: self.hub, + _delegate: Default::default(), + _additional_params: Default::default(), + } + } +} + + + + + +// ################### +// CallBuilders ### +// ################# + +/// Returns the attachments for the specified beacon that match the specified namespaced-type pattern. To control which namespaced types are returned, you add the `namespacedType` query parameter to the request. You must either use `*/*`, to return all attachments, or the namespace must be one of the ones returned from the `namespaces` endpoint. +/// +/// A builder for the *attachments.list* method supported by a *beacon* resource. +/// It is not used directly, but through a `BeaconMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_proximitybeacon1_beta1 as proximitybeacon1_beta1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use proximitybeacon1_beta1::Proximitybeacon; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Proximitybeacon::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.beacons().attachments_list("beaconName") +/// .namespaced_type("justo") +/// .doit(); +/// # } +/// ``` +pub struct BeaconAttachmentListCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Proximitybeacon, + _beacon_name: String, + _namespaced_type: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, +} + +impl<'a, C, A> CallBuilder for BeaconAttachmentListCall<'a, C, A> {} + +impl<'a, C, A> BeaconAttachmentListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ListBeaconAttachmentsResponse)> { + use url::percent_encoding::{percent_encode, FORM_URLENCODED_ENCODE_SET}; + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "proximitybeacon.beacons.attachments.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("beaconName", self._beacon_name.to_string())); + if let Some(value) = self._namespaced_type { + params.push(("namespacedType", value.to_string())); + } + for &field in ["alt", "beaconName", "namespacedType"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://proximitybeacon.googleapis.com/v1beta1/{+beaconName}/attachments".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 Err(Error::MissingAPIKey) + } + } + + for &(find_this, param_name) in [("{+beaconName}", "beaconName")].iter() { + let mut replace_with = String::new(); + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = value.to_string(); + break; + } + } + if find_this.as_bytes()[1] == '+' as u8 { + replace_with = percent_encode(replace_with.as_bytes(), FORM_URLENCODED_ENCODE_SET); + } + url = url.replace(find_this, &replace_with); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["beaconName"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + 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) + .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_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The beacon whose attachments are to be fetched. Required. + /// + /// Sets the *beacon 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 beacon_name(mut self, new_value: &str) -> BeaconAttachmentListCall<'a, C, A> { + self._beacon_name = new_value.to_string(); + self + } + /// Specifies the namespace and type of attachment to include in response in namespace/type format. Accepts `*/*` to specify "all types in all namespaces". + /// + /// Sets the *namespaced type* query property to the given value. + pub fn namespaced_type(mut self, new_value: &str) -> BeaconAttachmentListCall<'a, C, A> { + self._namespaced_type = Some(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> BeaconAttachmentListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> BeaconAttachmentListCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + +} + + +/// Returns detailed information about the specified beacon. +/// +/// A builder for the *get* method supported by a *beacon* resource. +/// It is not used directly, but through a `BeaconMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_proximitybeacon1_beta1 as proximitybeacon1_beta1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use proximitybeacon1_beta1::Proximitybeacon; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Proximitybeacon::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.beacons().get("beaconName") +/// .doit(); +/// # } +/// ``` +pub struct BeaconGetCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Proximitybeacon, + _beacon_name: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, +} + +impl<'a, C, A> CallBuilder for BeaconGetCall<'a, C, A> {} + +impl<'a, C, A> BeaconGetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Beacon)> { + use url::percent_encoding::{percent_encode, FORM_URLENCODED_ENCODE_SET}; + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "proximitybeacon.beacons.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("beaconName", self._beacon_name.to_string())); + for &field in ["alt", "beaconName"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://proximitybeacon.googleapis.com/v1beta1/{+beaconName}".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 Err(Error::MissingAPIKey) + } + } + + for &(find_this, param_name) in [("{+beaconName}", "beaconName")].iter() { + let mut replace_with = String::new(); + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = value.to_string(); + break; + } + } + if find_this.as_bytes()[1] == '+' as u8 { + replace_with = percent_encode(replace_with.as_bytes(), FORM_URLENCODED_ENCODE_SET); + } + url = url.replace(find_this, &replace_with); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["beaconName"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + 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) + .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_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Beacon that is requested. + /// + /// Sets the *beacon 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 beacon_name(mut self, new_value: &str) -> BeaconGetCall<'a, C, A> { + self._beacon_name = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> BeaconGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> BeaconGetCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + +} + + +/// Associates the given data with the specified beacon. Attachment data must contain two parts: +/// - A namespaced type. +/// - The actual attachment data itself. The namespaced type consists of two parts, the namespace and the type. The namespace must be one of the values returned by the `namespaces` endpoint, while the type can be a string of any characters except for the forward slash (`/`) up to 100 characters in length. Attachment data can be up to 1024 bytes long. +/// +/// A builder for the *attachments.create* method supported by a *beacon* resource. +/// It is not used directly, but through a `BeaconMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_proximitybeacon1_beta1 as proximitybeacon1_beta1; +/// use proximitybeacon1_beta1::BeaconAttachment; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use proximitybeacon1_beta1::Proximitybeacon; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Proximitybeacon::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req = BeaconAttachment::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.beacons().attachments_create(req, "beaconName") +/// .doit(); +/// # } +/// ``` +pub struct BeaconAttachmentCreateCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Proximitybeacon, + _request: BeaconAttachment, + _beacon_name: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, +} + +impl<'a, C, A> CallBuilder for BeaconAttachmentCreateCall<'a, C, A> {} + +impl<'a, C, A> BeaconAttachmentCreateCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, BeaconAttachment)> { + use url::percent_encoding::{percent_encode, FORM_URLENCODED_ENCODE_SET}; + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "proximitybeacon.beacons.attachments.create", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("beaconName", self._beacon_name.to_string())); + for &field in ["alt", "beaconName"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://proximitybeacon.googleapis.com/v1beta1/{+beaconName}/attachments".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 Err(Error::MissingAPIKey) + } + } + + for &(find_this, param_name) in [("{+beaconName}", "beaconName")].iter() { + let mut replace_with = String::new(); + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = value.to_string(); + break; + } + } + if find_this.as_bytes()[1] == '+' as u8 { + replace_with = percent_encode(replace_with.as_bytes(), FORM_URLENCODED_ENCODE_SET); + } + url = url.replace(find_this, &replace_with); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["beaconName"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + 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) + .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_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: BeaconAttachment) -> BeaconAttachmentCreateCall<'a, C, A> { + self._request = new_value; + self + } + /// The beacon on which the attachment should be created. Required. + /// + /// Sets the *beacon 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 beacon_name(mut self, new_value: &str) -> BeaconAttachmentCreateCall<'a, C, A> { + self._beacon_name = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> BeaconAttachmentCreateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> BeaconAttachmentCreateCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + +} + + +/// Decommissions the specified beacon in the service. This beacon will no longer be returned from `beaconinfo.getforobserved`. This operation is permanent -- you will not be able to re-register a beacon with this ID again. +/// +/// A builder for the *decommission* method supported by a *beacon* resource. +/// It is not used directly, but through a `BeaconMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_proximitybeacon1_beta1 as proximitybeacon1_beta1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use proximitybeacon1_beta1::Proximitybeacon; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Proximitybeacon::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.beacons().decommission("beaconName") +/// .doit(); +/// # } +/// ``` +pub struct BeaconDecommissionCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Proximitybeacon, + _beacon_name: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, +} + +impl<'a, C, A> CallBuilder for BeaconDecommissionCall<'a, C, A> {} + +impl<'a, C, A> BeaconDecommissionCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Empty)> { + use url::percent_encoding::{percent_encode, FORM_URLENCODED_ENCODE_SET}; + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "proximitybeacon.beacons.decommission", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("beaconName", self._beacon_name.to_string())); + for &field in ["alt", "beaconName"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://proximitybeacon.googleapis.com/v1beta1/{+beaconName}:decommission".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 Err(Error::MissingAPIKey) + } + } + + for &(find_this, param_name) in [("{+beaconName}", "beaconName")].iter() { + let mut replace_with = String::new(); + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = value.to_string(); + break; + } + } + if find_this.as_bytes()[1] == '+' as u8 { + replace_with = percent_encode(replace_with.as_bytes(), FORM_URLENCODED_ENCODE_SET); + } + url = url.replace(find_this, &replace_with); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["beaconName"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + 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) + .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_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Beacon that should be decommissioned. Required. + /// + /// Sets the *beacon 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 beacon_name(mut self, new_value: &str) -> BeaconDecommissionCall<'a, C, A> { + self._beacon_name = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> BeaconDecommissionCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> BeaconDecommissionCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + +} + + +/// (Re)activates a beacon. A beacon that is active will return information and attachment data when queried via `beaconinfo.getforobserved`. Calling this method on an already active beacon will do nothing (but will return a successful response code). +/// +/// A builder for the *activate* method supported by a *beacon* resource. +/// It is not used directly, but through a `BeaconMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_proximitybeacon1_beta1 as proximitybeacon1_beta1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use proximitybeacon1_beta1::Proximitybeacon; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Proximitybeacon::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.beacons().activate("beaconName") +/// .doit(); +/// # } +/// ``` +pub struct BeaconActivateCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Proximitybeacon, + _beacon_name: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, +} + +impl<'a, C, A> CallBuilder for BeaconActivateCall<'a, C, A> {} + +impl<'a, C, A> BeaconActivateCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Empty)> { + use url::percent_encoding::{percent_encode, FORM_URLENCODED_ENCODE_SET}; + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "proximitybeacon.beacons.activate", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("beaconName", self._beacon_name.to_string())); + for &field in ["alt", "beaconName"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://proximitybeacon.googleapis.com/v1beta1/{+beaconName}:activate".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 Err(Error::MissingAPIKey) + } + } + + for &(find_this, param_name) in [("{+beaconName}", "beaconName")].iter() { + let mut replace_with = String::new(); + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = value.to_string(); + break; + } + } + if find_this.as_bytes()[1] == '+' as u8 { + replace_with = percent_encode(replace_with.as_bytes(), FORM_URLENCODED_ENCODE_SET); + } + url = url.replace(find_this, &replace_with); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["beaconName"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + 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) + .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_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The beacon to activate. Required. + /// + /// Sets the *beacon 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 beacon_name(mut self, new_value: &str) -> BeaconActivateCall<'a, C, A> { + self._beacon_name = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> BeaconActivateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> BeaconActivateCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + +} + + +/// Searches the beacon registry for beacons that match the given search criteria. Only those beacons that the client has permission to list will be returned. +/// +/// A builder for the *list* method supported by a *beacon* resource. +/// It is not used directly, but through a `BeaconMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_proximitybeacon1_beta1 as proximitybeacon1_beta1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use proximitybeacon1_beta1::Proximitybeacon; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Proximitybeacon::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.beacons().list() +/// .q("nonumy") +/// .page_token("dolores") +/// .page_size(-61) +/// .doit(); +/// # } +/// ``` +pub struct BeaconListCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Proximitybeacon, + _q: Option, + _page_token: Option, + _page_size: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, +} + +impl<'a, C, A> CallBuilder for BeaconListCall<'a, C, A> {} + +impl<'a, C, A> BeaconListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ListBeaconsResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "proximitybeacon.beacons.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._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._page_size { + params.push(("pageSize", value.to_string())); + } + for &field in ["alt", "q", "pageToken", "pageSize"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://proximitybeacon.googleapis.com/v1beta1/beacons".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 Err(Error::MissingAPIKey) + } + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + 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) + .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_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Filter query string that supports the following field filters: * `description:""` For example: `description:"Room 3"` Returns beacons whose description matches tokens in the string "Room 3" (not necessarily that exact string). The string must be double-quoted. * `status:` For example: `status:active` Returns beacons whose status matches the given value. Values must be one of the Beacon.Status enum values (case insensitive). Accepts multiple filters which will be combined with OR logic. * `stability:` For example: `stability:mobile` Returns beacons whose expected stability matches the given value. Values must be one of the Beacon.Stability enum values (case insensitive). Accepts multiple filters which will be combined with OR logic. * `place_id:""` For example: `place_id:"ChIJVSZzVR8FdkgRXGmmm6SslKw="` Returns beacons explicitly registered at the given place, expressed as a Place ID obtained from [Google Places API](/places/place-id). Does not match places inside the given place. Does not consider the beacon's actual location (which may be different from its registered place). Accepts multiple filters that will be combined with OR logic. The place ID must be double-quoted. * `registration_time[|=]` For example: `registration_time>=1433116800` Returns beacons whose registration time matches the given filter. Supports the operators: , =. Timestamp must be expressed as an integer number of seconds since midnight January 1, 1970 UTC. Accepts at most two filters that will be combined with AND logic, to support "between" semantics. If more than two are supplied, the latter ones are ignored. * `lat: lng: radius:` For example: `lat:51.1232343 lng:-1.093852 radius:1000` Returns beacons whose registered location is within the given circle. When any of these fields are given, all are required. Latitude and longitude must be decimal degrees between -90.0 and 90.0 and between -180.0 and 180.0 respectively. Radius must be an integer number of meters less than 1,000,000 (1000 km). * `property:"="` For example: `property:"battery-type=CR2032"` Returns beacons which have a property of the given name and value. Supports multiple filters which will be combined with OR logic. The entire name=value string must be double-quoted as one string. * `attachment_type:""` For example: `attachment_type:"my-namespace/my-type"` Returns beacons having at least one attachment of the given namespaced type. Supports "any within this namespace" via the partial wildcard syntax: "my-namespace/*". Supports multiple filters which will be combined with OR logic. The string must be double-quoted. Multiple filters on the same field are combined with OR logic (except registration_time which is combined with AND logic). Multiple filters on different fields are combined with AND logic. Filters should be separated by spaces. As with any HTTP query string parameter, the whole filter expression must be URL-encoded. Example REST request: `GET /v1beta1/beacons?q=status:active%20lat:51.123%20lng:-1.095%20radius:1000` + /// + /// Sets the *q* query property to the given value. + pub fn q(mut self, new_value: &str) -> BeaconListCall<'a, C, A> { + self._q = Some(new_value.to_string()); + self + } + /// A pagination token obtained from a previous request to list beacons. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> BeaconListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// The maximum number of records to return for this request, up to a server-defined upper limit. + /// + /// Sets the *page size* query property to the given value. + pub fn page_size(mut self, new_value: i32) -> BeaconListCall<'a, C, A> { + self._page_size = Some(new_value); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> BeaconListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> BeaconListCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + +} + + +/// Updates the information about the specified beacon. **Any field that you do not populate in the submitted beacon will be permanently erased**, so you should follow the "read, modify, write" pattern to avoid inadvertently destroying data. Changes to the beacon status via this method will be silently ignored. To update beacon status, use the separate methods on this API for (de)activation and decommissioning. +/// +/// A builder for the *update* method supported by a *beacon* resource. +/// It is not used directly, but through a `BeaconMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_proximitybeacon1_beta1 as proximitybeacon1_beta1; +/// use proximitybeacon1_beta1::Beacon; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use proximitybeacon1_beta1::Proximitybeacon; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Proximitybeacon::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req = Beacon::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.beacons().update(req, "beaconName") +/// .doit(); +/// # } +/// ``` +pub struct BeaconUpdateCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Proximitybeacon, + _request: Beacon, + _beacon_name: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, +} + +impl<'a, C, A> CallBuilder for BeaconUpdateCall<'a, C, A> {} + +impl<'a, C, A> BeaconUpdateCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Beacon)> { + use url::percent_encoding::{percent_encode, FORM_URLENCODED_ENCODE_SET}; + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "proximitybeacon.beacons.update", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("beaconName", self._beacon_name.to_string())); + for &field in ["alt", "beaconName"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://proximitybeacon.googleapis.com/v1beta1/{+beaconName}".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 Err(Error::MissingAPIKey) + } + } + + for &(find_this, param_name) in [("{+beaconName}", "beaconName")].iter() { + let mut replace_with = String::new(); + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = value.to_string(); + break; + } + } + if find_this.as_bytes()[1] == '+' as u8 { + replace_with = percent_encode(replace_with.as_bytes(), FORM_URLENCODED_ENCODE_SET); + } + url = url.replace(find_this, &replace_with); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["beaconName"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + 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::Put, &url) + .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_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: Beacon) -> BeaconUpdateCall<'a, C, A> { + self._request = new_value; + self + } + /// Resource name of this beacon. A beacon name has the format "beacons/N!beaconId" where the beaconId is the base16 ID broadcast by the beacon and N is a code for the beacon's type. Possible values are `3` for Eddystone, `1` for iBeacon, or `5` for AltBeacon. This field must be left empty when registering. After reading a beacon, clients can use the name for future operations. + /// + /// Sets the *beacon 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 beacon_name(mut self, new_value: &str) -> BeaconUpdateCall<'a, C, A> { + self._beacon_name = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> BeaconUpdateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> BeaconUpdateCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + +} + + +/// Deletes the specified attachment for the given beacon. Each attachment has a unique attachment name (`attachmentName`) which is returned when you fetch the attachment data via this API. You specify this with the delete request to control which attachment is removed. This operation cannot be undone. +/// +/// A builder for the *attachments.delete* method supported by a *beacon* resource. +/// It is not used directly, but through a `BeaconMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_proximitybeacon1_beta1 as proximitybeacon1_beta1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use proximitybeacon1_beta1::Proximitybeacon; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Proximitybeacon::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.beacons().attachments_delete("attachmentName") +/// .doit(); +/// # } +/// ``` +pub struct BeaconAttachmentDeleteCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Proximitybeacon, + _attachment_name: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, +} + +impl<'a, C, A> CallBuilder for BeaconAttachmentDeleteCall<'a, C, A> {} + +impl<'a, C, A> BeaconAttachmentDeleteCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Empty)> { + use url::percent_encoding::{percent_encode, FORM_URLENCODED_ENCODE_SET}; + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "proximitybeacon.beacons.attachments.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("attachmentName", self._attachment_name.to_string())); + for &field in ["alt", "attachmentName"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://proximitybeacon.googleapis.com/v1beta1/{+attachmentName}".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 Err(Error::MissingAPIKey) + } + } + + for &(find_this, param_name) in [("{+attachmentName}", "attachmentName")].iter() { + let mut replace_with = String::new(); + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = value.to_string(); + break; + } + } + if find_this.as_bytes()[1] == '+' as u8 { + replace_with = percent_encode(replace_with.as_bytes(), FORM_URLENCODED_ENCODE_SET); + } + url = url.replace(find_this, &replace_with); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["attachmentName"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + 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) + .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_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The attachment name (`attachmentName`) of the attachment to remove. For example: `beacons/3!893737abc9/attachments/c5e937-af0-494-959-ec49d12738` Required. + /// + /// Sets the *attachment 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 attachment_name(mut self, new_value: &str) -> BeaconAttachmentDeleteCall<'a, C, A> { + self._attachment_name = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> BeaconAttachmentDeleteCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> BeaconAttachmentDeleteCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + +} + + +/// Deactivates a beacon. Once deactivated, the API will not return information nor attachment data for the beacon when queried via `beaconinfo.getforobserved`. Calling this method on an already inactive beacon will do nothing (but will return a successful response code). +/// +/// A builder for the *deactivate* method supported by a *beacon* resource. +/// It is not used directly, but through a `BeaconMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_proximitybeacon1_beta1 as proximitybeacon1_beta1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use proximitybeacon1_beta1::Proximitybeacon; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Proximitybeacon::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.beacons().deactivate("beaconName") +/// .doit(); +/// # } +/// ``` +pub struct BeaconDeactivateCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Proximitybeacon, + _beacon_name: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, +} + +impl<'a, C, A> CallBuilder for BeaconDeactivateCall<'a, C, A> {} + +impl<'a, C, A> BeaconDeactivateCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Empty)> { + use url::percent_encoding::{percent_encode, FORM_URLENCODED_ENCODE_SET}; + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "proximitybeacon.beacons.deactivate", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("beaconName", self._beacon_name.to_string())); + for &field in ["alt", "beaconName"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://proximitybeacon.googleapis.com/v1beta1/{+beaconName}:deactivate".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 Err(Error::MissingAPIKey) + } + } + + for &(find_this, param_name) in [("{+beaconName}", "beaconName")].iter() { + let mut replace_with = String::new(); + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = value.to_string(); + break; + } + } + if find_this.as_bytes()[1] == '+' as u8 { + replace_with = percent_encode(replace_with.as_bytes(), FORM_URLENCODED_ENCODE_SET); + } + url = url.replace(find_this, &replace_with); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["beaconName"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + 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) + .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_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The beacon name of this beacon. + /// + /// Sets the *beacon 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 beacon_name(mut self, new_value: &str) -> BeaconDeactivateCall<'a, C, A> { + self._beacon_name = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> BeaconDeactivateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> BeaconDeactivateCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + +} + + +/// Registers a previously unregistered beacon given its `advertisedId`. These IDs are unique within the system. An ID can be registered only once. +/// +/// A builder for the *register* method supported by a *beacon* resource. +/// It is not used directly, but through a `BeaconMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_proximitybeacon1_beta1 as proximitybeacon1_beta1; +/// use proximitybeacon1_beta1::Beacon; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use proximitybeacon1_beta1::Proximitybeacon; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Proximitybeacon::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req = Beacon::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.beacons().register(req) +/// .doit(); +/// # } +/// ``` +pub struct BeaconRegisterCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Proximitybeacon, + _request: Beacon, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, +} + +impl<'a, C, A> CallBuilder for BeaconRegisterCall<'a, C, A> {} + +impl<'a, C, A> BeaconRegisterCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Beacon)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "proximitybeacon.beacons.register", + 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 Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://proximitybeacon.googleapis.com/v1beta1/beacons:register".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 Err(Error::MissingAPIKey) + } + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + 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) + .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_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: Beacon) -> BeaconRegisterCall<'a, C, A> { + self._request = new_value; + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> BeaconRegisterCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> BeaconRegisterCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + +} + + +/// List the diagnostics for a single beacon. You can also list diagnostics for all the beacons owned by your Google Developers Console project by using the beacon name `beacons/-`. +/// +/// A builder for the *diagnostics.list* method supported by a *beacon* resource. +/// It is not used directly, but through a `BeaconMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_proximitybeacon1_beta1 as proximitybeacon1_beta1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use proximitybeacon1_beta1::Proximitybeacon; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Proximitybeacon::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.beacons().diagnostics_list("beaconName") +/// .page_token("justo") +/// .page_size(-21) +/// .alert_filter("et") +/// .doit(); +/// # } +/// ``` +pub struct BeaconDiagnosticListCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Proximitybeacon, + _beacon_name: String, + _page_token: Option, + _page_size: Option, + _alert_filter: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, +} + +impl<'a, C, A> CallBuilder for BeaconDiagnosticListCall<'a, C, A> {} + +impl<'a, C, A> BeaconDiagnosticListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ListDiagnosticsResponse)> { + use url::percent_encoding::{percent_encode, FORM_URLENCODED_ENCODE_SET}; + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "proximitybeacon.beacons.diagnostics.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("beaconName", self._beacon_name.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._alert_filter { + params.push(("alertFilter", value.to_string())); + } + for &field in ["alt", "beaconName", "pageToken", "pageSize", "alertFilter"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://proximitybeacon.googleapis.com/v1beta1/{+beaconName}/diagnostics".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 Err(Error::MissingAPIKey) + } + } + + for &(find_this, param_name) in [("{+beaconName}", "beaconName")].iter() { + let mut replace_with = String::new(); + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = value.to_string(); + break; + } + } + if find_this.as_bytes()[1] == '+' as u8 { + replace_with = percent_encode(replace_with.as_bytes(), FORM_URLENCODED_ENCODE_SET); + } + url = url.replace(find_this, &replace_with); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["beaconName"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + 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) + .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_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Beacon that the diagnostics are for. + /// + /// Sets the *beacon 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 beacon_name(mut self, new_value: &str) -> BeaconDiagnosticListCall<'a, C, A> { + self._beacon_name = new_value.to_string(); + self + } + /// Requests results that occur after the `page_token`, obtained from the response to a previous request. Optional. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> BeaconDiagnosticListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Specifies the maximum number of results to return. Defaults to 10. Maximum 1000. Optional. + /// + /// Sets the *page size* query property to the given value. + pub fn page_size(mut self, new_value: i32) -> BeaconDiagnosticListCall<'a, C, A> { + self._page_size = Some(new_value); + self + } + /// Requests only beacons that have the given alert. For example, to find beacons that have low batteries use `alert_filter=LOW_BATTERY`. + /// + /// Sets the *alert filter* query property to the given value. + pub fn alert_filter(mut self, new_value: &str) -> BeaconDiagnosticListCall<'a, C, A> { + self._alert_filter = Some(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> BeaconDiagnosticListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> BeaconDiagnosticListCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + +} + + +/// Deletes multiple attachments on a given beacon. This operation is permanent and cannot be undone. You can optionally specify `namespacedType` to choose which attachments should be deleted. If you do not specify `namespacedType`, all your attachments on the given beacon will be deleted. You also may explicitly specify `*/*` to delete all. +/// +/// A builder for the *attachments.batchDelete* method supported by a *beacon* resource. +/// It is not used directly, but through a `BeaconMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_proximitybeacon1_beta1 as proximitybeacon1_beta1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use proximitybeacon1_beta1::Proximitybeacon; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Proximitybeacon::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.beacons().attachments_batch_delete("beaconName") +/// .namespaced_type("diam") +/// .doit(); +/// # } +/// ``` +pub struct BeaconAttachmentBatchDeleteCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Proximitybeacon, + _beacon_name: String, + _namespaced_type: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, +} + +impl<'a, C, A> CallBuilder for BeaconAttachmentBatchDeleteCall<'a, C, A> {} + +impl<'a, C, A> BeaconAttachmentBatchDeleteCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, DeleteAttachmentsResponse)> { + use url::percent_encoding::{percent_encode, FORM_URLENCODED_ENCODE_SET}; + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "proximitybeacon.beacons.attachments.batchDelete", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("beaconName", self._beacon_name.to_string())); + if let Some(value) = self._namespaced_type { + params.push(("namespacedType", value.to_string())); + } + for &field in ["alt", "beaconName", "namespacedType"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://proximitybeacon.googleapis.com/v1beta1/{+beaconName}/attachments:batchDelete".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 Err(Error::MissingAPIKey) + } + } + + for &(find_this, param_name) in [("{+beaconName}", "beaconName")].iter() { + let mut replace_with = String::new(); + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = value.to_string(); + break; + } + } + if find_this.as_bytes()[1] == '+' as u8 { + replace_with = percent_encode(replace_with.as_bytes(), FORM_URLENCODED_ENCODE_SET); + } + url = url.replace(find_this, &replace_with); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["beaconName"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + 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) + .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_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The beacon whose attachments are to be deleted. Required. + /// + /// Sets the *beacon 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 beacon_name(mut self, new_value: &str) -> BeaconAttachmentBatchDeleteCall<'a, C, A> { + self._beacon_name = new_value.to_string(); + self + } + /// Specifies the namespace and type of attachments to delete in `namespace/type` format. Accepts `*/*` to specify "all types in all namespaces". Optional. + /// + /// Sets the *namespaced type* query property to the given value. + pub fn namespaced_type(mut self, new_value: &str) -> BeaconAttachmentBatchDeleteCall<'a, C, A> { + self._namespaced_type = Some(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> BeaconAttachmentBatchDeleteCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> BeaconAttachmentBatchDeleteCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + +} + + +/// Given one or more beacon observations, returns any beacon information and attachments accessible to your application. +/// +/// A builder for the *getforobserved* method supported by a *beaconinfo* resource. +/// It is not used directly, but through a `BeaconinfoMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_proximitybeacon1_beta1 as proximitybeacon1_beta1; +/// use proximitybeacon1_beta1::GetInfoForObservedBeaconsRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use proximitybeacon1_beta1::Proximitybeacon; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Proximitybeacon::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req = GetInfoForObservedBeaconsRequest::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.beaconinfo().getforobserved(req) +/// .doit(); +/// # } +/// ``` +pub struct BeaconinfoGetforobservedCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Proximitybeacon, + _request: GetInfoForObservedBeaconsRequest, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, +} + +impl<'a, C, A> CallBuilder for BeaconinfoGetforobservedCall<'a, C, A> {} + +impl<'a, C, A> BeaconinfoGetforobservedCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, GetInfoForObservedBeaconsResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "proximitybeacon.beaconinfo.getforobserved", + 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 Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://proximitybeacon.googleapis.com/v1beta1/beaconinfo:getforobserved".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 Err(Error::MissingAPIKey) + } + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + 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) + .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_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: GetInfoForObservedBeaconsRequest) -> BeaconinfoGetforobservedCall<'a, C, A> { + self._request = new_value; + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> BeaconinfoGetforobservedCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> BeaconinfoGetforobservedCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + +} + + +/// Lists all attachment namespaces owned by your Google Developers Console project. Attachment data associated with a beacon must include a namespaced type, and the namespace must be owned by your project. +/// +/// A builder for the *list* method supported by a *namespace* resource. +/// It is not used directly, but through a `NamespaceMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_proximitybeacon1_beta1 as proximitybeacon1_beta1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use proximitybeacon1_beta1::Proximitybeacon; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Proximitybeacon::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.namespaces().list() +/// .doit(); +/// # } +/// ``` +pub struct NamespaceListCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Proximitybeacon, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, +} + +impl<'a, C, A> CallBuilder for NamespaceListCall<'a, C, A> {} + +impl<'a, C, A> NamespaceListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ListNamespacesResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "proximitybeacon.namespaces.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 Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://proximitybeacon.googleapis.com/v1beta1/namespaces".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 Err(Error::MissingAPIKey) + } + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + 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) + .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_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> NamespaceListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> NamespaceListCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + +} + + diff --git a/gen/pubsub1-cli/Cargo.toml b/gen/pubsub1-cli/Cargo.toml new file mode 100644 index 0000000000..11f782e8d6 --- /dev/null +++ b/gen/pubsub1-cli/Cargo.toml @@ -0,0 +1,35 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-pubsub1-cli" +version = "0.3.2+20150526" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with pubsub (protocol v1)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/pubsub1-cli" +homepage = "https://cloud.google.com/pubsub/docs" +documentation = "http://byron.github.io/google-apis-rs/google_pubsub1_cli" +license = "MIT" +keywords = ["pubsub", "google", "cli"] + +[[bin]] +name = "pubsub1" + +[dependencies] +hyper = ">= 0.6.8" +mime = "0.1.0" +serde = ">= 0.6.0" +serde_json = ">= 0.6.0" +yup-oauth2 = "*" +strsim = "*" +yup-hyper-mock = ">=1.0.0" +clap = ">= 1.0.3" + +[build-dependencies] +syntex = { version = "*" } +serde_codegen = { version = "*" } + + +[dependencies.google-pubsub1] +path = "../pubsub1" diff --git a/gen/pubsub1-cli/LICENSE.md b/gen/pubsub1-cli/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/pubsub1-cli/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/pubsub1-cli/README.md b/gen/pubsub1-cli/README.md new file mode 100644 index 0000000000..1879252892 --- /dev/null +++ b/gen/pubsub1-cli/README.md @@ -0,0 +1,132 @@ + +The `pubsub1` command-line interface *(CLI)* allows to use most features of the *Google pubsub* service from the comfort of your terminal. + +By default all output is printed to standard out, but flags can be set to direct it into a file independent of your shell's +capabilities. Errors will be printed to standard error, and cause the program's exit code to be non-zero. + +If data-structures are requested, these will be returned as pretty-printed JSON, to be useful as input to other tools. + +Everything else about the *pubsub* API can be found at the +[official documentation site](https://cloud.google.com/pubsub/docs). + +# Downloads + +You can download the pre-compiled 64bit binaries for the following platforms: + +* ![icon](http://megaicons.net/static/img/icons_sizes/6/140/16/ubuntu-icon.png) [ubuntu](http://dl.byronimo.de/google.rs/cli/0.3.2/ubuntu/pubsub1.tar.gz) +* ![icon](http://hydra-media.cursecdn.com/wow.gamepedia.com/a/a2/Apple-icon-16x16.png?version=25ddd67ac3dd3b634478e3978b76cb74) [osx](http://dl.byronimo.de/google.rs/cli/0.3.2/osx/pubsub1.tar.gz) + +Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/pubsub1-cli). + +# Usage + +This documentation was generated from the *pubsub* API at revision *20150526*. The CLI is at version *0.3.2*. + +```bash +pubsub1 [options] + projects + subscriptions-acknowledge (-r )... [-p ]... [-o ] + subscriptions-create (-r )... [-p ]... [-o ] + subscriptions-delete [-p ]... [-o ] + subscriptions-get [-p ]... [-o ] + subscriptions-get-iam-policy [-p ]... [-o ] + subscriptions-list [-p ]... [-o ] + subscriptions-modify-ack-deadline (-r )... [-p ]... [-o ] + subscriptions-modify-push-config (-r )... [-p ]... [-o ] + subscriptions-pull (-r )... [-p ]... [-o ] + subscriptions-set-iam-policy (-r )... [-p ]... [-o ] + subscriptions-test-iam-permissions (-r )... [-p ]... [-o ] + topics-create (-r )... [-p ]... [-o ] + topics-delete [-p ]... [-o ] + topics-get [-p ]... [-o ] + topics-get-iam-policy [-p ]... [-o ] + topics-list [-p ]... [-o ] + topics-publish (-r )... [-p ]... [-o ] + topics-set-iam-policy (-r )... [-p ]... [-o ] + topics-subscriptions-list [-p ]... [-o ] + topics-test-iam-permissions (-r )... [-p ]... [-o ] + pubsub1 --help + +Configuration: + [--scope ]... + Specify the authentication a method should be executed in. Each scope + requires the user to grant this application permission to use it. + If unset, it defaults to the shortest scope url for a particular method. + --config-dir + A directory into which we will store our persistent data. Defaults to + a user-writable directory that we will create during the first invocation. + [default: ~/.google-service-cli] + --debug + Output all server communication to standard error. `tx` and `rx` are placed + into the same stream. + --debug-auth + Output all communication related to authentication to standard error. `tx` + and `rx` are placed into the same stream. + +``` + +# Configuration + +The program will store all persistent data in the `~/.google-service-cli` directory in *JSON* files prefixed with `pubsub1-`. You can change the directory used to store configuration with the `--config-dir` flag on a per-invocation basis. + +More information about the various kinds of persistent data are given in the following paragraphs. + +# Authentication + +Most APIs require a user to authenticate any request. If this is the case, the [scope][scopes] determines the +set of permissions granted. The granularity of these is usually no more than *read-only* or *full-access*. + +If not set, the system will automatically select the smallest feasible scope, e.g. when invoking a +method that is read-only, it will ask only for a read-only scope. +You may use the `--scope` flag to specify a scope directly. +All applicable scopes are documented in the respective method's CLI documentation. + +The first time a scope is used, the user is asked for permission. Follow the instructions given +by the CLI to grant permissions, or to decline. + +If a scope was authenticated by the user, the respective information will be stored as *JSON* in the configuration +directory, e.g. `~/.google-service-cli/pubsub1-token-.json`. No manual management of these tokens +is necessary. + +To revoke granted authentication, please refer to the [official documentation][revoke-access]. + +# Application Secrets + +In order to allow any application to use Google services, it will need to be registered using the +[Google Developer Console][google-dev-console]. APIs the application may use are then enabled for it +one by one. Most APIs can be used for free and have a daily quota. + +To allow more comfortable usage of the CLI without forcing anyone to register an own application, the CLI +comes with a default application secret that is configured accordingly. This also means that heavy usage +all around the world may deplete the daily quota. + +You can workaround this limitation by putting your own secrets file at this location: +`~/.google-service-cli/pubsub1-secret.json`, assuming that the required *pubsub* API +was enabled for it. Such a secret file can be downloaded in the *Google Developer Console* at +*APIs & auth -> Credentials -> Download JSON* and used as is. + +Learn more about how to setup Google projects and enable APIs using the [official documentation][google-project-new]. + + +# Debugging + +Even though the CLI does its best to provide usable error messages, sometimes it might be desirable to know +what exactly led to a particular issue. This is done by allowing all client-server communication to be +output to standard error *as-is*. + +The `--debug` flag will print all client-server communication to standard error, whereas the `--debug-auth` flag +will cause all communication related to authentication to standard error. +If the `--debug` flag is set, error-results will be debug-printed, possibly yielding more information about the +issue at hand. + +You may consider redirecting standard error into a file for ease of use, e.g. `pubsub1 --debug [options] 2>debug.txt`. + + +[scopes]: https://developers.google.com/+/api/oauth#scopes +[revoke-access]: http://webapps.stackexchange.com/a/30849 +[google-dev-console]: https://console.developers.google.com/ +[google-project-new]: https://developers.google.com/console/help/new/ \ No newline at end of file diff --git a/gen/pubsub1-cli/mkdocs.yml b/gen/pubsub1-cli/mkdocs.yml new file mode 100644 index 0000000000..e23ba98383 --- /dev/null +++ b/gen/pubsub1-cli/mkdocs.yml @@ -0,0 +1,36 @@ +site_name: pubsub v0.3.2+20150526 +site_url: http://byron.github.io/google-apis-rs/google-pubsub1-cli +site_description: Write integrating applications with bcore + +repo_url: https://github.com/Byron/google-apis-rs/tree/master/gen/pubsub1-cli + +docs_dir: docs +site_dir: build_html + +pages: +- ['index.md', 'Home'] +- ['projects_subscriptions-acknowledge.md', 'Projects', 'Subscriptions Acknowledge'] +- ['projects_subscriptions-create.md', 'Projects', 'Subscriptions Create'] +- ['projects_subscriptions-delete.md', 'Projects', 'Subscriptions Delete'] +- ['projects_subscriptions-get.md', 'Projects', 'Subscriptions Get'] +- ['projects_subscriptions-get-iam-policy.md', 'Projects', 'Subscriptions Get Iam Policy'] +- ['projects_subscriptions-list.md', 'Projects', 'Subscriptions List'] +- ['projects_subscriptions-modify-ack-deadline.md', 'Projects', 'Subscriptions Modify Ack Deadline'] +- ['projects_subscriptions-modify-push-config.md', 'Projects', 'Subscriptions Modify Push Config'] +- ['projects_subscriptions-pull.md', 'Projects', 'Subscriptions Pull'] +- ['projects_subscriptions-set-iam-policy.md', 'Projects', 'Subscriptions Set Iam Policy'] +- ['projects_subscriptions-test-iam-permissions.md', 'Projects', 'Subscriptions Test Iam Permissions'] +- ['projects_topics-create.md', 'Projects', 'Topics Create'] +- ['projects_topics-delete.md', 'Projects', 'Topics Delete'] +- ['projects_topics-get.md', 'Projects', 'Topics Get'] +- ['projects_topics-get-iam-policy.md', 'Projects', 'Topics Get Iam Policy'] +- ['projects_topics-list.md', 'Projects', 'Topics List'] +- ['projects_topics-publish.md', 'Projects', 'Topics Publish'] +- ['projects_topics-set-iam-policy.md', 'Projects', 'Topics Set Iam Policy'] +- ['projects_topics-subscriptions-list.md', 'Projects', 'Topics Subscriptions List'] +- ['projects_topics-test-iam-permissions.md', 'Projects', 'Topics Test Iam Permissions'] + +theme: readthedocs + +copyright: Copyright © 2015, `Sebastian Thiel` + diff --git a/gen/pubsub1-cli/src/cmn.rs b/gen/pubsub1-cli/src/cmn.rs new file mode 100644 index 0000000000..8358f156fa --- /dev/null +++ b/gen/pubsub1-cli/src/cmn.rs @@ -0,0 +1,721 @@ +// COPY OF 'src/rust/cli/cmn.rs' +// DO NOT EDIT +use oauth2::{ApplicationSecret, ConsoleApplicationSecret, TokenStorage, Token}; +use serde_json as json; +use serde_json::value::Value; +use mime::Mime; +use clap::{App, SubCommand}; +use strsim; + +use std::fs; +use std::env; +use std::io; +use std::fmt; +use std::path::{Path, PathBuf}; +use std::str::FromStr; +use std::string::ToString; +use std::io::{Write, Read, stdout}; + +use std::default::Default; + +const FIELD_SEP: char = '.'; + + +pub enum ComplexType { + Pod, + Vec, + Map, +} + + // Null, + // Bool(bool), + // I64(i64), + // U64(u64), + // F64(f64), + // String(String), + +pub enum JsonType { + Boolean, + Int, + Uint, + Float, + String, +} + +pub struct JsonTypeInfo { + pub jtype: JsonType, + pub ctype: ComplexType, +} + +// Based on @erickt user comment. Thanks for the idea ! +// Remove all keys whose values are null from given value (changed in place) +pub fn remove_json_null_values(value: &mut Value) { + match *value { + Value::Object(ref mut map) => { + let mut for_removal = Vec::new(); + + for (key, mut value) in map.iter_mut() { + if value.is_null() { + for_removal.push(key.clone()); + } else { + remove_json_null_values(&mut value); + } + } + + for key in &for_removal { + map.remove(key); + } + } + _ => {} + } +} + +fn did_you_mean<'a>(v: &str, possible_values: &[&'a str]) -> Option<&'a str> { + + let mut candidate: Option<(f64, &str)> = None; + for pv in possible_values { + let confidence = strsim::jaro_winkler(v, pv); + if confidence > 0.8 && (candidate.is_none() || (candidate.as_ref().unwrap().0 < confidence)) { + candidate = Some((confidence, pv)); + } + } + match candidate { + None => None, + Some((_, candidate)) => Some(candidate), + } +} + +pub enum CallType { + Upload(UploadProtocol), + Standard, +} + +arg_enum!{ + pub enum UploadProtocol { + Simple, + Resumable + } +} + +impl AsRef for UploadProtocol { + fn as_ref(&self) -> &str { + match *self { + UploadProtocol::Simple => "simple", + UploadProtocol::Resumable => "resumable" + } + } +} + +impl AsRef for CallType { + fn as_ref(&self) -> &str { + match *self { + CallType::Upload(ref proto) => proto.as_ref(), + CallType::Standard => "standard-request" + } + } +} + +#[derive(Clone, Default)] +pub struct FieldCursor(Vec); + +impl ToString for FieldCursor { + fn to_string(&self) -> String { + self.0.join(".") + } +} + +impl From<&'static str> for FieldCursor { + fn from(value: &'static str) -> FieldCursor { + let mut res = FieldCursor::default(); + res.set(value).unwrap(); + res + } +} + +impl FieldCursor { + pub fn set(&mut self, value: &str) -> Result<(), CLIError> { + if value.len() == 0 { + return Err(CLIError::Field(FieldError::Empty)) + } + + let mut first_is_field_sep = false; + let mut char_count: usize = 0; + let mut last_c = FIELD_SEP; + let mut num_conscutive_field_seps = 0; + + let mut field = String::new(); + let mut fields = self.0.clone(); + + let push_field = |fs: &mut Vec, f: &mut String| { + if f.len() > 0 { + fs.push(f.clone()); + f.truncate(0); + } + }; + + for (cid, c) in value.chars().enumerate() { + char_count += 1; + + if c == FIELD_SEP { + if cid == 0 { + first_is_field_sep = true; + } + num_conscutive_field_seps += 1; + if cid > 0 && last_c == FIELD_SEP { + if fields.pop().is_none() { + return Err(CLIError::Field(FieldError::PopOnEmpty(value.to_string()))) + } + } else { + push_field(&mut fields, &mut field); + } + } else { + num_conscutive_field_seps = 0; + if cid == 1 { + if first_is_field_sep { + fields.truncate(0); + } + } + field.push(c); + } + + last_c = c; + } + + push_field(&mut fields, &mut field); + + if char_count == 1 && first_is_field_sep { + fields.truncate(0); + } + if char_count > 1 && num_conscutive_field_seps == 1 { + return Err(CLIError::Field(FieldError::TrailingFieldSep(value.to_string()))) + } + + self.0 = fields; + Ok(()) + } + + pub fn did_you_mean(value: &str, possible_values: &[&str]) -> Option { + if value.len() == 0 { + return None + } + + let mut last_c = FIELD_SEP; + + let mut field = String::new(); + let mut output = String::new(); + + let push_field = |fs: &mut String, f: &mut String| { + if f.len() > 0 { + fs.push_str( + match did_you_mean(&f, possible_values) { + Some(candidate) => candidate, + None => &f, + }); + f.truncate(0); + } + }; + + for (cid, c) in value.chars().enumerate() { + if c == FIELD_SEP { + if last_c != FIELD_SEP { + push_field(&mut output, &mut field); + } + output.push(c); + } else { + field.push(c); + } + + last_c = c; + } + + push_field(&mut output, &mut field); + + if &output == value { + None + } else { + Some(output) + } + } + + pub fn set_json_value(&self, mut object: &mut Value, + value: &str, type_info: JsonTypeInfo, + err: &mut InvalidOptionsError, + orig_cursor: &FieldCursor) { + assert!(self.0.len() > 0); + + for field in &self.0[..self.0.len()-1] { + let tmp = object; + object = + match *tmp { + Value::Object(ref mut mapping) => { + mapping.entry(field.to_owned()).or_insert( + Value::Object(Default::default()) + ) + }, + _ => panic!("We don't expect non-object Values here ...") + }; + } + + match *object { + Value::Object(ref mut mapping) => { + let field = &self.0[self.0.len()-1]; + let to_jval = + |value: &str, jtype: JsonType, err: &mut InvalidOptionsError| + -> Value { + match jtype { + JsonType::Boolean => + Value::Bool(arg_from_str(value, err, &field, "boolean")), + JsonType::Int => + Value::I64(arg_from_str(value, err, &field, "int")), + JsonType::Uint => + Value::U64(arg_from_str(value, err, &field, "uint")), + JsonType::Float => + Value::F64(arg_from_str(value, err, &field, "float")), + JsonType::String => + Value::String(value.to_owned()), + } + }; + + match type_info.ctype { + ComplexType::Pod => { + if mapping.insert(field.to_owned(), to_jval(value, type_info.jtype, err)).is_some() { + err.issues.push(CLIError::Field(FieldError::Duplicate(orig_cursor.to_string()))); + } + }, + ComplexType::Vec => { + match *mapping.entry(field.to_owned()) + .or_insert(Value::Array(Default::default())) { + Value::Array(ref mut values) => values.push(to_jval(value, type_info.jtype, err)), + _ => unreachable!() + } + }, + ComplexType::Map => { + let (key, value) = parse_kv_arg(value, err, true); + let jval = to_jval(value.unwrap_or(""), type_info.jtype, err); + + match *mapping.entry(field.to_owned()) + .or_insert(Value::Object(Default::default())) { + Value::Object(ref mut value_map) => { + if value_map.insert(key.to_owned(), jval).is_some() { + err.issues.push(CLIError::Field(FieldError::Duplicate(orig_cursor.to_string()))); + } + } + _ => unreachable!() + } + } + } + }, + _ => unreachable!() + } + } + + pub fn num_fields(&self) -> usize { + self.0.len() + } +} + +pub fn parse_kv_arg<'a>(kv: &'a str, err: &mut InvalidOptionsError, for_hashmap: bool) + -> (&'a str, Option<&'a str>) { + let mut add_err = || err.issues.push(CLIError::InvalidKeyValueSyntax(kv.to_string(),for_hashmap)); + match kv.find('=') { + None => { + add_err(); + return (kv, None) + }, + Some(pos) => { + let key = &kv[..pos]; + if kv.len() <= pos + 1 { + add_err(); + return (key, Some("")) + } + (key, Some(&kv[pos+1..])) + } + } +} + +pub fn calltype_from_str(name: &str, valid_protocols: Vec, err: &mut InvalidOptionsError) -> CallType { + CallType::Upload( + match UploadProtocol::from_str(name) { + Ok(up) => up, + Err(msg) => { + err.issues.push(CLIError::InvalidUploadProtocol(name.to_string(), valid_protocols)); + UploadProtocol::Simple + } + }) +} + +pub fn input_file_from_opts(file_path: &str, err: &mut InvalidOptionsError) -> Option { + match fs::File::open(file_path) { + Ok(f) => Some(f), + Err(io_err) => { + err.issues.push(CLIError::Input(InputError::IOError((file_path.to_string(), io_err)))); + None + } + } +} + +pub fn input_mime_from_opts(mime: &str, err: &mut InvalidOptionsError) -> Option { + match mime.parse() { + Ok(m) => Some(m), + Err(_) => { + err.issues.push(CLIError::Input(InputError::Mime(mime.to_string()))); + None + } + } +} + +pub fn writer_from_opts(arg: Option<&str>) -> Result, io::Error> { + let f = arg.unwrap_or("-"); + match f { + "-" => Ok(Box::new(stdout())), + _ => match fs::OpenOptions::new().create(true).write(true).open(f) { + Ok(f) => Ok(Box::new(f)), + Err(io_err) => Err(io_err), + } + } +} + + +pub fn arg_from_str<'a, T>(arg: &str, err: &mut InvalidOptionsError, + arg_name: &'a str, + arg_type: &'a str) -> T + where T: FromStr + Default, + ::Err: fmt::Display { + match FromStr::from_str(arg) { + Err(perr) => { + err.issues.push( + CLIError::ParseError(arg_name.to_owned(), arg_type.to_owned(), arg.to_string(), format!("{}", perr)) + ); + Default::default() + }, + Ok(v) => v, + } +} + +pub struct JsonTokenStorage { + pub program_name: &'static str, + pub db_dir: String, +} + +impl JsonTokenStorage { + fn path(&self, scope_hash: u64) -> PathBuf { + Path::new(&self.db_dir).join(&format!("{}-token-{}.json", self.program_name, scope_hash)) + } +} + +impl TokenStorage for JsonTokenStorage { + type Error = json::Error; + + // NOTE: logging might be interesting, currently we swallow all errors + fn set(&mut self, scope_hash: u64, _: &Vec<&str>, token: Option) -> Result<(), json::Error> { + match token { + None => { + match fs::remove_file(self.path(scope_hash)) { + Err(err) => + match err.kind() { + io::ErrorKind::NotFound => Ok(()), + _ => Err(json::Error::IoError(err)) + }, + Ok(_) => Ok(()), + } + } + Some(token) => { + match fs::OpenOptions::new().create(true).write(true).open(&self.path(scope_hash)) { + Ok(mut f) => { + match json::to_writer_pretty(&mut f, &token) { + Ok(_) => Ok(()), + Err(serde_err) => Err(serde_err), + } + }, + Err(io_err) => Err(json::Error::IoError(io_err)) + } + } + } + } + + fn get(&self, scope_hash: u64, _: &Vec<&str>) -> Result, json::Error> { + match fs::File::open(&self.path(scope_hash)) { + Ok(mut f) => { + match json::de::from_reader(f) { + Ok(token) => Ok(Some(token)), + Err(err) => Err(err), + } + }, + Err(io_err) => { + match io_err.kind() { + io::ErrorKind::NotFound => Ok(None), + _ => Err(json::Error::IoError(io_err)) + } + } + } + } +} + + +#[derive(Debug)] +pub enum ApplicationSecretError { + DecoderError((String, json::Error)), + FormatError(String), +} + +impl fmt::Display for ApplicationSecretError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + ApplicationSecretError::DecoderError((ref path, ref err)) + => writeln!(f, "Could not decode file at '{}' with error: {}.", + path, err), + ApplicationSecretError::FormatError(ref path) + => writeln!(f, "'installed' field is unset in secret file at '{}'.", + path), + } + } +} + +#[derive(Debug)] +pub enum ConfigurationError { + DirectoryCreationFailed((String, io::Error)), + DirectoryUnset, + HomeExpansionFailed(String), + Secret(ApplicationSecretError), + IOError((String, io::Error)), +} + +impl fmt::Display for ConfigurationError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + ConfigurationError::DirectoryCreationFailed((ref dir, ref err)) + => writeln!(f, "Directory '{}' could not be created with error: {}.", dir, err), + ConfigurationError::DirectoryUnset + => writeln!(f, "--config-dir was unset or empty."), + ConfigurationError::HomeExpansionFailed(ref dir) + => writeln!(f, "Couldn't find HOME directory of current user, failed to expand '{}'.", dir), + ConfigurationError::Secret(ref err) + => writeln!(f, "Secret -> {}", err), + ConfigurationError::IOError((ref path, ref err)) + => writeln!(f, "IO operation failed on path '{}' with error: {}.", path, err), + } + } +} + +#[derive(Debug)] +pub enum InputError { + IOError((String, io::Error)), + Mime(String), +} + +impl fmt::Display for InputError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + InputError::IOError((ref file_path, ref io_err)) + => writeln!(f, "Failed to open '{}' for reading with error: {}.", file_path, io_err), + InputError::Mime(ref mime) + => writeln!(f, "'{}' is not a known mime-type.", mime), + } + } +} + +#[derive(Debug)] +pub enum FieldError { + PopOnEmpty(String), + TrailingFieldSep(String), + Unknown(String, Option, Option), + Duplicate(String), + Empty, +} + + +impl fmt::Display for FieldError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + FieldError::PopOnEmpty(ref field) + => writeln!(f, "'{}': Cannot move up on empty field cursor.", field), + FieldError::TrailingFieldSep(ref field) + => writeln!(f, "'{}': Single field separator may not be last character.", field), + FieldError::Unknown(ref field, ref suggestion, ref value) => { + let suffix = + match *suggestion { + Some(ref s) => { + let kv = + match *value { + Some(ref v) => format!("{}={}", s, v), + None => s.clone(), + }; + format!(" Did you mean '{}' ?", kv) + }, + None => String::new(), + }; + writeln!(f, "Field '{}' does not exist.{}", field, suffix) + }, + FieldError::Duplicate(ref cursor) + => writeln!(f, "Value at '{}' was already set", cursor), + FieldError::Empty + => writeln!(f, "Field names must not be empty."), + } + } +} + + +#[derive(Debug)] +pub enum CLIError { + Configuration(ConfigurationError), + ParseError(String, String, String, String), + UnknownParameter(String, Vec<&'static str>), + InvalidUploadProtocol(String, Vec), + InvalidKeyValueSyntax(String, bool), + Input(InputError), + Field(FieldError), + MissingCommandError, + MissingMethodError(String), +} + +impl fmt::Display for CLIError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + CLIError::Configuration(ref err) => write!(f, "Configuration -> {}", err), + CLIError::Input(ref err) => write!(f, "Input -> {}", err), + CLIError::Field(ref err) => write!(f, "Field -> {}", err), + CLIError::InvalidUploadProtocol(ref proto_name, ref valid_names) + => writeln!(f, "'{}' is not a valid upload protocol. Choose from one of {}.", proto_name, valid_names.join(", ")), + CLIError::ParseError(ref arg_name, ref type_name, ref value, ref err_desc) + => writeln!(f, "Failed to parse argument '{}' with value '{}' as {} with error: {}.", + arg_name, value, type_name, err_desc), + CLIError::UnknownParameter(ref param_name, ref possible_values) => { + let mut suffix = + match did_you_mean(param_name, &possible_values) { + Some(v) => format!(" Did you mean '{}' ?", v), + None => String::new(), + }; + write!(f, "Parameter '{}' is unknown.{}\n", param_name, suffix) + }, + CLIError::InvalidKeyValueSyntax(ref kv, is_hashmap) => { + let hashmap_info = if is_hashmap { "hashmap " } else { "" }; + writeln!(f, "'{}' does not match {}pattern =.", kv, hashmap_info) + }, + CLIError::MissingCommandError => writeln!(f, "Please specify the main sub-command."), + CLIError::MissingMethodError(ref cmd) => writeln!(f, "Please specify the method to call on the '{}' command.", cmd), + } + } +} + +#[derive(Debug)] +pub struct InvalidOptionsError { + pub issues: Vec, + pub exit_code: i32, +} + +impl fmt::Display for InvalidOptionsError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + for issue in &self.issues { + try!(issue.fmt(f)); + } + Ok(()) + } +} + +impl InvalidOptionsError { + pub fn single(err: CLIError, exit_code: i32) -> InvalidOptionsError { + InvalidOptionsError { + issues: vec![err], + exit_code: exit_code, + } + } + + pub fn new() -> InvalidOptionsError { + InvalidOptionsError { + issues: Vec::new(), + exit_code: 1, + } + } +} + +pub fn assure_config_dir_exists(dir: &str) -> Result { + let trdir = dir.trim(); + if trdir.len() == 0 { + return Err(CLIError::Configuration(ConfigurationError::DirectoryUnset)) + } + + let expanded_config_dir = + if trdir.as_bytes()[0] == b'~' { + match env::var("HOME").ok().or(env::var("UserProfile").ok()) { + None => return Err(CLIError::Configuration(ConfigurationError::HomeExpansionFailed(trdir.to_string()))), + Some(mut user) => { + user.push_str(&trdir[1..]); + user + } + } + } else { + trdir.to_string() + }; + + if let Err(err) = fs::create_dir(&expanded_config_dir) { + if err.kind() != io::ErrorKind::AlreadyExists { + return Err(CLIError::Configuration( + ConfigurationError::DirectoryCreationFailed((expanded_config_dir, err)))) + } + } + + Ok(expanded_config_dir) +} + +pub fn application_secret_from_directory(dir: &str, + secret_basename: &str, + json_console_secret: &str) + -> Result { + let secret_path = Path::new(dir).join(secret_basename); + let secret_str = || secret_path.as_path().to_str().unwrap().to_string(); + let secret_io_error = |io_err: io::Error| { + Err(CLIError::Configuration(ConfigurationError::IOError( + (secret_str(), io_err) + ))) + }; + + for _ in 0..2 { + match fs::File::open(&secret_path) { + Err(mut err) => { + if err.kind() == io::ErrorKind::NotFound { + // Write our built-in one - user may adjust the written file at will + + err = match fs::OpenOptions::new().create(true).write(true).open(&secret_path) { + Err(cfe) => cfe, + Ok(mut f) => { + // Assure we convert 'ugly' json string into pretty one + let console_secret: ConsoleApplicationSecret + = json::from_str(json_console_secret).unwrap(); + match json::to_writer_pretty(&mut f, &console_secret) { + Err(serde_err) => match serde_err { + json::Error::IoError(err) => err, + _ => panic!("Unexpected serde error: {:#?}", serde_err) + }, + Ok(_) => continue, + } + } + }; + // fall through to IO error handling + } + return secret_io_error(err) + }, + Ok(mut f) => { + match json::de::from_reader::<_, ConsoleApplicationSecret>(f) { + Err(json::Error::IoError(err)) => + return secret_io_error(err), + Err(json_err) => + return Err(CLIError::Configuration( + ConfigurationError::Secret( + ApplicationSecretError::DecoderError( + (secret_str(), json_err) + )))), + Ok(console_secret) => + match console_secret.installed { + Some(secret) => return Ok(secret), + None => return Err( + CLIError::Configuration( + ConfigurationError::Secret( + ApplicationSecretError::FormatError(secret_str()) + ))) + }, + } + } + } + } + unreachable!(); +} diff --git a/gen/pubsub1-cli/src/main.rs b/gen/pubsub1-cli/src/main.rs new file mode 100644 index 0000000000..7e810f9531 --- /dev/null +++ b/gen/pubsub1-cli/src/main.rs @@ -0,0 +1,2245 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/cli/main.rs.mako' +// DO NOT EDIT ! +#![allow(unused_variables, unused_imports, dead_code, unused_mut)] + +#[macro_use] +extern crate clap; +extern crate yup_oauth2 as oauth2; +extern crate yup_hyper_mock as mock; +extern crate serde; +extern crate serde_json; +extern crate hyper; +extern crate mime; +extern crate strsim; +extern crate google_pubsub1 as api; + +use std::env; +use std::io::{self, Write}; +use clap::{App, SubCommand, Arg}; + +mod cmn; + +use cmn::{InvalidOptionsError, CLIError, JsonTokenStorage, arg_from_str, writer_from_opts, parse_kv_arg, + input_file_from_opts, input_mime_from_opts, FieldCursor, FieldError, CallType, UploadProtocol, + calltype_from_str, remove_json_null_values, ComplexType, JsonType, JsonTypeInfo}; + +use std::default::Default; +use std::str::FromStr; + +use oauth2::{Authenticator, DefaultAuthenticatorDelegate}; +use serde_json as json; +use clap::ArgMatches; + +enum DoitError { + IoError(String, io::Error), + ApiError(api::Error), +} + +struct Engine<'n, 'a> { + opt: ArgMatches<'n, 'a>, + hub: api::Pubsub>, + gp: Vec<&'static str>, + gpm: Vec<(&'static str, &'static str)>, +} + + +impl<'n, 'a> Engine<'n, 'a> { + fn _projects_subscriptions_acknowledge(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "ack-ids" => Some(("ackIds", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["ack-ids"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::AcknowledgeRequest = json::value::from_value(object).unwrap(); + let mut call = self.hub.projects().subscriptions_acknowledge(request, opt.value_of("subscription").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _projects_subscriptions_create(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "topic" => Some(("topic", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "ack-deadline-seconds" => Some(("ackDeadlineSeconds", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "push-config.attributes" => Some(("pushConfig.attributes", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Map })), + "push-config.push-endpoint" => Some(("pushConfig.pushEndpoint", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["ack-deadline-seconds", "attributes", "name", "push-config", "push-endpoint", "topic"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::Subscription = json::value::from_value(object).unwrap(); + let mut call = self.hub.projects().subscriptions_create(request, opt.value_of("name").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _projects_subscriptions_delete(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.projects().subscriptions_delete(opt.value_of("subscription").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _projects_subscriptions_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.projects().subscriptions_get(opt.value_of("subscription").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _projects_subscriptions_get_iam_policy(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.projects().subscriptions_get_iam_policy(opt.value_of("resource").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _projects_subscriptions_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.projects().subscriptions_list(opt.value_of("project").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "page-size" => { + call = call.page_size(arg_from_str(value.unwrap_or("-0"), err, "page-size", "integer")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["page-token", "page-size"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _projects_subscriptions_modify_ack_deadline(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "ack-deadline-seconds" => Some(("ackDeadlineSeconds", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "ack-ids" => Some(("ackIds", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["ack-deadline-seconds", "ack-ids"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::ModifyAckDeadlineRequest = json::value::from_value(object).unwrap(); + let mut call = self.hub.projects().subscriptions_modify_ack_deadline(request, opt.value_of("subscription").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _projects_subscriptions_modify_push_config(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "push-config.attributes" => Some(("pushConfig.attributes", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Map })), + "push-config.push-endpoint" => Some(("pushConfig.pushEndpoint", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["attributes", "push-config", "push-endpoint"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::ModifyPushConfigRequest = json::value::from_value(object).unwrap(); + let mut call = self.hub.projects().subscriptions_modify_push_config(request, opt.value_of("subscription").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _projects_subscriptions_pull(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "return-immediately" => Some(("returnImmediately", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "max-messages" => Some(("maxMessages", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["max-messages", "return-immediately"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::PullRequest = json::value::from_value(object).unwrap(); + let mut call = self.hub.projects().subscriptions_pull(request, opt.value_of("subscription").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _projects_subscriptions_set_iam_policy(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "policy.version" => Some(("policy.version", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "policy.etag" => Some(("policy.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["etag", "policy", "version"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::SetIamPolicyRequest = json::value::from_value(object).unwrap(); + let mut call = self.hub.projects().subscriptions_set_iam_policy(request, opt.value_of("resource").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _projects_subscriptions_test_iam_permissions(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "permissions" => Some(("permissions", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["permissions"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::TestIamPermissionsRequest = json::value::from_value(object).unwrap(); + let mut call = self.hub.projects().subscriptions_test_iam_permissions(request, opt.value_of("resource").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _projects_topics_create(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["name"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::Topic = json::value::from_value(object).unwrap(); + let mut call = self.hub.projects().topics_create(request, opt.value_of("name").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _projects_topics_delete(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.projects().topics_delete(opt.value_of("topic").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _projects_topics_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.projects().topics_get(opt.value_of("topic").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _projects_topics_get_iam_policy(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.projects().topics_get_iam_policy(opt.value_of("resource").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _projects_topics_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.projects().topics_list(opt.value_of("project").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "page-size" => { + call = call.page_size(arg_from_str(value.unwrap_or("-0"), err, "page-size", "integer")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["page-token", "page-size"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _projects_topics_publish(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec![]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::PublishRequest = json::value::from_value(object).unwrap(); + let mut call = self.hub.projects().topics_publish(request, opt.value_of("topic").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _projects_topics_set_iam_policy(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "policy.version" => Some(("policy.version", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "policy.etag" => Some(("policy.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["etag", "policy", "version"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::SetIamPolicyRequest = json::value::from_value(object).unwrap(); + let mut call = self.hub.projects().topics_set_iam_policy(request, opt.value_of("resource").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _projects_topics_subscriptions_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.projects().topics_subscriptions_list(opt.value_of("topic").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "page-size" => { + call = call.page_size(arg_from_str(value.unwrap_or("-0"), err, "page-size", "integer")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["page-token", "page-size"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _projects_topics_test_iam_permissions(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "permissions" => Some(("permissions", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["permissions"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::TestIamPermissionsRequest = json::value::from_value(object).unwrap(); + let mut call = self.hub.projects().topics_test_iam_permissions(request, opt.value_of("resource").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _doit(&self, dry_run: bool) -> Result, Option> { + let mut err = InvalidOptionsError::new(); + let mut call_result: Result<(), DoitError> = Ok(()); + let mut err_opt: Option = None; + match self.opt.subcommand() { + ("projects", Some(opt)) => { + match opt.subcommand() { + ("subscriptions-acknowledge", Some(opt)) => { + call_result = self._projects_subscriptions_acknowledge(opt, dry_run, &mut err); + }, + ("subscriptions-create", Some(opt)) => { + call_result = self._projects_subscriptions_create(opt, dry_run, &mut err); + }, + ("subscriptions-delete", Some(opt)) => { + call_result = self._projects_subscriptions_delete(opt, dry_run, &mut err); + }, + ("subscriptions-get", Some(opt)) => { + call_result = self._projects_subscriptions_get(opt, dry_run, &mut err); + }, + ("subscriptions-get-iam-policy", Some(opt)) => { + call_result = self._projects_subscriptions_get_iam_policy(opt, dry_run, &mut err); + }, + ("subscriptions-list", Some(opt)) => { + call_result = self._projects_subscriptions_list(opt, dry_run, &mut err); + }, + ("subscriptions-modify-ack-deadline", Some(opt)) => { + call_result = self._projects_subscriptions_modify_ack_deadline(opt, dry_run, &mut err); + }, + ("subscriptions-modify-push-config", Some(opt)) => { + call_result = self._projects_subscriptions_modify_push_config(opt, dry_run, &mut err); + }, + ("subscriptions-pull", Some(opt)) => { + call_result = self._projects_subscriptions_pull(opt, dry_run, &mut err); + }, + ("subscriptions-set-iam-policy", Some(opt)) => { + call_result = self._projects_subscriptions_set_iam_policy(opt, dry_run, &mut err); + }, + ("subscriptions-test-iam-permissions", Some(opt)) => { + call_result = self._projects_subscriptions_test_iam_permissions(opt, dry_run, &mut err); + }, + ("topics-create", Some(opt)) => { + call_result = self._projects_topics_create(opt, dry_run, &mut err); + }, + ("topics-delete", Some(opt)) => { + call_result = self._projects_topics_delete(opt, dry_run, &mut err); + }, + ("topics-get", Some(opt)) => { + call_result = self._projects_topics_get(opt, dry_run, &mut err); + }, + ("topics-get-iam-policy", Some(opt)) => { + call_result = self._projects_topics_get_iam_policy(opt, dry_run, &mut err); + }, + ("topics-list", Some(opt)) => { + call_result = self._projects_topics_list(opt, dry_run, &mut err); + }, + ("topics-publish", Some(opt)) => { + call_result = self._projects_topics_publish(opt, dry_run, &mut err); + }, + ("topics-set-iam-policy", Some(opt)) => { + call_result = self._projects_topics_set_iam_policy(opt, dry_run, &mut err); + }, + ("topics-subscriptions-list", Some(opt)) => { + call_result = self._projects_topics_subscriptions_list(opt, dry_run, &mut err); + }, + ("topics-test-iam-permissions", Some(opt)) => { + call_result = self._projects_topics_test_iam_permissions(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("projects".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + _ => { + err.issues.push(CLIError::MissingCommandError); + writeln!(io::stderr(), "{}\n", self.opt.usage()).ok(); + } + } + + if dry_run { + if err.issues.len() > 0 { + err_opt = Some(err); + } + Err(err_opt) + } else { + Ok(call_result) + } + } + + // Please note that this call will fail if any part of the opt can't be handled + fn new(opt: ArgMatches<'a, 'n>) -> Result, InvalidOptionsError> { + let (config_dir, secret) = { + let config_dir = match cmn::assure_config_dir_exists(opt.value_of("folder").unwrap_or("~/.google-service-cli")) { + Err(e) => return Err(InvalidOptionsError::single(e, 3)), + Ok(p) => p, + }; + + match cmn::application_secret_from_directory(&config_dir, "pubsub1-secret.json", + "{\"installed\":{\"auth_uri\":\"https://accounts.google.com/o/oauth2/auth\",\"client_secret\":\"hCsslbCUyfehWMmbkG8vTYxG\",\"token_uri\":\"https://accounts.google.com/o/oauth2/token\",\"client_email\":\"\",\"redirect_uris\":[\"urn:ietf:wg:oauth:2.0:oob\",\"oob\"],\"client_x509_cert_url\":\"\",\"client_id\":\"620010449518-9ngf7o4dhs0dka470npqvor6dc5lqb9b.apps.googleusercontent.com\",\"auth_provider_x509_cert_url\":\"https://www.googleapis.com/oauth2/v1/certs\"}}") { + Ok(secret) => (config_dir, secret), + Err(e) => return Err(InvalidOptionsError::single(e, 4)) + } + }; + + let auth = Authenticator::new( &secret, DefaultAuthenticatorDelegate, + if opt.is_present("debug-auth") { + hyper::Client::with_connector(mock::TeeConnector { + connector: hyper::net::HttpsConnector::::default() + }) + } else { + hyper::Client::new() + }, + JsonTokenStorage { + program_name: "pubsub1", + db_dir: config_dir.clone(), + }, None); + + let client = + if opt.is_present("debug") { + hyper::Client::with_connector(mock::TeeConnector { + connector: hyper::net::HttpsConnector::::default() + }) + } else { + hyper::Client::new() + }; + let engine = Engine { + opt: opt, + hub: api::Pubsub::new(client, auth), + gp: vec!["$-xgafv", "access-token", "alt", "bearer-token", "callback", "fields", "key", "oauth-token", "pp", "pretty-print", "quota-user", "upload-type", "upload-protocol"], + gpm: vec![ + ("$-xgafv", "$.xgafv"), + ("access-token", "access_token"), + ("bearer-token", "bearer_token"), + ("oauth-token", "oauth_token"), + ("pretty-print", "prettyPrint"), + ("quota-user", "quotaUser"), + ("upload-type", "uploadType"), + ("upload-protocol", "upload_protocol"), + ] + }; + + match engine._doit(true) { + Err(Some(err)) => Err(err), + Err(None) => Ok(engine), + Ok(_) => unreachable!(), + } + } + + fn doit(&self) -> Result<(), DoitError> { + match self._doit(false) { + Ok(res) => res, + Err(_) => unreachable!(), + } + } +} + +fn main() { + let mut exit_status = 0i32; + let arg_data = [ + ("projects", "methods: 'subscriptions-acknowledge', 'subscriptions-create', 'subscriptions-delete', 'subscriptions-get', 'subscriptions-get-iam-policy', 'subscriptions-list', 'subscriptions-modify-ack-deadline', 'subscriptions-modify-push-config', 'subscriptions-pull', 'subscriptions-set-iam-policy', 'subscriptions-test-iam-permissions', 'topics-create', 'topics-delete', 'topics-get', 'topics-get-iam-policy', 'topics-list', 'topics-publish', 'topics-set-iam-policy', 'topics-subscriptions-list' and 'topics-test-iam-permissions'", vec![ + ("subscriptions-acknowledge", + Some(r##"Acknowledges the messages associated with the `ack_ids` in the `AcknowledgeRequest`. The Pub/Sub system can remove the relevant messages from the subscription. Acknowledging a message whose ack deadline has expired may succeed, but such a message may be redelivered later. Acknowledging a message more than once will not result in an error."##), + "Details at http://byron.github.io/google-apis-rs/google_pubsub1_cli/projects_subscriptions-acknowledge", + vec![ + (Some(r##"subscription"##), + None, + Some(r##"The subscription whose message is being acknowledged."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("subscriptions-create", + Some(r##"Creates a subscription to a given topic for a given subscriber. If the subscription already exists, returns `ALREADY_EXISTS`. If the corresponding topic doesn't exist, returns `NOT_FOUND`. If the name is not provided in the request, the server will assign a random name for this subscription on the same project as the topic."##), + "Details at http://byron.github.io/google-apis-rs/google_pubsub1_cli/projects_subscriptions-create", + vec![ + (Some(r##"name"##), + None, + Some(r##"The name of the subscription. It must have the format `"projects/{project}/subscriptions/{subscription}"`. `{subscription}` must start with a letter, and contain only letters (`[A-Za-z]`), numbers (`[0-9]`), dashes (`-`), underscores (`_`), periods (`.`), tildes (`~`), plus (`+`) or percent signs (`%`). It must be between 3 and 255 characters in length, and it must not start with `"goog"`."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("subscriptions-delete", + Some(r##"Deletes an existing subscription. All pending messages in the subscription are immediately dropped. Calls to `Pull` after deletion will return `NOT_FOUND`. After a subscription is deleted, a new one may be created with the same name, but the new one has no association with the old subscription, or its topic unless the same topic is specified."##), + "Details at http://byron.github.io/google-apis-rs/google_pubsub1_cli/projects_subscriptions-delete", + vec![ + (Some(r##"subscription"##), + None, + Some(r##"The subscription to delete."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("subscriptions-get", + Some(r##"Gets the configuration details of a subscription."##), + "Details at http://byron.github.io/google-apis-rs/google_pubsub1_cli/projects_subscriptions-get", + vec![ + (Some(r##"subscription"##), + None, + Some(r##"The name of the subscription to get."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("subscriptions-get-iam-policy", + Some(r##"Gets the access control policy for a `resource`. Is empty if the policy or the resource does not exist."##), + "Details at http://byron.github.io/google-apis-rs/google_pubsub1_cli/projects_subscriptions-get-iam-policy", + vec![ + (Some(r##"resource"##), + None, + Some(r##"REQUIRED: The resource for which policy is being requested. Resource is usually specified as a path, such as, `projects/{project}`."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("subscriptions-list", + Some(r##"Lists matching subscriptions."##), + "Details at http://byron.github.io/google-apis-rs/google_pubsub1_cli/projects_subscriptions-list", + vec![ + (Some(r##"project"##), + None, + Some(r##"The name of the cloud project that subscriptions belong to."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("subscriptions-modify-ack-deadline", + Some(r##"Modifies the ack deadline for a specific message. This method is useful to indicate that more time is needed to process a message by the subscriber, or to make the message available for redelivery if the processing was interrupted."##), + "Details at http://byron.github.io/google-apis-rs/google_pubsub1_cli/projects_subscriptions-modify-ack-deadline", + vec![ + (Some(r##"subscription"##), + None, + Some(r##"The name of the subscription."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("subscriptions-modify-push-config", + Some(r##"Modifies the `PushConfig` for a specified subscription. This may be used to change a push subscription to a pull one (signified by an empty `PushConfig`) or vice versa, or change the endpoint URL and other attributes of a push subscription. Messages will accumulate for delivery continuously through the call regardless of changes to the `PushConfig`."##), + "Details at http://byron.github.io/google-apis-rs/google_pubsub1_cli/projects_subscriptions-modify-push-config", + vec![ + (Some(r##"subscription"##), + None, + Some(r##"The name of the subscription."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("subscriptions-pull", + Some(r##"Pulls messages from the server. Returns an empty list if there are no messages available in the backlog. The server may return `UNAVAILABLE` if there are too many concurrent pull requests pending for the given subscription."##), + "Details at http://byron.github.io/google-apis-rs/google_pubsub1_cli/projects_subscriptions-pull", + vec![ + (Some(r##"subscription"##), + None, + Some(r##"The subscription from which messages should be pulled."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("subscriptions-set-iam-policy", + Some(r##"Sets the access control policy on the specified resource. Replaces any existing policy."##), + "Details at http://byron.github.io/google-apis-rs/google_pubsub1_cli/projects_subscriptions-set-iam-policy", + vec![ + (Some(r##"resource"##), + None, + Some(r##"REQUIRED: The resource for which policy is being specified. `resource` is usually specified as a path, such as, `projects/{project}/zones/{zone}/disks/{disk}`."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("subscriptions-test-iam-permissions", + Some(r##"Returns permissions that a caller has on the specified resource."##), + "Details at http://byron.github.io/google-apis-rs/google_pubsub1_cli/projects_subscriptions-test-iam-permissions", + vec![ + (Some(r##"resource"##), + None, + Some(r##"REQUIRED: The resource for which policy detail is being requested. `resource` is usually specified as a path, such as, `projects/{project}`."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("topics-create", + Some(r##"Creates the given topic with the given name."##), + "Details at http://byron.github.io/google-apis-rs/google_pubsub1_cli/projects_topics-create", + vec![ + (Some(r##"name"##), + None, + Some(r##"The name of the topic. It must have the format `"projects/{project}/topics/{topic}"`. `{topic}` must start with a letter, and contain only letters (`[A-Za-z]`), numbers (`[0-9]`), dashes (`-`), underscores (`_`), periods (`.`), tildes (`~`), plus (`+`) or percent signs (`%`). It must be between 3 and 255 characters in length, and it must not start with `"goog"`."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("topics-delete", + Some(r##"Deletes the topic with the given name. Returns `NOT_FOUND` if the topic does not exist. After a topic is deleted, a new topic may be created with the same name; this is an entirely new topic with none of the old configuration or subscriptions. Existing subscriptions to this topic are not deleted, but their `topic` field is set to `_deleted-topic_`."##), + "Details at http://byron.github.io/google-apis-rs/google_pubsub1_cli/projects_topics-delete", + vec![ + (Some(r##"topic"##), + None, + Some(r##"Name of the topic to delete."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("topics-get", + Some(r##"Gets the configuration of a topic."##), + "Details at http://byron.github.io/google-apis-rs/google_pubsub1_cli/projects_topics-get", + vec![ + (Some(r##"topic"##), + None, + Some(r##"The name of the topic to get."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("topics-get-iam-policy", + Some(r##"Gets the access control policy for a `resource`. Is empty if the policy or the resource does not exist."##), + "Details at http://byron.github.io/google-apis-rs/google_pubsub1_cli/projects_topics-get-iam-policy", + vec![ + (Some(r##"resource"##), + None, + Some(r##"REQUIRED: The resource for which policy is being requested. Resource is usually specified as a path, such as, `projects/{project}`."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("topics-list", + Some(r##"Lists matching topics."##), + "Details at http://byron.github.io/google-apis-rs/google_pubsub1_cli/projects_topics-list", + vec![ + (Some(r##"project"##), + None, + Some(r##"The name of the cloud project that topics belong to."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("topics-publish", + Some(r##"Adds one or more messages to the topic. Returns `NOT_FOUND` if the topic does not exist. The message payload must not be empty; it must contain either a non-empty data field, or at least one attribute."##), + "Details at http://byron.github.io/google-apis-rs/google_pubsub1_cli/projects_topics-publish", + vec![ + (Some(r##"topic"##), + None, + Some(r##"The messages in the request will be published on this topic."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("topics-set-iam-policy", + Some(r##"Sets the access control policy on the specified resource. Replaces any existing policy."##), + "Details at http://byron.github.io/google-apis-rs/google_pubsub1_cli/projects_topics-set-iam-policy", + vec![ + (Some(r##"resource"##), + None, + Some(r##"REQUIRED: The resource for which policy is being specified. `resource` is usually specified as a path, such as, `projects/{project}/zones/{zone}/disks/{disk}`."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("topics-subscriptions-list", + Some(r##"Lists the name of the subscriptions for this topic."##), + "Details at http://byron.github.io/google-apis-rs/google_pubsub1_cli/projects_topics-subscriptions-list", + vec![ + (Some(r##"topic"##), + None, + Some(r##"The name of the topic that subscriptions are attached to."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("topics-test-iam-permissions", + Some(r##"Returns permissions that a caller has on the specified resource."##), + "Details at http://byron.github.io/google-apis-rs/google_pubsub1_cli/projects_topics-test-iam-permissions", + vec![ + (Some(r##"resource"##), + None, + Some(r##"REQUIRED: The resource for which policy detail is being requested. `resource` is usually specified as a path, such as, `projects/{project}`."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ]; + + let mut app = App::new("pubsub1") + .author("Sebastian Thiel ") + .version("0.3.2+20150526") + .about("Provides reliable, many-to-many, asynchronous messaging between applications.") + .after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_pubsub1_cli") + .arg(Arg::with_name("url") + .long("scope") + .help("Specify the authentication a method should be executed in. Each scope requires the user to grant this application permission to use it.If unset, it defaults to the shortest scope url for a particular method.") + .multiple(true) + .takes_value(true)) + .arg(Arg::with_name("folder") + .long("config-dir") + .help("A directory into which we will store our persistent data. Defaults to a user-writable directory that we will create during the first invocation.[default: ~/.google-service-cli") + .multiple(false) + .takes_value(true)) + .arg(Arg::with_name("debug") + .long("debug") + .help("Output all server communication to standard error. `tx` and `rx` are placed into the same stream.") + .multiple(false) + .takes_value(false)) + .arg(Arg::with_name("debug-auth") + .long("debug-auth") + .help("Output all communication related to authentication to standard error. `tx` and `rx` are placed into the same stream.") + .multiple(false) + .takes_value(false)); + + for &(main_command_name, ref about, ref subcommands) in arg_data.iter() { + let mut mcmd = SubCommand::with_name(main_command_name).about(about); + + for &(sub_command_name, ref desc, url_info, ref args) in subcommands { + let mut scmd = SubCommand::with_name(sub_command_name); + if let &Some(desc) = desc { + scmd = scmd.about(desc); + } + scmd = scmd.after_help(url_info); + + for &(ref arg_name, ref flag, ref desc, ref required, ref multi) in args { + let arg_name_str = + match (arg_name, flag) { + (&Some(an), _ ) => an, + (_ , &Some(f)) => f, + _ => unreachable!(), + }; + let mut arg = Arg::with_name(arg_name_str) + .empty_values(false); + if let &Some(short_flag) = flag { + arg = arg.short(short_flag); + } + if let &Some(desc) = desc { + arg = arg.help(desc); + } + if arg_name.is_some() && flag.is_some() { + arg = arg.takes_value(true); + } + if let &Some(required) = required { + arg = arg.required(required); + } + if let &Some(multi) = multi { + arg = arg.multiple(multi); + } + scmd = scmd.arg(arg); + } + mcmd = mcmd.subcommand(scmd); + } + app = app.subcommand(mcmd); + } + + let matches = app.get_matches(); + + let debug = matches.is_present("debug"); + match Engine::new(matches) { + Err(err) => { + exit_status = err.exit_code; + writeln!(io::stderr(), "{}", err).ok(); + }, + Ok(engine) => { + if let Err(doit_err) = engine.doit() { + exit_status = 1; + match doit_err { + DoitError::IoError(path, err) => { + writeln!(io::stderr(), "Failed to open output file '{}': {}", path, err).ok(); + }, + DoitError::ApiError(err) => { + if debug { + writeln!(io::stderr(), "{:#?}", err).ok(); + } else { + writeln!(io::stderr(), "{}", err).ok(); + } + } + } + } + } + } + + std::process::exit(exit_status); +} \ No newline at end of file diff --git a/gen/pubsub1/Cargo.toml b/gen/pubsub1/Cargo.toml new file mode 100644 index 0000000000..38f0615393 --- /dev/null +++ b/gen/pubsub1/Cargo.toml @@ -0,0 +1,29 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-pubsub1" +version = "0.1.9+20150526" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with pubsub (protocol v1)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/pubsub1" +homepage = "https://cloud.google.com/pubsub/docs" +documentation = "http://byron.github.io/google-apis-rs/google_pubsub1" +license = "MIT" +keywords = ["pubsub", "google", "protocol", "web", "api"] +build = "src/build.rs" + + +[dependencies] +hyper = ">= 0.6.8" +mime = "0.1.0" +serde = ">= 0.6.0" +serde_json = ">= 0.6.0" +yup-oauth2 = "*" +url = "*" + +[build-dependencies] +syntex = { version = "*" } +serde_codegen = { version = "*" } + diff --git a/gen/pubsub1/LICENSE.md b/gen/pubsub1/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/pubsub1/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/pubsub1/README.md b/gen/pubsub1/README.md new file mode 100644 index 0000000000..3f5193cc79 --- /dev/null +++ b/gen/pubsub1/README.md @@ -0,0 +1,183 @@ + +The `google-pubsub1` library allows access to all features of the *Google pubsub* service. + +This documentation was generated from *pubsub* crate version *0.1.9+20150526*, where *20150526* is the exact revision of the *pubsub:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. + +Everything else about the *pubsub* *v1* API can be found at the +[official documentation site](https://cloud.google.com/pubsub/docs). +# Features + +Handle the following *Resources* with ease from the central [hub](http://byron.github.io/google-apis-rs/google_pubsub1/struct.Pubsub.html) ... + +* projects + * [*subscriptions acknowledge*](http://byron.github.io/google-apis-rs/google_pubsub1/struct.ProjectSubscriptionAcknowledgeCall.html), [*subscriptions create*](http://byron.github.io/google-apis-rs/google_pubsub1/struct.ProjectSubscriptionCreateCall.html), [*subscriptions delete*](http://byron.github.io/google-apis-rs/google_pubsub1/struct.ProjectSubscriptionDeleteCall.html), [*subscriptions get*](http://byron.github.io/google-apis-rs/google_pubsub1/struct.ProjectSubscriptionGetCall.html), [*subscriptions get iam policy*](http://byron.github.io/google-apis-rs/google_pubsub1/struct.ProjectSubscriptionGetIamPolicyCall.html), [*subscriptions list*](http://byron.github.io/google-apis-rs/google_pubsub1/struct.ProjectSubscriptionListCall.html), [*subscriptions modify ack deadline*](http://byron.github.io/google-apis-rs/google_pubsub1/struct.ProjectSubscriptionModifyAckDeadlineCall.html), [*subscriptions modify push config*](http://byron.github.io/google-apis-rs/google_pubsub1/struct.ProjectSubscriptionModifyPushConfigCall.html), [*subscriptions pull*](http://byron.github.io/google-apis-rs/google_pubsub1/struct.ProjectSubscriptionPullCall.html), [*subscriptions set iam policy*](http://byron.github.io/google-apis-rs/google_pubsub1/struct.ProjectSubscriptionSetIamPolicyCall.html), [*subscriptions test iam permissions*](http://byron.github.io/google-apis-rs/google_pubsub1/struct.ProjectSubscriptionTestIamPermissionCall.html), [*topics create*](http://byron.github.io/google-apis-rs/google_pubsub1/struct.ProjectTopicCreateCall.html), [*topics delete*](http://byron.github.io/google-apis-rs/google_pubsub1/struct.ProjectTopicDeleteCall.html), [*topics get*](http://byron.github.io/google-apis-rs/google_pubsub1/struct.ProjectTopicGetCall.html), [*topics get iam policy*](http://byron.github.io/google-apis-rs/google_pubsub1/struct.ProjectTopicGetIamPolicyCall.html), [*topics list*](http://byron.github.io/google-apis-rs/google_pubsub1/struct.ProjectTopicListCall.html), [*topics publish*](http://byron.github.io/google-apis-rs/google_pubsub1/struct.ProjectTopicPublishCall.html), [*topics set iam policy*](http://byron.github.io/google-apis-rs/google_pubsub1/struct.ProjectTopicSetIamPolicyCall.html), [*topics subscriptions list*](http://byron.github.io/google-apis-rs/google_pubsub1/struct.ProjectTopicSubscriptionListCall.html) and [*topics test iam permissions*](http://byron.github.io/google-apis-rs/google_pubsub1/struct.ProjectTopicTestIamPermissionCall.html) + + + + +# Structure of this Library + +The API is structured into the following primary items: + +* **[Hub](http://byron.github.io/google-apis-rs/google_pubsub1/struct.Pubsub.html)** + * a central object to maintain state and allow accessing all *Activities* + * creates [*Method Builders*](http://byron.github.io/google-apis-rs/google_pubsub1/trait.MethodsBuilder.html) which in turn + allow access to individual [*Call Builders*](http://byron.github.io/google-apis-rs/google_pubsub1/trait.CallBuilder.html) +* **[Resources](http://byron.github.io/google-apis-rs/google_pubsub1/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_pubsub1/trait.Part.html)** + * a collection of properties + * never directly used in *Activities* +* **[Activities](http://byron.github.io/google-apis-rs/google_pubsub1/trait.CallBuilder.html)** + * operations to apply to *Resources* + +All *structures* are marked with applicable traits to further categorize them and ease browsing. + +Generally speaking, you can invoke *Activities* like this: + +```Rust,ignore +let r = hub.resource().activity(...).doit() +``` + +Or specifically ... + +```ignore +let r = hub.projects().subscriptions_acknowledge(...).doit() +let r = hub.projects().subscriptions_modify_push_config(...).doit() +let r = hub.projects().subscriptions_delete(...).doit() +let r = hub.projects().topics_delete(...).doit() +let r = hub.projects().subscriptions_modify_ack_deadline(...).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-pubsub1 = "*" +``` + +## A complete example + +```Rust +extern crate hyper; +extern crate yup_oauth2 as oauth2; +extern crate google_pubsub1 as pubsub1; +use pubsub1::AcknowledgeRequest; +use pubsub1::{Result, Error}; +use std::default::Default; +use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +use pubsub1::Pubsub; + +// 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 = Pubsub::new(hyper::Client::new(), auth); +// As the method needs a request, you would usually fill it with the desired information +// into the respective structure. Some of the parts shown here might not be applicable ! +// Values shown here are possibly random and not representative ! +let mut req = AcknowledgeRequest::default(); + +// You can configure optional parameters by calling 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().subscriptions_acknowledge(req, "subscription") + .doit(); + +match result { + Err(e) => match e { + // The Error enum provides details about what exactly happened. + // You can also just use its `Debug`, `Display` or `Error` traits + Error::HttpError(_) + |Error::MissingAPIKey + |Error::MissingToken(_) + |Error::Cancelled + |Error::UploadSizeLimitExceeded(_, _) + |Error::Failure(_) + |Error::BadRequest(_) + |Error::FieldClash(_) + |Error::JsonDecodeError(_, _) => println!("{}", e), + }, + Ok(res) => println!("Success: {:?}", res), +} + +``` +## Handling Errors + +All errors produced by the system are provided either as [Result](http://byron.github.io/google-apis-rs/google_pubsub1/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_pubsub1/trait.Delegate.html), or the [Authenticator Delegate](http://byron.github.io/google-apis-rs/google_pubsub1/../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 Downloads +If a method supports downloads, the response body, which is part of the [Result](http://byron.github.io/google-apis-rs/google_pubsub1/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_pubsub1/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_pubsub1/trait.Delegate.html) to the +[Method Builder](http://byron.github.io/google-apis-rs/google_pubsub1/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_pubsub1/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_pubsub1/trait.RequestValue.html) and +[decodable](http://byron.github.io/google-apis-rs/google_pubsub1/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_pubsub1/trait.Part.html) which are identifiable 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_pubsub1/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_pubsub1/trait.RequestValue.html) are moved + +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 **pubsub1** 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/pubsub1/src/build.rs b/gen/pubsub1/src/build.rs new file mode 100644 index 0000000000..53a003ffc0 --- /dev/null +++ b/gen/pubsub1/src/build.rs @@ -0,0 +1,16 @@ +extern crate syntex; +extern crate serde_codegen; + +use std::env; +use std::path::Path; + +pub fn main() { + let out_dir = env::var_os("OUT_DIR").unwrap(); + + let src = Path::new("src/lib.rs.in"); + let dst = Path::new(&out_dir).join("lib.rs"); + + let mut registry = syntex::Registry::new(); + serde_codegen::register(&mut registry); + registry.expand("google-pubsub1", &src, &dst).unwrap(); +} diff --git a/gen/pubsub1/src/cmn.rs b/gen/pubsub1/src/cmn.rs new file mode 100644 index 0000000000..0e31353ba3 --- /dev/null +++ b/gen/pubsub1/src/cmn.rs @@ -0,0 +1,762 @@ +// COPY OF 'src/rust/api/cmn.rs' +// DO NOT EDIT +use std::io::{self, Read, Seek, Cursor, Write, SeekFrom}; +use std; +use std::fmt::{self, Display}; +use std::str::FromStr; +use std::error; +use std::thread::sleep_ms; + +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::h1::LINE_ENDING; +use hyper::method::Method; +use hyper::status::StatusCode; + +use serde_json as json; + +/// 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 {} + +/// Identifies types for building methods of a particular resource type +pub trait MethodsBuilder {} + +/// Identifies types which represent builders for a particular resource method +pub trait CallBuilder {} + +/// Identifies types which can be inserted and deleted. +/// Types with this trait are most commonly used by clients of this API. +pub trait Resource {} + +/// Identifies types which are used in API responses. +pub trait ResponseResult {} + +/// Identifies types which are used in API requests. +pub trait RequestValue {} + +/// Identifies types which are not actually used by the API +/// This might be a bug within the google API schema. +pub trait UnusedType {} + +/// Identifies types which are only used as part of other types, which +/// usually are carrying the `Resource` trait. +pub trait Part {} + +/// 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 {} + +/// 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 +} + +/// A utility to represent detailed errors we might see in case there are BadRequests. +/// The latter happen if the sent parameters or request structures are unsound +#[derive(Deserialize, Serialize, Debug)] +pub struct ErrorResponse { + error: ServerError, +} + +#[derive(Deserialize, Serialize, Debug)] +pub struct ServerError { + errors: Vec, + code: u16, + message: String, +} + +#[derive(Deserialize, Serialize, Debug)] +pub struct ServerMessage { + domain: String, + reason: String, + message: String, + #[serde(rename="locationType")] + location_type: Option, + location: 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 successful. That way, the delegate 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. + /// + /// If you choose to retry after a duration, the duration should be chosen using the + /// [exponential backoff algorithm](http://en.wikipedia.org/wiki/Exponential_backoff). + /// + /// Return retry information. + fn http_error(&mut self, &hyper::Error) -> 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 it as a general information about the + /// impending failure. + /// The given Error provides information about why the token couldn't be acquired in the + /// first place + fn token(&mut self, err: &error::Error) -> Option { + let _ = err; + 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/canceled, 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()`. + /// It will also be called with None after a successful upload, which allows the delegate + /// to forget the URL. That way, we will not attempt to resume an upload that has already + /// finished. + fn store_upload_url(&mut self, url: Option<&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: &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. + /// + /// If you choose to retry after a duration, the duration should be chosen using the + /// [exponential backoff algorithm](http://en.wikipedia.org/wiki/Exponential_backoff). + fn http_failure(&mut self, _: &hyper::client::Response, Option, _: 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 {} + + +#[derive(Debug)] +pub enum Error { + /// The http connection failed + HttpError(hyper::Error), + + /// 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), + + /// Represents information about a request that was not understood by the server. + /// Details are included. + BadRequest(ErrorResponse), + + /// 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(Box), + + /// 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(String, json::Error), + + /// Indicates an HTTP repsonse with a non-success status code + Failure(hyper::client::Response), +} + + +impl Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + Error::HttpError(ref err) => err.fmt(f), + Error::UploadSizeLimitExceeded(ref resource_size, ref max_size) => + writeln!(f, "The media size {} exceeds the maximum allowed upload size of {}" + , resource_size, max_size), + Error::MissingAPIKey => { + (writeln!(f, "The application's API key was not found in the configuration")).ok(); + writeln!(f, "It is used as there are no Scopes defined for this method.") + }, + Error::BadRequest(ref err) => { + try!(writeln!(f, "Bad Requst ({}): {}", err.error.code, err.error.message)); + for err in err.error.errors.iter() { + try!(writeln!(f, " {}: {}, {}{}", + err.domain, + err.message, + err.reason, + match &err.location { + &Some(ref loc) => format!("@{}", loc), + &None => String::new(), + })); + } + Ok(()) + }, + Error::MissingToken(ref err) => + writeln!(f, "Token retrieval failed with error: {}", err), + Error::Cancelled => + writeln!(f, "Operation cancelled by delegate"), + Error::FieldClash(field) => + writeln!(f, "The custom parameter '{}' is already provided natively by the CallBuilder.", field), + Error::JsonDecodeError(ref json_str, ref err) + => writeln!(f, "{}: {}", err, json_str), + Error::Failure(ref response) => + writeln!(f, "Http status indicates failure: {:?}", response), + } + } +} + +impl error::Error for Error { + fn description(&self) -> &str { + match *self { + Error::HttpError(ref err) => err.description(), + Error::JsonDecodeError(_, ref err) => err.description(), + _ => "NO DESCRIPTION POSSIBLE - use `Display.fmt()` instead" + } + } + + fn cause(&self) -> Option<&error::Error> { + match *self { + Error::HttpError(ref err) => err.cause(), + Error::JsonDecodeError(_, ref err) => err.cause(), + _ => None + } + } +} + +/// A universal result type used as return for all calls. +pub type Result = std::result::Result; + +/// 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 + 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 following macro invocation needs to be expanded, as `include!` +// doens't support external macros +// header!{ +// #[doc="The `X-Upload-Content-Type` header."] +// (XUploadContentType, "X-Upload-Content-Type") => [Mime] + +// xupload_content_type { +// test_header!( +// test1, +// vec![b"text/plain"], +// Some(HeaderField( +// vec![Mime(TopLevel::Text, SubLevel::Plain, Vec::new())] +// ))); + +// } +// } + +/// The `X-Upload-Content-Type` header. +/// +/// Generated via rustc --pretty expanded -Z unstable-options, and manually +/// processed to be more readable. +#[derive(PartialEq, Debug, Clone)] +pub struct XUploadContentType(pub Mime); + +impl ::std::ops::Deref for XUploadContentType { + type Target = Mime; + fn deref<'a>(&'a self) -> &'a Mime { &self.0 } +} +impl ::std::ops::DerefMut for XUploadContentType { + fn deref_mut<'a>(&'a mut self) -> &'a mut Mime { &mut self.0 } +} +impl Header for XUploadContentType { + fn header_name() -> &'static str { "X-Upload-Content-Type" } + fn parse_header(raw: &[Vec]) -> hyper::error::Result { + hyper::header::parsing::from_one_raw_str(raw).map(XUploadContentType) + } +} +impl HeaderFormat for XUploadContentType { + fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { + Display::fmt(&**self, f) + } +} +impl Display for XUploadContentType { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Display::fmt(&**self, f) + } +} + +#[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]) -> hyper::error::Result { + Err(hyper::error::Error::Method) + } +} + + +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]) -> hyper::error::Result { + if raw.len() > 0 { + let v = &raw[0]; + if let Ok(s) = std::str::from_utf8(v) { + const PREFIX: &'static str = "bytes "; + if s.starts_with(PREFIX) { + if let Ok(c) = ::from_str(&s[PREFIX.len()..]) { + return Ok(RangeResponseHeader(c)) + } + } + } + } + Err(hyper::error::Error::Method) + } +} + +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, 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, A> ResumableUploadHelper<'a, A> + where A: oauth2::GetToken { + + fn query_transfer_status(&mut self) -> std::result::Result> { + 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, None) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + return Err(Ok(r)) + } + }; + return Ok(h.0.last) + } + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + return Err(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() { + Ok(s) => s, + Err(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 + }; + + self.reader.seek(SeekFrom::Start(start)).unwrap(); + loop { + let request_size = match self.content_length - start { + rs if rs > chunk_size => chunk_size, + rs => rs + }; + + 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 + } + // workaround https://github.com/rust-lang/rust/issues/22252 + let res = 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(); + match res { + 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, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + } + return Some(Ok(res)) + }, + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + return Some(Err(err)) + } + } + } + } +} + +// Copy of src/rust/cli/cmn.rs +// TODO(ST): Allow sharing common code between program types +pub fn remove_json_null_values(value: &mut json::value::Value) { + match *value { + json::value::Value::Object(ref mut map) => { + let mut for_removal = Vec::new(); + + for (key, mut value) in map.iter_mut() { + if value.is_null() { + for_removal.push(key.clone()); + } else { + remove_json_null_values(&mut value); + } + } + + for key in &for_removal { + map.remove(key); + } + } + _ => {} + } +} diff --git a/gen/pubsub1/src/lib.rs b/gen/pubsub1/src/lib.rs new file mode 100644 index 0000000000..bf388e1a3e --- /dev/null +++ b/gen/pubsub1/src/lib.rs @@ -0,0 +1,187 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/api/lib.rs.mako' +// DO NOT EDIT ! + +//! This documentation was generated from *pubsub* crate version *0.1.9+20150526*, where *20150526* is the exact revision of the *pubsub:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +//! +//! Everything else about the *pubsub* *v1* API can be found at the +//! [official documentation site](https://cloud.google.com/pubsub/docs). +//! The original source code is [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/pubsub1). +//! # Features +//! +//! Handle the following *Resources* with ease from the central [hub](struct.Pubsub.html) ... +//! +//! * projects +//! * [*subscriptions acknowledge*](struct.ProjectSubscriptionAcknowledgeCall.html), [*subscriptions create*](struct.ProjectSubscriptionCreateCall.html), [*subscriptions delete*](struct.ProjectSubscriptionDeleteCall.html), [*subscriptions get*](struct.ProjectSubscriptionGetCall.html), [*subscriptions get iam policy*](struct.ProjectSubscriptionGetIamPolicyCall.html), [*subscriptions list*](struct.ProjectSubscriptionListCall.html), [*subscriptions modify ack deadline*](struct.ProjectSubscriptionModifyAckDeadlineCall.html), [*subscriptions modify push config*](struct.ProjectSubscriptionModifyPushConfigCall.html), [*subscriptions pull*](struct.ProjectSubscriptionPullCall.html), [*subscriptions set iam policy*](struct.ProjectSubscriptionSetIamPolicyCall.html), [*subscriptions test iam permissions*](struct.ProjectSubscriptionTestIamPermissionCall.html), [*topics create*](struct.ProjectTopicCreateCall.html), [*topics delete*](struct.ProjectTopicDeleteCall.html), [*topics get*](struct.ProjectTopicGetCall.html), [*topics get iam policy*](struct.ProjectTopicGetIamPolicyCall.html), [*topics list*](struct.ProjectTopicListCall.html), [*topics publish*](struct.ProjectTopicPublishCall.html), [*topics set iam policy*](struct.ProjectTopicSetIamPolicyCall.html), [*topics subscriptions list*](struct.ProjectTopicSubscriptionListCall.html) and [*topics test iam permissions*](struct.ProjectTopicTestIamPermissionCall.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.Pubsub.html)** +//! * a central object to maintain state and allow accessing all *Activities* +//! * creates [*Method Builders*](trait.MethodsBuilder.html) which in turn +//! allow access to individual [*Call Builders*](trait.CallBuilder.html) +//! * **[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* +//! +//! All *structures* are marked with applicable traits to further categorize them and ease browsing. +//! +//! Generally speaking, you can invoke *Activities* like this: +//! +//! ```Rust,ignore +//! let r = hub.resource().activity(...).doit() +//! ``` +//! +//! Or specifically ... +//! +//! ```ignore +//! let r = hub.projects().subscriptions_acknowledge(...).doit() +//! let r = hub.projects().subscriptions_modify_push_config(...).doit() +//! let r = hub.projects().subscriptions_delete(...).doit() +//! let r = hub.projects().topics_delete(...).doit() +//! let r = hub.projects().subscriptions_modify_ack_deadline(...).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-pubsub1 = "*" +//! ``` +//! +//! ## A complete example +//! +//! ```test_harness,no_run +//! extern crate hyper; +//! extern crate yup_oauth2 as oauth2; +//! extern crate google_pubsub1 as pubsub1; +//! use pubsub1::AcknowledgeRequest; +//! use pubsub1::{Result, Error}; +//! # #[test] fn egal() { +//! use std::default::Default; +//! use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +//! use pubsub1::Pubsub; +//! +//! // 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 = Pubsub::new(hyper::Client::new(), auth); +//! // As the method needs a request, you would usually fill it with the desired information +//! // into the respective structure. Some of the parts shown here might not be applicable ! +//! // Values shown here are possibly random and not representative ! +//! let mut req = AcknowledgeRequest::default(); +//! +//! // You can configure optional parameters by calling 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().subscriptions_acknowledge(req, "subscription") +//! .doit(); +//! +//! match result { +//! Err(e) => match e { +//! // The Error enum provides details about what exactly happened. +//! // You can also just use its `Debug`, `Display` or `Error` traits +//! Error::HttpError(_) +//! |Error::MissingAPIKey +//! |Error::MissingToken(_) +//! |Error::Cancelled +//! |Error::UploadSizeLimitExceeded(_, _) +//! |Error::Failure(_) +//! |Error::BadRequest(_) +//! |Error::FieldClash(_) +//! |Error::JsonDecodeError(_, _) => println!("{}", e), +//! }, +//! Ok(res) => println!("Success: {:?}", res), +//! } +//! # } +//! ``` +//! ## 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 Downloads +//! 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 identifiable 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 moved +//! +//! 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 +//! +//! + +// 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)] + +include!(concat!(env!("OUT_DIR"), "/lib.rs")); \ No newline at end of file diff --git a/gen/pubsub1/src/lib.rs.in b/gen/pubsub1/src/lib.rs.in new file mode 100644 index 0000000000..c062307d55 --- /dev/null +++ b/gen/pubsub1/src/lib.rs.in @@ -0,0 +1,6329 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/api/lib.rs.in.mako' +// DO NOT EDIT ! + +extern crate hyper; +extern crate serde; +extern crate serde_json; +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 serde_json as json; +use std::io; +use std::fs; +use std::thread::sleep_ms; + +pub use cmn::{MultiPartReader, ToParts, MethodInfo, Result, Error, CallBuilder, Hub, ReadSeek, Part, + ResponseResult, RequestValue, NestedType, Delegate, DefaultDelegate, MethodsBuilder, + Resource, ErrorResponse, remove_json_null_values}; + + +// ############## +// 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, + + /// View and manage Pub/Sub topics and subscriptions + Full, +} + +impl AsRef for Scope { + fn as_ref(&self) -> &str { + match *self { + Scope::CloudPlatform => "https://www.googleapis.com/auth/cloud-platform", + Scope::Full => "https://www.googleapis.com/auth/pubsub", + } + } +} + +impl Default for Scope { + fn default() -> Scope { + Scope::Full + } +} + + + +// ######## +// HUB ### +// ###### + +/// Central instance to access all Pubsub related resource activities +/// +/// # Examples +/// +/// Instantiate a new hub +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate yup_oauth2 as oauth2; +/// extern crate google_pubsub1 as pubsub1; +/// use pubsub1::AcknowledgeRequest; +/// use pubsub1::{Result, Error}; +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use pubsub1::Pubsub; +/// +/// // 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 = Pubsub::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req = AcknowledgeRequest::default(); +/// +/// // You can configure optional parameters by calling 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().subscriptions_acknowledge(req, "subscription") +/// .doit(); +/// +/// match result { +/// Err(e) => match e { +/// // The Error enum provides details about what exactly happened. +/// // You can also just use its `Debug`, `Display` or `Error` traits +/// Error::HttpError(_) +/// |Error::MissingAPIKey +/// |Error::MissingToken(_) +/// |Error::Cancelled +/// |Error::UploadSizeLimitExceeded(_, _) +/// |Error::Failure(_) +/// |Error::BadRequest(_) +/// |Error::FieldClash(_) +/// |Error::JsonDecodeError(_, _) => println!("{}", e), +/// }, +/// Ok(res) => println!("Success: {:?}", res), +/// } +/// # } +/// ``` +pub struct Pubsub { + client: RefCell, + auth: RefCell, + _user_agent: String, +} + +impl<'a, C, A> Hub for Pubsub {} + +impl<'a, C, A> Pubsub + where C: BorrowMut, A: oauth2::GetToken { + + pub fn new(client: C, authenticator: A) -> Pubsub { + Pubsub { + client: RefCell::new(client), + auth: RefCell::new(authenticator), + _user_agent: "google-api-rust-client/0.1.9".to_string(), + } + } + + pub fn projects(&'a self) -> ProjectMethods<'a, C, 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.9`. + /// + /// 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 message for `TestIamPermissions` 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*). +/// +/// * [subscriptions test iam permissions projects](struct.ProjectSubscriptionTestIamPermissionCall.html) (request) +/// * [topics test iam permissions projects](struct.ProjectTopicTestIamPermissionCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct TestIamPermissionsRequest { + /// The set of permissions to check for the `resource`. Permissions with wildcards (such as '*' or 'storage.*') are not allowed. + pub permissions: Option>, +} + +impl RequestValue for TestIamPermissionsRequest {} + + +/// Response for the `ListTopicSubscriptions` 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*). +/// +/// * [topics subscriptions list projects](struct.ProjectTopicSubscriptionListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ListTopicSubscriptionsResponse { + /// If not empty, indicates that there may be more subscriptions that match the request; this value should be passed in a new `ListTopicSubscriptionsRequest` to get more subscriptions. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// The names of the subscriptions that match the request. + pub subscriptions: Option>, +} + +impl ResponseResult for ListTopicSubscriptionsResponse {} + + +/// Request message for `SetIamPolicy` 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*). +/// +/// * [subscriptions set iam policy projects](struct.ProjectSubscriptionSetIamPolicyCall.html) (request) +/// * [topics set iam policy projects](struct.ProjectTopicSetIamPolicyCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct SetIamPolicyRequest { + /// REQUIRED: The complete policy to be applied to the `resource`. The size of the policy is limited to a few 10s of KB. An empty policy is a valid policy but certain Cloud Platform services (such as Projects) might reject them. + pub policy: Option, +} + +impl RequestValue for SetIamPolicyRequest {} + + +/// A message and its corresponding acknowledgment 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 ReceivedMessage { + /// This ID can be used to acknowledge the received message. + #[serde(rename="ackId")] + pub ack_id: Option, + /// The message. + pub message: Option, +} + +impl Part for ReceivedMessage {} + + +/// Request for the Acknowledge 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*). +/// +/// * [subscriptions acknowledge projects](struct.ProjectSubscriptionAcknowledgeCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct AcknowledgeRequest { + /// The acknowledgment ID for the messages being acknowledged that was returned by the Pub/Sub system in the `Pull` response. Must not be empty. + #[serde(rename="ackIds")] + pub ack_ids: Option>, +} + +impl RequestValue for AcknowledgeRequest {} + + +/// Request for the ModifyAckDeadline 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*). +/// +/// * [subscriptions modify ack deadline projects](struct.ProjectSubscriptionModifyAckDeadlineCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ModifyAckDeadlineRequest { + /// The new ack deadline with respect to the time this request was sent to the Pub/Sub system. Must be >= 0. For example, if the value is 10, the new ack deadline will expire 10 seconds after the `ModifyAckDeadline` call was made. Specifying zero may immediately make the message available for another pull request. + #[serde(rename="ackDeadlineSeconds")] + pub ack_deadline_seconds: Option, + /// List of acknowledgment IDs. + #[serde(rename="ackIds")] + pub ack_ids: Option>, +} + +impl RequestValue for ModifyAckDeadlineRequest {} + + +/// Request for the Publish 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*). +/// +/// * [topics publish projects](struct.ProjectTopicPublishCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct PublishRequest { + /// The messages to publish. + pub messages: Option>, +} + +impl RequestValue for PublishRequest {} + + +/// Defines an Identity and Access Management (IAM) policy. It is used to specify access control policies for Cloud Platform resources. A `Policy` consists of a list of `bindings`. A `Binding` binds a list of `members` to a `role`, where the members can be user accounts, Google groups, Google domains, and service accounts. A `role` is a named list of permissions defined by IAM. **Example** { "bindings": [ { "role": "roles/owner", "members": [ "user:mike@example.com", "group:admins@example.com", "domain:google.com", "serviceAccount:my-other-app@appspot.gserviceaccount.com"] }, { "role": "roles/viewer", "members": ["user:sean@example.com"] } ] } For a description of IAM and its features, see the [IAM developer's guide](https://cloud.google.com/iam). +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where 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 iam policy projects](struct.ProjectSubscriptionGetIamPolicyCall.html) (response) +/// * [topics get iam policy projects](struct.ProjectTopicGetIamPolicyCall.html) (response) +/// * [subscriptions set iam policy projects](struct.ProjectSubscriptionSetIamPolicyCall.html) (response) +/// * [topics set iam policy projects](struct.ProjectTopicSetIamPolicyCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Policy { + /// Associates a list of `members` to a `role`. Multiple `bindings` must not be specified for the same `role`. `bindings` with no members will result in an error. + pub bindings: Option>, + /// Version of the `Policy`. The default version is 0. + pub version: Option, + /// Can be used to perform a read-modify-write. + pub etag: Option, +} + +impl ResponseResult for Policy {} + + +/// Response for the `ListSubscriptions` 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*). +/// +/// * [subscriptions list projects](struct.ProjectSubscriptionListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ListSubscriptionsResponse { + /// If not empty, indicates that there may be more subscriptions that match the request; this value should be passed in a new `ListSubscriptionsRequest` to get more subscriptions. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// The subscriptions that match the request. + pub subscriptions: Option>, +} + +impl ResponseResult for ListSubscriptionsResponse {} + + +/// Response for the `ListTopics` 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*). +/// +/// * [topics list projects](struct.ProjectTopicListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ListTopicsResponse { + /// If not empty, indicates that there may be more topics that match the request; this value should be passed in a new `ListTopicsRequest`. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// The resulting topics. + pub topics: Option>, +} + +impl ResponseResult for ListTopicsResponse {} + + +/// Request for the ModifyPushConfig 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*). +/// +/// * [subscriptions modify push config projects](struct.ProjectSubscriptionModifyPushConfigCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ModifyPushConfigRequest { + /// The push configuration for future deliveries. An empty `pushConfig` indicates that the Pub/Sub system should stop pushing messages from the given subscription and allow messages to be pulled and acknowledged - effectively pausing the subscription if `Pull` is not called. + #[serde(rename="pushConfig")] + pub push_config: Option, +} + +impl RequestValue for ModifyPushConfigRequest {} + + +/// A generic empty message that you can re-use to avoid defining duplicated empty messages in your APIs. A typical example is to use it as the request or the response type of an API method. For instance: service Foo { rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); } The JSON representation for `Empty` is empty JSON object `{}`. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where 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 acknowledge projects](struct.ProjectSubscriptionAcknowledgeCall.html) (response) +/// * [subscriptions modify push config projects](struct.ProjectSubscriptionModifyPushConfigCall.html) (response) +/// * [subscriptions delete projects](struct.ProjectSubscriptionDeleteCall.html) (response) +/// * [topics delete projects](struct.ProjectTopicDeleteCall.html) (response) +/// * [subscriptions modify ack deadline projects](struct.ProjectSubscriptionModifyAckDeadlineCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Empty; + +impl ResponseResult for Empty {} + + +/// Response message for `TestIamPermissions` 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*). +/// +/// * [subscriptions test iam permissions projects](struct.ProjectSubscriptionTestIamPermissionCall.html) (response) +/// * [topics test iam permissions projects](struct.ProjectTopicTestIamPermissionCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct TestIamPermissionsResponse { + /// A subset of `TestPermissionsRequest.permissions` that the caller is allowed. + pub permissions: Option>, +} + +impl ResponseResult for TestIamPermissionsResponse {} + + +/// Request for the `Pull` 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*). +/// +/// * [subscriptions pull projects](struct.ProjectSubscriptionPullCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct PullRequest { + /// If this is specified as true the system will respond immediately even if it is not able to return a message in the `Pull` response. Otherwise the system is allowed to wait until at least one message is available rather than returning no messages. The client may cancel the request if it does not wish to wait any longer for the response. + #[serde(rename="returnImmediately")] + pub return_immediately: Option, + /// The maximum number of messages returned for this request. The Pub/Sub system may return fewer than the number specified. + #[serde(rename="maxMessages")] + pub max_messages: Option, +} + +impl RequestValue for PullRequest {} + + +/// Associates `members` with a `role`. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Binding { + /// Role that is assigned to `members`. For example, `roles/viewer`, `roles/editor`, or `roles/owner`. Required + pub role: Option, + /// Specifies the identities requesting access for a Cloud Platform resource. `members` can have the following formats: * `allUsers`: A special identifier that represents anyone who is on the internet; with or without a Google account. * `allAuthenticatedUsers`: A special identifier that represents anyone who is authenticated with a Google account or a service account. * `user:{emailid}`: An email address that represents a specific Google account. For example, `alice@gmail.com` or `joe@example.com`. * `serviceAccount:{emailid}`: An email address that represents a service account. For example, `my-other-app@appspot.gserviceaccount.com`. * `group:{emailid}`: An email address that represents a Google group. For example, `admins@example.com`. * `domain:{domain}`: A Google Apps domain name that represents all the users of that domain. For example, `google.com` or `example.com`. + pub members: Option>, +} + +impl Part for Binding {} + + +/// A topic 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*). +/// +/// * [topics create projects](struct.ProjectTopicCreateCall.html) (request|response) +/// * [topics get projects](struct.ProjectTopicGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Topic { + /// The name of the topic. It must have the format `"projects/{project}/topics/{topic}"`. `{topic}` must start with a letter, and contain only letters (`[A-Za-z]`), numbers (`[0-9]`), dashes (`-`), underscores (`_`), periods (`.`), tildes (`~`), plus (`+`) or percent signs (`%`). It must be between 3 and 255 characters in length, and it must not start with `"goog"`. + pub name: Option, +} + +impl RequestValue for Topic {} +impl ResponseResult for Topic {} + + +/// Response for the `Publish` 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*). +/// +/// * [topics publish projects](struct.ProjectTopicPublishCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct PublishResponse { + /// The server-assigned ID of each published message, in the same order as the messages in the request. IDs are guaranteed to be unique within the topic. + #[serde(rename="messageIds")] + pub message_ids: Option>, +} + +impl ResponseResult for PublishResponse {} + + +/// Response for the `Pull` 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*). +/// +/// * [subscriptions pull projects](struct.ProjectSubscriptionPullCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct PullResponse { + /// Received Pub/Sub messages. The Pub/Sub system will return zero messages if there are no more available in the backlog. The Pub/Sub system may return fewer than the `maxMessages` requested even if there are more messages available in the backlog. + #[serde(rename="receivedMessages")] + pub received_messages: Option>, +} + +impl ResponseResult for PullResponse {} + + +/// A message data and its attributes. The message payload must not be empty; it must contain either a non-empty data field, or at least one attribute. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct PubsubMessage { + /// Optional attributes for this message. + pub attributes: Option>, + /// The message payload. For JSON requests, the value of this field must be base64-encoded. + pub data: Option, + /// ID of this message assigned by the server at publication time. Guaranteed to be unique within the topic. This value may be read by a subscriber that receives a `PubsubMessage` via a `Pull` call or a push delivery. It must not be populated by a publisher in a `Publish` call. + #[serde(rename="messageId")] + pub message_id: Option, +} + +impl Part for PubsubMessage {} + + +/// Configuration for a push delivery endpoint. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct PushConfig { + /// Endpoint configuration attributes. Every endpoint has a set of API supported attributes that can be used to control different aspects of the message delivery. The currently supported attribute is `x-goog-version`, which you can use to change the format of the push message. This attribute indicates the version of the data expected by the endpoint. This controls the shape of the envelope (i.e. its fields and metadata). The endpoint version is based on the version of the Pub/Sub API. If not present during the `CreateSubscription` call, it will default to the version of the API used to make such call. If not present during a `ModifyPushConfig` call, its value will not be changed. `GetSubscription` calls will always return a valid version, even if the subscription was created without this attribute. The possible values for this attribute are: * `v1beta1`: uses the push format defined in the v1beta1 Pub/Sub API. * `v1` or `v1beta2`: uses the push format defined in the v1 Pub/Sub API. + pub attributes: Option>, + /// A URL locating the endpoint to which messages should be pushed. For example, a Webhook endpoint might use "https://example.com/push". + #[serde(rename="pushEndpoint")] + pub push_endpoint: Option, +} + +impl Part for PushConfig {} + + +/// A subscription 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*). +/// +/// * [subscriptions create projects](struct.ProjectSubscriptionCreateCall.html) (request|response) +/// * [subscriptions get projects](struct.ProjectSubscriptionGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Subscription { + /// The name of the topic from which this subscription is receiving messages. The value of this field will be `_deleted-topic_` if the topic has been deleted. + pub topic: Option, + /// This value is the maximum time after a subscriber receives a message before the subscriber should acknowledge the message. After message delivery but before the ack deadline expires and before the message is acknowledged, it is an outstanding message and will not be delivered again during that time (on a best-effort basis). For pull delivery this value is used as the initial value for the ack deadline. To override this value for a given message, call `ModifyAckDeadline` with the corresponding `ack_id`. For push delivery, this value is also used to set the request timeout for the call to the push endpoint. If the subscriber never acknowledges the message, the Pub/Sub system will eventually redeliver the message. If this parameter is not set, the default value of 10 seconds is used. + #[serde(rename="ackDeadlineSeconds")] + pub ack_deadline_seconds: Option, + /// If push delivery is used with this subscription, this field is used to configure it. An empty `pushConfig` signifies that the subscriber will pull and ack messages using API methods. + #[serde(rename="pushConfig")] + pub push_config: Option, + /// The name of the subscription. It must have the format `"projects/{project}/subscriptions/{subscription}"`. `{subscription}` must start with a letter, and contain only letters (`[A-Za-z]`), numbers (`[0-9]`), dashes (`-`), underscores (`_`), periods (`.`), tildes (`~`), plus (`+`) or percent signs (`%`). It must be between 3 and 255 characters in length, and it must not start with `"goog"`. + pub name: Option, +} + +impl RequestValue for Subscription {} +impl ResponseResult for Subscription {} + + + +// ################### +// MethodBuilders ### +// ################# + +/// A builder providing access to all methods supported on *project* resources. +/// It is not used directly, but through the `Pubsub` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate yup_oauth2 as oauth2; +/// extern crate google_pubsub1 as pubsub1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use pubsub1::Pubsub; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Pubsub::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `subscriptions_acknowledge(...)`, `subscriptions_create(...)`, `subscriptions_delete(...)`, `subscriptions_get(...)`, `subscriptions_get_iam_policy(...)`, `subscriptions_list(...)`, `subscriptions_modify_ack_deadline(...)`, `subscriptions_modify_push_config(...)`, `subscriptions_pull(...)`, `subscriptions_set_iam_policy(...)`, `subscriptions_test_iam_permissions(...)`, `topics_create(...)`, `topics_delete(...)`, `topics_get(...)`, `topics_get_iam_policy(...)`, `topics_list(...)`, `topics_publish(...)`, `topics_set_iam_policy(...)`, `topics_subscriptions_list(...)` and `topics_test_iam_permissions(...)` +/// // to build up your call. +/// let rb = hub.projects(); +/// # } +/// ``` +pub struct ProjectMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Pubsub, +} + +impl<'a, C, A> MethodsBuilder for ProjectMethods<'a, C, A> {} + +impl<'a, C, A> ProjectMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Lists matching topics. + /// + /// # Arguments + /// + /// * `project` - The name of the cloud project that topics belong to. + pub fn topics_list(&self, project: &str) -> ProjectTopicListCall<'a, C, A> { + ProjectTopicListCall { + hub: self.hub, + _project: project.to_string(), + _page_token: Default::default(), + _page_size: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Pulls messages from the server. Returns an empty list if there are no messages available in the backlog. The server may return `UNAVAILABLE` if there are too many concurrent pull requests pending for the given subscription. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `subscription` - The subscription from which messages should be pulled. + pub fn subscriptions_pull(&self, request: PullRequest, subscription: &str) -> ProjectSubscriptionPullCall<'a, C, A> { + ProjectSubscriptionPullCall { + hub: self.hub, + _request: request, + _subscription: subscription.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Creates the given topic with the given name. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `name` - The name of the topic. It must have the format `"projects/{project}/topics/{topic}"`. `{topic}` must start with a letter, and contain only letters (`[A-Za-z]`), numbers (`[0-9]`), dashes (`-`), underscores (`_`), periods (`.`), tildes (`~`), plus (`+`) or percent signs (`%`). It must be between 3 and 255 characters in length, and it must not start with `"goog"`. + pub fn topics_create(&self, request: Topic, name: &str) -> ProjectTopicCreateCall<'a, C, A> { + ProjectTopicCreateCall { + hub: self.hub, + _request: request, + _name: name.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Returns permissions that a caller has on the specified resource. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `resource` - REQUIRED: The resource for which policy detail is being requested. `resource` is usually specified as a path, such as, `projects/{project}`. + pub fn topics_test_iam_permissions(&self, request: TestIamPermissionsRequest, resource: &str) -> ProjectTopicTestIamPermissionCall<'a, C, A> { + ProjectTopicTestIamPermissionCall { + hub: self.hub, + _request: request, + _resource: resource.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Modifies the `PushConfig` for a specified subscription. This may be used to change a push subscription to a pull one (signified by an empty `PushConfig`) or vice versa, or change the endpoint URL and other attributes of a push subscription. Messages will accumulate for delivery continuously through the call regardless of changes to the `PushConfig`. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `subscription` - The name of the subscription. + pub fn subscriptions_modify_push_config(&self, request: ModifyPushConfigRequest, subscription: &str) -> ProjectSubscriptionModifyPushConfigCall<'a, C, A> { + ProjectSubscriptionModifyPushConfigCall { + hub: self.hub, + _request: request, + _subscription: subscription.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Adds one or more messages to the topic. Returns `NOT_FOUND` if the topic does not exist. The message payload must not be empty; it must contain either a non-empty data field, or at least one attribute. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `topic` - The messages in the request will be published on this topic. + pub fn topics_publish(&self, request: PublishRequest, topic: &str) -> ProjectTopicPublishCall<'a, C, A> { + ProjectTopicPublishCall { + hub: self.hub, + _request: request, + _topic: topic.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets the configuration of a topic. + /// + /// # Arguments + /// + /// * `topic` - The name of the topic to get. + pub fn topics_get(&self, topic: &str) -> ProjectTopicGetCall<'a, C, A> { + ProjectTopicGetCall { + hub: self.hub, + _topic: topic.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets the access control policy for a `resource`. Is empty if the policy or the resource does not exist. + /// + /// # Arguments + /// + /// * `resource` - REQUIRED: The resource for which policy is being requested. Resource is usually specified as a path, such as, `projects/{project}`. + pub fn topics_get_iam_policy(&self, resource: &str) -> ProjectTopicGetIamPolicyCall<'a, C, A> { + ProjectTopicGetIamPolicyCall { + hub: self.hub, + _resource: resource.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Modifies the ack deadline for a specific message. This method is useful to indicate that more time is needed to process a message by the subscriber, or to make the message available for redelivery if the processing was interrupted. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `subscription` - The name of the subscription. + pub fn subscriptions_modify_ack_deadline(&self, request: ModifyAckDeadlineRequest, subscription: &str) -> ProjectSubscriptionModifyAckDeadlineCall<'a, C, A> { + ProjectSubscriptionModifyAckDeadlineCall { + hub: self.hub, + _request: request, + _subscription: subscription.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 subscription. All pending messages in the subscription are immediately dropped. Calls to `Pull` after deletion will return `NOT_FOUND`. After a subscription is deleted, a new one may be created with the same name, but the new one has no association with the old subscription, or its topic unless the same topic is specified. + /// + /// # Arguments + /// + /// * `subscription` - The subscription to delete. + pub fn subscriptions_delete(&self, subscription: &str) -> ProjectSubscriptionDeleteCall<'a, C, A> { + ProjectSubscriptionDeleteCall { + hub: self.hub, + _subscription: subscription.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Sets the access control policy on the specified resource. Replaces any existing policy. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `resource` - REQUIRED: The resource for which policy is being specified. `resource` is usually specified as a path, such as, `projects/{project}/zones/{zone}/disks/{disk}`. + pub fn topics_set_iam_policy(&self, request: SetIamPolicyRequest, resource: &str) -> ProjectTopicSetIamPolicyCall<'a, C, A> { + ProjectTopicSetIamPolicyCall { + hub: self.hub, + _request: request, + _resource: resource.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Creates a subscription to a given topic for a given subscriber. If the subscription already exists, returns `ALREADY_EXISTS`. If the corresponding topic doesn't exist, returns `NOT_FOUND`. If the name is not provided in the request, the server will assign a random name for this subscription on the same project as the topic. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `name` - The name of the subscription. It must have the format `"projects/{project}/subscriptions/{subscription}"`. `{subscription}` must start with a letter, and contain only letters (`[A-Za-z]`), numbers (`[0-9]`), dashes (`-`), underscores (`_`), periods (`.`), tildes (`~`), plus (`+`) or percent signs (`%`). It must be between 3 and 255 characters in length, and it must not start with `"goog"`. + pub fn subscriptions_create(&self, request: Subscription, name: &str) -> ProjectSubscriptionCreateCall<'a, C, A> { + ProjectSubscriptionCreateCall { + hub: self.hub, + _request: request, + _name: name.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Acknowledges the messages associated with the `ack_ids` in the `AcknowledgeRequest`. The Pub/Sub system can remove the relevant messages from the subscription. Acknowledging a message whose ack deadline has expired may succeed, but such a message may be redelivered later. Acknowledging a message more than once will not result in an error. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `subscription` - The subscription whose message is being acknowledged. + pub fn subscriptions_acknowledge(&self, request: AcknowledgeRequest, subscription: &str) -> ProjectSubscriptionAcknowledgeCall<'a, C, A> { + ProjectSubscriptionAcknowledgeCall { + hub: self.hub, + _request: request, + _subscription: subscription.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets the access control policy for a `resource`. Is empty if the policy or the resource does not exist. + /// + /// # Arguments + /// + /// * `resource` - REQUIRED: The resource for which policy is being requested. Resource is usually specified as a path, such as, `projects/{project}`. + pub fn subscriptions_get_iam_policy(&self, resource: &str) -> ProjectSubscriptionGetIamPolicyCall<'a, C, A> { + ProjectSubscriptionGetIamPolicyCall { + hub: self.hub, + _resource: resource.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Returns permissions that a caller has on the specified resource. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `resource` - REQUIRED: The resource for which policy detail is being requested. `resource` is usually specified as a path, such as, `projects/{project}`. + pub fn subscriptions_test_iam_permissions(&self, request: TestIamPermissionsRequest, resource: &str) -> ProjectSubscriptionTestIamPermissionCall<'a, C, A> { + ProjectSubscriptionTestIamPermissionCall { + hub: self.hub, + _request: request, + _resource: resource.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Deletes the topic with the given name. Returns `NOT_FOUND` if the topic does not exist. After a topic is deleted, a new topic may be created with the same name; this is an entirely new topic with none of the old configuration or subscriptions. Existing subscriptions to this topic are not deleted, but their `topic` field is set to `_deleted-topic_`. + /// + /// # Arguments + /// + /// * `topic` - Name of the topic to delete. + pub fn topics_delete(&self, topic: &str) -> ProjectTopicDeleteCall<'a, C, A> { + ProjectTopicDeleteCall { + hub: self.hub, + _topic: topic.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets the configuration details of a subscription. + /// + /// # Arguments + /// + /// * `subscription` - The name of the subscription to get. + pub fn subscriptions_get(&self, subscription: &str) -> ProjectSubscriptionGetCall<'a, C, A> { + ProjectSubscriptionGetCall { + hub: self.hub, + _subscription: subscription.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Lists the name of the subscriptions for this topic. + /// + /// # Arguments + /// + /// * `topic` - The name of the topic that subscriptions are attached to. + pub fn topics_subscriptions_list(&self, topic: &str) -> ProjectTopicSubscriptionListCall<'a, C, A> { + ProjectTopicSubscriptionListCall { + hub: self.hub, + _topic: topic.to_string(), + _page_token: Default::default(), + _page_size: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Lists matching subscriptions. + /// + /// # Arguments + /// + /// * `project` - The name of the cloud project that subscriptions belong to. + pub fn subscriptions_list(&self, project: &str) -> ProjectSubscriptionListCall<'a, C, A> { + ProjectSubscriptionListCall { + hub: self.hub, + _project: project.to_string(), + _page_token: Default::default(), + _page_size: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Sets the access control policy on the specified resource. Replaces any existing policy. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `resource` - REQUIRED: The resource for which policy is being specified. `resource` is usually specified as a path, such as, `projects/{project}/zones/{zone}/disks/{disk}`. + pub fn subscriptions_set_iam_policy(&self, request: SetIamPolicyRequest, resource: &str) -> ProjectSubscriptionSetIamPolicyCall<'a, C, A> { + ProjectSubscriptionSetIamPolicyCall { + hub: self.hub, + _request: request, + _resource: resource.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + + + +// ################### +// CallBuilders ### +// ################# + +/// Lists matching topics. +/// +/// A builder for the *topics.list* method supported by a *project* resource. +/// It is not used directly, but through a `ProjectMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_pubsub1 as pubsub1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use pubsub1::Pubsub; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Pubsub::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling 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().topics_list("project") +/// .page_token("sed") +/// .page_size(-85) +/// .doit(); +/// # } +/// ``` +pub struct ProjectTopicListCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Pubsub, + _project: String, + _page_token: Option, + _page_size: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ProjectTopicListCall<'a, C, A> {} + +impl<'a, C, A> ProjectTopicListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ListTopicsResponse)> { + use url::percent_encoding::{percent_encode, FORM_URLENCODED_ENCODE_SET}; + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "pubsub.projects.topics.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._page_size { + params.push(("pageSize", value.to_string())); + } + for &field in ["alt", "project", "pageToken", "pageSize"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://pubsub.googleapis.com/v1/{+project}/topics".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{+project}", "project")].iter() { + let mut replace_with = String::new(); + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = value.to_string(); + break; + } + } + if find_this.as_bytes()[1] == '+' as u8 { + replace_with = percent_encode(replace_with.as_bytes(), FORM_URLENCODED_ENCODE_SET); + } + url = url.replace(find_this, &replace_with); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["project"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The name of the cloud project that topics belong to. + /// + /// 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) -> ProjectTopicListCall<'a, C, A> { + self._project = new_value.to_string(); + self + } + /// The value returned by the last `ListTopicsResponse`; indicates that this is a continuation of a prior `ListTopics` call, and that the system should return the next page of data. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> ProjectTopicListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Maximum number of topics to return. + /// + /// Sets the *page size* query property to the given value. + pub fn page_size(mut self, new_value: i32) -> ProjectTopicListCall<'a, C, A> { + self._page_size = Some(new_value); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectTopicListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> ProjectTopicListCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProjectTopicListCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Pulls messages from the server. Returns an empty list if there are no messages available in the backlog. The server may return `UNAVAILABLE` if there are too many concurrent pull requests pending for the given subscription. +/// +/// A builder for the *subscriptions.pull* method supported by a *project* resource. +/// It is not used directly, but through a `ProjectMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_pubsub1 as pubsub1; +/// use pubsub1::PullRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use pubsub1::Pubsub; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Pubsub::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req = PullRequest::default(); +/// +/// // You can configure optional parameters by calling 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().subscriptions_pull(req, "subscription") +/// .doit(); +/// # } +/// ``` +pub struct ProjectSubscriptionPullCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Pubsub, + _request: PullRequest, + _subscription: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ProjectSubscriptionPullCall<'a, C, A> {} + +impl<'a, C, A> ProjectSubscriptionPullCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, PullResponse)> { + use url::percent_encoding::{percent_encode, FORM_URLENCODED_ENCODE_SET}; + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "pubsub.projects.subscriptions.pull", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("subscription", self._subscription.to_string())); + for &field in ["alt", "subscription"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://pubsub.googleapis.com/v1/{+subscription}:pull".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{+subscription}", "subscription")].iter() { + let mut replace_with = String::new(); + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = value.to_string(); + break; + } + } + if find_this.as_bytes()[1] == '+' as u8 { + replace_with = percent_encode(replace_with.as_bytes(), FORM_URLENCODED_ENCODE_SET); + } + url = url.replace(find_this, &replace_with); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["subscription"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: PullRequest) -> ProjectSubscriptionPullCall<'a, C, A> { + self._request = new_value; + self + } + /// The subscription from which messages should be pulled. + /// + /// Sets the *subscription* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn subscription(mut self, new_value: &str) -> ProjectSubscriptionPullCall<'a, C, A> { + self._subscription = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectSubscriptionPullCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> ProjectSubscriptionPullCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProjectSubscriptionPullCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Creates the given topic with the given name. +/// +/// A builder for the *topics.create* method supported by a *project* resource. +/// It is not used directly, but through a `ProjectMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_pubsub1 as pubsub1; +/// use pubsub1::Topic; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use pubsub1::Pubsub; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Pubsub::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req = Topic::default(); +/// +/// // You can configure optional parameters by calling 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().topics_create(req, "name") +/// .doit(); +/// # } +/// ``` +pub struct ProjectTopicCreateCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Pubsub, + _request: Topic, + _name: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ProjectTopicCreateCall<'a, C, A> {} + +impl<'a, C, A> ProjectTopicCreateCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Topic)> { + use url::percent_encoding::{percent_encode, FORM_URLENCODED_ENCODE_SET}; + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "pubsub.projects.topics.create", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("name", self._name.to_string())); + for &field in ["alt", "name"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://pubsub.googleapis.com/v1/{+name}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{+name}", "name")].iter() { + let mut replace_with = String::new(); + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = value.to_string(); + break; + } + } + if find_this.as_bytes()[1] == '+' as u8 { + replace_with = percent_encode(replace_with.as_bytes(), FORM_URLENCODED_ENCODE_SET); + } + url = url.replace(find_this, &replace_with); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["name"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: Topic) -> ProjectTopicCreateCall<'a, C, A> { + self._request = new_value; + self + } + /// The name of the topic. It must have the format `"projects/{project}/topics/{topic}"`. `{topic}` must start with a letter, and contain only letters (`[A-Za-z]`), numbers (`[0-9]`), dashes (`-`), underscores (`_`), periods (`.`), tildes (`~`), plus (`+`) or percent signs (`%`). It must be between 3 and 255 characters in length, and it must not start with `"goog"`. + /// + /// Sets the *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 name(mut self, new_value: &str) -> ProjectTopicCreateCall<'a, C, A> { + self._name = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectTopicCreateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> ProjectTopicCreateCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProjectTopicCreateCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Returns permissions that a caller has on the specified resource. +/// +/// A builder for the *topics.testIamPermissions* method supported by a *project* resource. +/// It is not used directly, but through a `ProjectMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_pubsub1 as pubsub1; +/// use pubsub1::TestIamPermissionsRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use pubsub1::Pubsub; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Pubsub::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req = TestIamPermissionsRequest::default(); +/// +/// // You can configure optional parameters by calling 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().topics_test_iam_permissions(req, "resource") +/// .doit(); +/// # } +/// ``` +pub struct ProjectTopicTestIamPermissionCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Pubsub, + _request: TestIamPermissionsRequest, + _resource: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ProjectTopicTestIamPermissionCall<'a, C, A> {} + +impl<'a, C, A> ProjectTopicTestIamPermissionCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, TestIamPermissionsResponse)> { + use url::percent_encoding::{percent_encode, FORM_URLENCODED_ENCODE_SET}; + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "pubsub.projects.topics.testIamPermissions", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("resource", self._resource.to_string())); + for &field in ["alt", "resource"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://pubsub.googleapis.com/v1/{+resource}:testIamPermissions".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{+resource}", "resource")].iter() { + let mut replace_with = String::new(); + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = value.to_string(); + break; + } + } + if find_this.as_bytes()[1] == '+' as u8 { + replace_with = percent_encode(replace_with.as_bytes(), FORM_URLENCODED_ENCODE_SET); + } + url = url.replace(find_this, &replace_with); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["resource"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: TestIamPermissionsRequest) -> ProjectTopicTestIamPermissionCall<'a, C, A> { + self._request = new_value; + self + } + /// REQUIRED: The resource for which policy detail is being requested. `resource` is usually specified as a path, such as, `projects/{project}`. + /// + /// 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. + pub fn resource(mut self, new_value: &str) -> ProjectTopicTestIamPermissionCall<'a, C, A> { + self._resource = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectTopicTestIamPermissionCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> ProjectTopicTestIamPermissionCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProjectTopicTestIamPermissionCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Modifies the `PushConfig` for a specified subscription. This may be used to change a push subscription to a pull one (signified by an empty `PushConfig`) or vice versa, or change the endpoint URL and other attributes of a push subscription. Messages will accumulate for delivery continuously through the call regardless of changes to the `PushConfig`. +/// +/// A builder for the *subscriptions.modifyPushConfig* method supported by a *project* resource. +/// It is not used directly, but through a `ProjectMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_pubsub1 as pubsub1; +/// use pubsub1::ModifyPushConfigRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use pubsub1::Pubsub; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Pubsub::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req = ModifyPushConfigRequest::default(); +/// +/// // You can configure optional parameters by calling 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().subscriptions_modify_push_config(req, "subscription") +/// .doit(); +/// # } +/// ``` +pub struct ProjectSubscriptionModifyPushConfigCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Pubsub, + _request: ModifyPushConfigRequest, + _subscription: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ProjectSubscriptionModifyPushConfigCall<'a, C, A> {} + +impl<'a, C, A> ProjectSubscriptionModifyPushConfigCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Empty)> { + use url::percent_encoding::{percent_encode, FORM_URLENCODED_ENCODE_SET}; + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "pubsub.projects.subscriptions.modifyPushConfig", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("subscription", self._subscription.to_string())); + for &field in ["alt", "subscription"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://pubsub.googleapis.com/v1/{+subscription}:modifyPushConfig".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{+subscription}", "subscription")].iter() { + let mut replace_with = String::new(); + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = value.to_string(); + break; + } + } + if find_this.as_bytes()[1] == '+' as u8 { + replace_with = percent_encode(replace_with.as_bytes(), FORM_URLENCODED_ENCODE_SET); + } + url = url.replace(find_this, &replace_with); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["subscription"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: ModifyPushConfigRequest) -> ProjectSubscriptionModifyPushConfigCall<'a, C, A> { + self._request = new_value; + self + } + /// The name of the subscription. + /// + /// Sets the *subscription* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn subscription(mut self, new_value: &str) -> ProjectSubscriptionModifyPushConfigCall<'a, C, A> { + self._subscription = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectSubscriptionModifyPushConfigCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> ProjectSubscriptionModifyPushConfigCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProjectSubscriptionModifyPushConfigCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Adds one or more messages to the topic. Returns `NOT_FOUND` if the topic does not exist. The message payload must not be empty; it must contain either a non-empty data field, or at least one attribute. +/// +/// A builder for the *topics.publish* method supported by a *project* resource. +/// It is not used directly, but through a `ProjectMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_pubsub1 as pubsub1; +/// use pubsub1::PublishRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use pubsub1::Pubsub; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Pubsub::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req = PublishRequest::default(); +/// +/// // You can configure optional parameters by calling 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().topics_publish(req, "topic") +/// .doit(); +/// # } +/// ``` +pub struct ProjectTopicPublishCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Pubsub, + _request: PublishRequest, + _topic: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ProjectTopicPublishCall<'a, C, A> {} + +impl<'a, C, A> ProjectTopicPublishCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, PublishResponse)> { + use url::percent_encoding::{percent_encode, FORM_URLENCODED_ENCODE_SET}; + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "pubsub.projects.topics.publish", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("topic", self._topic.to_string())); + for &field in ["alt", "topic"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://pubsub.googleapis.com/v1/{+topic}:publish".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{+topic}", "topic")].iter() { + let mut replace_with = String::new(); + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = value.to_string(); + break; + } + } + if find_this.as_bytes()[1] == '+' as u8 { + replace_with = percent_encode(replace_with.as_bytes(), FORM_URLENCODED_ENCODE_SET); + } + url = url.replace(find_this, &replace_with); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["topic"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: PublishRequest) -> ProjectTopicPublishCall<'a, C, A> { + self._request = new_value; + self + } + /// The messages in the request will be published on this topic. + /// + /// Sets the *topic* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn topic(mut self, new_value: &str) -> ProjectTopicPublishCall<'a, C, A> { + self._topic = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectTopicPublishCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> ProjectTopicPublishCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProjectTopicPublishCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Gets the configuration of a topic. +/// +/// A builder for the *topics.get* method supported by a *project* resource. +/// It is not used directly, but through a `ProjectMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_pubsub1 as pubsub1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use pubsub1::Pubsub; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Pubsub::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling 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().topics_get("topic") +/// .doit(); +/// # } +/// ``` +pub struct ProjectTopicGetCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Pubsub, + _topic: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ProjectTopicGetCall<'a, C, A> {} + +impl<'a, C, A> ProjectTopicGetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Topic)> { + use url::percent_encoding::{percent_encode, FORM_URLENCODED_ENCODE_SET}; + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "pubsub.projects.topics.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("topic", self._topic.to_string())); + for &field in ["alt", "topic"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://pubsub.googleapis.com/v1/{+topic}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{+topic}", "topic")].iter() { + let mut replace_with = String::new(); + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = value.to_string(); + break; + } + } + if find_this.as_bytes()[1] == '+' as u8 { + replace_with = percent_encode(replace_with.as_bytes(), FORM_URLENCODED_ENCODE_SET); + } + url = url.replace(find_this, &replace_with); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["topic"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The name of the topic to get. + /// + /// Sets the *topic* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn topic(mut self, new_value: &str) -> ProjectTopicGetCall<'a, C, A> { + self._topic = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectTopicGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> ProjectTopicGetCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProjectTopicGetCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Gets the access control policy for a `resource`. Is empty if the policy or the resource does not exist. +/// +/// A builder for the *topics.getIamPolicy* method supported by a *project* resource. +/// It is not used directly, but through a `ProjectMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_pubsub1 as pubsub1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use pubsub1::Pubsub; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Pubsub::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling 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().topics_get_iam_policy("resource") +/// .doit(); +/// # } +/// ``` +pub struct ProjectTopicGetIamPolicyCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Pubsub, + _resource: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ProjectTopicGetIamPolicyCall<'a, C, A> {} + +impl<'a, C, A> ProjectTopicGetIamPolicyCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Policy)> { + use url::percent_encoding::{percent_encode, FORM_URLENCODED_ENCODE_SET}; + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "pubsub.projects.topics.getIamPolicy", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("resource", self._resource.to_string())); + for &field in ["alt", "resource"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://pubsub.googleapis.com/v1/{+resource}:getIamPolicy".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{+resource}", "resource")].iter() { + let mut replace_with = String::new(); + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = value.to_string(); + break; + } + } + if find_this.as_bytes()[1] == '+' as u8 { + replace_with = percent_encode(replace_with.as_bytes(), FORM_URLENCODED_ENCODE_SET); + } + url = url.replace(find_this, &replace_with); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["resource"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// REQUIRED: The resource for which policy is being requested. Resource is usually specified as a path, such as, `projects/{project}`. + /// + /// 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. + pub fn resource(mut self, new_value: &str) -> ProjectTopicGetIamPolicyCall<'a, C, A> { + self._resource = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectTopicGetIamPolicyCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> ProjectTopicGetIamPolicyCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProjectTopicGetIamPolicyCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Modifies the ack deadline for a specific message. This method is useful to indicate that more time is needed to process a message by the subscriber, or to make the message available for redelivery if the processing was interrupted. +/// +/// A builder for the *subscriptions.modifyAckDeadline* method supported by a *project* resource. +/// It is not used directly, but through a `ProjectMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_pubsub1 as pubsub1; +/// use pubsub1::ModifyAckDeadlineRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use pubsub1::Pubsub; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Pubsub::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req = ModifyAckDeadlineRequest::default(); +/// +/// // You can configure optional parameters by calling 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().subscriptions_modify_ack_deadline(req, "subscription") +/// .doit(); +/// # } +/// ``` +pub struct ProjectSubscriptionModifyAckDeadlineCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Pubsub, + _request: ModifyAckDeadlineRequest, + _subscription: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ProjectSubscriptionModifyAckDeadlineCall<'a, C, A> {} + +impl<'a, C, A> ProjectSubscriptionModifyAckDeadlineCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Empty)> { + use url::percent_encoding::{percent_encode, FORM_URLENCODED_ENCODE_SET}; + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "pubsub.projects.subscriptions.modifyAckDeadline", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("subscription", self._subscription.to_string())); + for &field in ["alt", "subscription"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://pubsub.googleapis.com/v1/{+subscription}:modifyAckDeadline".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{+subscription}", "subscription")].iter() { + let mut replace_with = String::new(); + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = value.to_string(); + break; + } + } + if find_this.as_bytes()[1] == '+' as u8 { + replace_with = percent_encode(replace_with.as_bytes(), FORM_URLENCODED_ENCODE_SET); + } + url = url.replace(find_this, &replace_with); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["subscription"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: ModifyAckDeadlineRequest) -> ProjectSubscriptionModifyAckDeadlineCall<'a, C, A> { + self._request = new_value; + self + } + /// The name of the subscription. + /// + /// Sets the *subscription* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn subscription(mut self, new_value: &str) -> ProjectSubscriptionModifyAckDeadlineCall<'a, C, A> { + self._subscription = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectSubscriptionModifyAckDeadlineCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> ProjectSubscriptionModifyAckDeadlineCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProjectSubscriptionModifyAckDeadlineCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Deletes an existing subscription. All pending messages in the subscription are immediately dropped. Calls to `Pull` after deletion will return `NOT_FOUND`. After a subscription is deleted, a new one may be created with the same name, but the new one has no association with the old subscription, or its topic unless the same topic is specified. +/// +/// A builder for the *subscriptions.delete* method supported by a *project* resource. +/// It is not used directly, but through a `ProjectMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_pubsub1 as pubsub1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use pubsub1::Pubsub; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Pubsub::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling 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().subscriptions_delete("subscription") +/// .doit(); +/// # } +/// ``` +pub struct ProjectSubscriptionDeleteCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Pubsub, + _subscription: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ProjectSubscriptionDeleteCall<'a, C, A> {} + +impl<'a, C, A> ProjectSubscriptionDeleteCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Empty)> { + use url::percent_encoding::{percent_encode, FORM_URLENCODED_ENCODE_SET}; + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "pubsub.projects.subscriptions.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("subscription", self._subscription.to_string())); + for &field in ["alt", "subscription"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://pubsub.googleapis.com/v1/{+subscription}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{+subscription}", "subscription")].iter() { + let mut replace_with = String::new(); + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = value.to_string(); + break; + } + } + if find_this.as_bytes()[1] == '+' as u8 { + replace_with = percent_encode(replace_with.as_bytes(), FORM_URLENCODED_ENCODE_SET); + } + url = url.replace(find_this, &replace_with); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["subscription"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The subscription to delete. + /// + /// Sets the *subscription* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn subscription(mut self, new_value: &str) -> ProjectSubscriptionDeleteCall<'a, C, A> { + self._subscription = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectSubscriptionDeleteCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> ProjectSubscriptionDeleteCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProjectSubscriptionDeleteCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Sets the access control policy on the specified resource. Replaces any existing policy. +/// +/// A builder for the *topics.setIamPolicy* method supported by a *project* resource. +/// It is not used directly, but through a `ProjectMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_pubsub1 as pubsub1; +/// use pubsub1::SetIamPolicyRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use pubsub1::Pubsub; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Pubsub::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req = SetIamPolicyRequest::default(); +/// +/// // You can configure optional parameters by calling 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().topics_set_iam_policy(req, "resource") +/// .doit(); +/// # } +/// ``` +pub struct ProjectTopicSetIamPolicyCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Pubsub, + _request: SetIamPolicyRequest, + _resource: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ProjectTopicSetIamPolicyCall<'a, C, A> {} + +impl<'a, C, A> ProjectTopicSetIamPolicyCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Policy)> { + use url::percent_encoding::{percent_encode, FORM_URLENCODED_ENCODE_SET}; + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "pubsub.projects.topics.setIamPolicy", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("resource", self._resource.to_string())); + for &field in ["alt", "resource"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://pubsub.googleapis.com/v1/{+resource}:setIamPolicy".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{+resource}", "resource")].iter() { + let mut replace_with = String::new(); + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = value.to_string(); + break; + } + } + if find_this.as_bytes()[1] == '+' as u8 { + replace_with = percent_encode(replace_with.as_bytes(), FORM_URLENCODED_ENCODE_SET); + } + url = url.replace(find_this, &replace_with); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["resource"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: SetIamPolicyRequest) -> ProjectTopicSetIamPolicyCall<'a, C, A> { + self._request = new_value; + self + } + /// REQUIRED: The resource for which policy is being specified. `resource` is usually specified as a path, such as, `projects/{project}/zones/{zone}/disks/{disk}`. + /// + /// 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. + pub fn resource(mut self, new_value: &str) -> ProjectTopicSetIamPolicyCall<'a, C, A> { + self._resource = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectTopicSetIamPolicyCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> ProjectTopicSetIamPolicyCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProjectTopicSetIamPolicyCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Creates a subscription to a given topic for a given subscriber. If the subscription already exists, returns `ALREADY_EXISTS`. If the corresponding topic doesn't exist, returns `NOT_FOUND`. If the name is not provided in the request, the server will assign a random name for this subscription on the same project as the topic. +/// +/// A builder for the *subscriptions.create* method supported by a *project* resource. +/// It is not used directly, but through a `ProjectMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_pubsub1 as pubsub1; +/// use pubsub1::Subscription; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use pubsub1::Pubsub; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Pubsub::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req = Subscription::default(); +/// +/// // You can configure optional parameters by calling 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().subscriptions_create(req, "name") +/// .doit(); +/// # } +/// ``` +pub struct ProjectSubscriptionCreateCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Pubsub, + _request: Subscription, + _name: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ProjectSubscriptionCreateCall<'a, C, A> {} + +impl<'a, C, A> ProjectSubscriptionCreateCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Subscription)> { + use url::percent_encoding::{percent_encode, FORM_URLENCODED_ENCODE_SET}; + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "pubsub.projects.subscriptions.create", + http_method: hyper::method::Method::Put }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("name", self._name.to_string())); + for &field in ["alt", "name"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://pubsub.googleapis.com/v1/{+name}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{+name}", "name")].iter() { + let mut replace_with = String::new(); + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = value.to_string(); + break; + } + } + if find_this.as_bytes()[1] == '+' as u8 { + replace_with = percent_encode(replace_with.as_bytes(), FORM_URLENCODED_ENCODE_SET); + } + url = url.replace(find_this, &replace_with); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["name"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: Subscription) -> ProjectSubscriptionCreateCall<'a, C, A> { + self._request = new_value; + self + } + /// The name of the subscription. It must have the format `"projects/{project}/subscriptions/{subscription}"`. `{subscription}` must start with a letter, and contain only letters (`[A-Za-z]`), numbers (`[0-9]`), dashes (`-`), underscores (`_`), periods (`.`), tildes (`~`), plus (`+`) or percent signs (`%`). It must be between 3 and 255 characters in length, and it must not start with `"goog"`. + /// + /// Sets the *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 name(mut self, new_value: &str) -> ProjectSubscriptionCreateCall<'a, C, A> { + self._name = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectSubscriptionCreateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> ProjectSubscriptionCreateCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProjectSubscriptionCreateCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Acknowledges the messages associated with the `ack_ids` in the `AcknowledgeRequest`. The Pub/Sub system can remove the relevant messages from the subscription. Acknowledging a message whose ack deadline has expired may succeed, but such a message may be redelivered later. Acknowledging a message more than once will not result in an error. +/// +/// A builder for the *subscriptions.acknowledge* method supported by a *project* resource. +/// It is not used directly, but through a `ProjectMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_pubsub1 as pubsub1; +/// use pubsub1::AcknowledgeRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use pubsub1::Pubsub; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Pubsub::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req = AcknowledgeRequest::default(); +/// +/// // You can configure optional parameters by calling 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().subscriptions_acknowledge(req, "subscription") +/// .doit(); +/// # } +/// ``` +pub struct ProjectSubscriptionAcknowledgeCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Pubsub, + _request: AcknowledgeRequest, + _subscription: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ProjectSubscriptionAcknowledgeCall<'a, C, A> {} + +impl<'a, C, A> ProjectSubscriptionAcknowledgeCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Empty)> { + use url::percent_encoding::{percent_encode, FORM_URLENCODED_ENCODE_SET}; + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "pubsub.projects.subscriptions.acknowledge", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("subscription", self._subscription.to_string())); + for &field in ["alt", "subscription"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://pubsub.googleapis.com/v1/{+subscription}:acknowledge".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{+subscription}", "subscription")].iter() { + let mut replace_with = String::new(); + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = value.to_string(); + break; + } + } + if find_this.as_bytes()[1] == '+' as u8 { + replace_with = percent_encode(replace_with.as_bytes(), FORM_URLENCODED_ENCODE_SET); + } + url = url.replace(find_this, &replace_with); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["subscription"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: AcknowledgeRequest) -> ProjectSubscriptionAcknowledgeCall<'a, C, A> { + self._request = new_value; + self + } + /// The subscription whose message is being acknowledged. + /// + /// Sets the *subscription* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn subscription(mut self, new_value: &str) -> ProjectSubscriptionAcknowledgeCall<'a, C, A> { + self._subscription = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectSubscriptionAcknowledgeCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> ProjectSubscriptionAcknowledgeCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProjectSubscriptionAcknowledgeCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Gets the access control policy for a `resource`. Is empty if the policy or the resource does not exist. +/// +/// A builder for the *subscriptions.getIamPolicy* method supported by a *project* resource. +/// It is not used directly, but through a `ProjectMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_pubsub1 as pubsub1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use pubsub1::Pubsub; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Pubsub::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling 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().subscriptions_get_iam_policy("resource") +/// .doit(); +/// # } +/// ``` +pub struct ProjectSubscriptionGetIamPolicyCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Pubsub, + _resource: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ProjectSubscriptionGetIamPolicyCall<'a, C, A> {} + +impl<'a, C, A> ProjectSubscriptionGetIamPolicyCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Policy)> { + use url::percent_encoding::{percent_encode, FORM_URLENCODED_ENCODE_SET}; + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "pubsub.projects.subscriptions.getIamPolicy", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("resource", self._resource.to_string())); + for &field in ["alt", "resource"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://pubsub.googleapis.com/v1/{+resource}:getIamPolicy".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{+resource}", "resource")].iter() { + let mut replace_with = String::new(); + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = value.to_string(); + break; + } + } + if find_this.as_bytes()[1] == '+' as u8 { + replace_with = percent_encode(replace_with.as_bytes(), FORM_URLENCODED_ENCODE_SET); + } + url = url.replace(find_this, &replace_with); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["resource"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// REQUIRED: The resource for which policy is being requested. Resource is usually specified as a path, such as, `projects/{project}`. + /// + /// 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. + pub fn resource(mut self, new_value: &str) -> ProjectSubscriptionGetIamPolicyCall<'a, C, A> { + self._resource = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectSubscriptionGetIamPolicyCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> ProjectSubscriptionGetIamPolicyCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProjectSubscriptionGetIamPolicyCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Returns permissions that a caller has on the specified resource. +/// +/// A builder for the *subscriptions.testIamPermissions* method supported by a *project* resource. +/// It is not used directly, but through a `ProjectMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_pubsub1 as pubsub1; +/// use pubsub1::TestIamPermissionsRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use pubsub1::Pubsub; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Pubsub::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req = TestIamPermissionsRequest::default(); +/// +/// // You can configure optional parameters by calling 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().subscriptions_test_iam_permissions(req, "resource") +/// .doit(); +/// # } +/// ``` +pub struct ProjectSubscriptionTestIamPermissionCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Pubsub, + _request: TestIamPermissionsRequest, + _resource: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ProjectSubscriptionTestIamPermissionCall<'a, C, A> {} + +impl<'a, C, A> ProjectSubscriptionTestIamPermissionCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, TestIamPermissionsResponse)> { + use url::percent_encoding::{percent_encode, FORM_URLENCODED_ENCODE_SET}; + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "pubsub.projects.subscriptions.testIamPermissions", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("resource", self._resource.to_string())); + for &field in ["alt", "resource"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://pubsub.googleapis.com/v1/{+resource}:testIamPermissions".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{+resource}", "resource")].iter() { + let mut replace_with = String::new(); + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = value.to_string(); + break; + } + } + if find_this.as_bytes()[1] == '+' as u8 { + replace_with = percent_encode(replace_with.as_bytes(), FORM_URLENCODED_ENCODE_SET); + } + url = url.replace(find_this, &replace_with); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["resource"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: TestIamPermissionsRequest) -> ProjectSubscriptionTestIamPermissionCall<'a, C, A> { + self._request = new_value; + self + } + /// REQUIRED: The resource for which policy detail is being requested. `resource` is usually specified as a path, such as, `projects/{project}`. + /// + /// 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. + pub fn resource(mut self, new_value: &str) -> ProjectSubscriptionTestIamPermissionCall<'a, C, A> { + self._resource = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectSubscriptionTestIamPermissionCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> ProjectSubscriptionTestIamPermissionCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProjectSubscriptionTestIamPermissionCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Deletes the topic with the given name. Returns `NOT_FOUND` if the topic does not exist. After a topic is deleted, a new topic may be created with the same name; this is an entirely new topic with none of the old configuration or subscriptions. Existing subscriptions to this topic are not deleted, but their `topic` field is set to `_deleted-topic_`. +/// +/// A builder for the *topics.delete* method supported by a *project* resource. +/// It is not used directly, but through a `ProjectMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_pubsub1 as pubsub1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use pubsub1::Pubsub; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Pubsub::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling 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().topics_delete("topic") +/// .doit(); +/// # } +/// ``` +pub struct ProjectTopicDeleteCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Pubsub, + _topic: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ProjectTopicDeleteCall<'a, C, A> {} + +impl<'a, C, A> ProjectTopicDeleteCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Empty)> { + use url::percent_encoding::{percent_encode, FORM_URLENCODED_ENCODE_SET}; + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "pubsub.projects.topics.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("topic", self._topic.to_string())); + for &field in ["alt", "topic"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://pubsub.googleapis.com/v1/{+topic}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{+topic}", "topic")].iter() { + let mut replace_with = String::new(); + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = value.to_string(); + break; + } + } + if find_this.as_bytes()[1] == '+' as u8 { + replace_with = percent_encode(replace_with.as_bytes(), FORM_URLENCODED_ENCODE_SET); + } + url = url.replace(find_this, &replace_with); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["topic"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Name of the topic to delete. + /// + /// Sets the *topic* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn topic(mut self, new_value: &str) -> ProjectTopicDeleteCall<'a, C, A> { + self._topic = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectTopicDeleteCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> ProjectTopicDeleteCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProjectTopicDeleteCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Gets the configuration details of a subscription. +/// +/// A builder for the *subscriptions.get* method supported by a *project* resource. +/// It is not used directly, but through a `ProjectMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_pubsub1 as pubsub1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use pubsub1::Pubsub; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Pubsub::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling 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().subscriptions_get("subscription") +/// .doit(); +/// # } +/// ``` +pub struct ProjectSubscriptionGetCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Pubsub, + _subscription: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ProjectSubscriptionGetCall<'a, C, A> {} + +impl<'a, C, A> ProjectSubscriptionGetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Subscription)> { + use url::percent_encoding::{percent_encode, FORM_URLENCODED_ENCODE_SET}; + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "pubsub.projects.subscriptions.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("subscription", self._subscription.to_string())); + for &field in ["alt", "subscription"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://pubsub.googleapis.com/v1/{+subscription}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{+subscription}", "subscription")].iter() { + let mut replace_with = String::new(); + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = value.to_string(); + break; + } + } + if find_this.as_bytes()[1] == '+' as u8 { + replace_with = percent_encode(replace_with.as_bytes(), FORM_URLENCODED_ENCODE_SET); + } + url = url.replace(find_this, &replace_with); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["subscription"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The name of the subscription to get. + /// + /// Sets the *subscription* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn subscription(mut self, new_value: &str) -> ProjectSubscriptionGetCall<'a, C, A> { + self._subscription = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectSubscriptionGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> ProjectSubscriptionGetCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProjectSubscriptionGetCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Lists the name of the subscriptions for this topic. +/// +/// A builder for the *topics.subscriptions.list* method supported by a *project* resource. +/// It is not used directly, but through a `ProjectMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_pubsub1 as pubsub1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use pubsub1::Pubsub; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Pubsub::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling 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().topics_subscriptions_list("topic") +/// .page_token("justo") +/// .page_size(-34) +/// .doit(); +/// # } +/// ``` +pub struct ProjectTopicSubscriptionListCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Pubsub, + _topic: String, + _page_token: Option, + _page_size: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ProjectTopicSubscriptionListCall<'a, C, A> {} + +impl<'a, C, A> ProjectTopicSubscriptionListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ListTopicSubscriptionsResponse)> { + use url::percent_encoding::{percent_encode, FORM_URLENCODED_ENCODE_SET}; + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "pubsub.projects.topics.subscriptions.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("topic", self._topic.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())); + } + for &field in ["alt", "topic", "pageToken", "pageSize"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://pubsub.googleapis.com/v1/{+topic}/subscriptions".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{+topic}", "topic")].iter() { + let mut replace_with = String::new(); + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = value.to_string(); + break; + } + } + if find_this.as_bytes()[1] == '+' as u8 { + replace_with = percent_encode(replace_with.as_bytes(), FORM_URLENCODED_ENCODE_SET); + } + url = url.replace(find_this, &replace_with); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["topic"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The name of the topic that subscriptions are attached to. + /// + /// Sets the *topic* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn topic(mut self, new_value: &str) -> ProjectTopicSubscriptionListCall<'a, C, A> { + self._topic = new_value.to_string(); + self + } + /// The value returned by the last `ListTopicSubscriptionsResponse`; indicates that this is a continuation of a prior `ListTopicSubscriptions` call, and that the system should return the next page of data. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> ProjectTopicSubscriptionListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Maximum number of subscription names to return. + /// + /// Sets the *page size* query property to the given value. + pub fn page_size(mut self, new_value: i32) -> ProjectTopicSubscriptionListCall<'a, C, A> { + self._page_size = Some(new_value); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectTopicSubscriptionListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> ProjectTopicSubscriptionListCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProjectTopicSubscriptionListCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Lists matching subscriptions. +/// +/// A builder for the *subscriptions.list* method supported by a *project* resource. +/// It is not used directly, but through a `ProjectMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_pubsub1 as pubsub1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use pubsub1::Pubsub; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Pubsub::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling 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().subscriptions_list("project") +/// .page_token("diam") +/// .page_size(-55) +/// .doit(); +/// # } +/// ``` +pub struct ProjectSubscriptionListCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Pubsub, + _project: String, + _page_token: Option, + _page_size: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ProjectSubscriptionListCall<'a, C, A> {} + +impl<'a, C, A> ProjectSubscriptionListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ListSubscriptionsResponse)> { + use url::percent_encoding::{percent_encode, FORM_URLENCODED_ENCODE_SET}; + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "pubsub.projects.subscriptions.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._page_size { + params.push(("pageSize", value.to_string())); + } + for &field in ["alt", "project", "pageToken", "pageSize"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://pubsub.googleapis.com/v1/{+project}/subscriptions".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{+project}", "project")].iter() { + let mut replace_with = String::new(); + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = value.to_string(); + break; + } + } + if find_this.as_bytes()[1] == '+' as u8 { + replace_with = percent_encode(replace_with.as_bytes(), FORM_URLENCODED_ENCODE_SET); + } + url = url.replace(find_this, &replace_with); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["project"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The name of the cloud project that subscriptions belong to. + /// + /// 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) -> ProjectSubscriptionListCall<'a, C, A> { + self._project = new_value.to_string(); + self + } + /// The value returned by the last `ListSubscriptionsResponse`; indicates that this is a continuation of a prior `ListSubscriptions` call, and that the system should return the next page of data. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> ProjectSubscriptionListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Maximum number of subscriptions to return. + /// + /// Sets the *page size* query property to the given value. + pub fn page_size(mut self, new_value: i32) -> ProjectSubscriptionListCall<'a, C, A> { + self._page_size = Some(new_value); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectSubscriptionListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> ProjectSubscriptionListCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProjectSubscriptionListCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Sets the access control policy on the specified resource. Replaces any existing policy. +/// +/// A builder for the *subscriptions.setIamPolicy* method supported by a *project* resource. +/// It is not used directly, but through a `ProjectMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_pubsub1 as pubsub1; +/// use pubsub1::SetIamPolicyRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use pubsub1::Pubsub; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Pubsub::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req = SetIamPolicyRequest::default(); +/// +/// // You can configure optional parameters by calling 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().subscriptions_set_iam_policy(req, "resource") +/// .doit(); +/// # } +/// ``` +pub struct ProjectSubscriptionSetIamPolicyCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Pubsub, + _request: SetIamPolicyRequest, + _resource: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ProjectSubscriptionSetIamPolicyCall<'a, C, A> {} + +impl<'a, C, A> ProjectSubscriptionSetIamPolicyCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Policy)> { + use url::percent_encoding::{percent_encode, FORM_URLENCODED_ENCODE_SET}; + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "pubsub.projects.subscriptions.setIamPolicy", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("resource", self._resource.to_string())); + for &field in ["alt", "resource"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://pubsub.googleapis.com/v1/{+resource}:setIamPolicy".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{+resource}", "resource")].iter() { + let mut replace_with = String::new(); + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = value.to_string(); + break; + } + } + if find_this.as_bytes()[1] == '+' as u8 { + replace_with = percent_encode(replace_with.as_bytes(), FORM_URLENCODED_ENCODE_SET); + } + url = url.replace(find_this, &replace_with); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["resource"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: SetIamPolicyRequest) -> ProjectSubscriptionSetIamPolicyCall<'a, C, A> { + self._request = new_value; + self + } + /// REQUIRED: The resource for which policy is being specified. `resource` is usually specified as a path, such as, `projects/{project}/zones/{zone}/disks/{disk}`. + /// + /// 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. + pub fn resource(mut self, new_value: &str) -> ProjectSubscriptionSetIamPolicyCall<'a, C, A> { + self._resource = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ProjectSubscriptionSetIamPolicyCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> ProjectSubscriptionSetIamPolicyCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ProjectSubscriptionSetIamPolicyCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + diff --git a/gen/pubsub1_beta2-cli/Cargo.toml b/gen/pubsub1_beta2-cli/Cargo.toml index 06634d8f10..e75e5a6f94 100644 --- a/gen/pubsub1_beta2-cli/Cargo.toml +++ b/gen/pubsub1_beta2-cli/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-pubsub1_beta2-cli" -version = "0.3.2+20150604" +version = "0.3.2+20150526" authors = ["Sebastian Thiel "] description = "A complete library to interact with pubsub (protocol v1beta2)" repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/pubsub1_beta2-cli" diff --git a/gen/pubsub1_beta2-cli/README.md b/gen/pubsub1_beta2-cli/README.md index 89eb51bf5b..e533bd3a2e 100644 --- a/gen/pubsub1_beta2-cli/README.md +++ b/gen/pubsub1_beta2-cli/README.md @@ -24,7 +24,7 @@ Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/ma # Usage -This documentation was generated from the *pubsub* API at revision *20150604*. The CLI is at version *0.3.2*. +This documentation was generated from the *pubsub* API at revision *20150526*. The CLI is at version *0.3.2*. ```bash pubsub1-beta2 [options] diff --git a/gen/pubsub1_beta2-cli/mkdocs.yml b/gen/pubsub1_beta2-cli/mkdocs.yml index 073028fb28..83243cdeec 100644 --- a/gen/pubsub1_beta2-cli/mkdocs.yml +++ b/gen/pubsub1_beta2-cli/mkdocs.yml @@ -1,4 +1,4 @@ -site_name: pubsub v0.3.2+20150604 +site_name: pubsub v0.3.2+20150526 site_url: http://byron.github.io/google-apis-rs/google-pubsub1_beta2-cli site_description: Write integrating applications with bcore diff --git a/gen/pubsub1_beta2-cli/src/main.rs b/gen/pubsub1_beta2-cli/src/main.rs index af4f496222..815235f269 100644 --- a/gen/pubsub1_beta2-cli/src/main.rs +++ b/gen/pubsub1_beta2-cli/src/main.rs @@ -1639,7 +1639,7 @@ fn main() { let arg_data = [ ("projects", "methods: 'subscriptions-acknowledge', 'subscriptions-create', 'subscriptions-delete', 'subscriptions-get', 'subscriptions-get-iam-policy', 'subscriptions-list', 'subscriptions-modify-ack-deadline', 'subscriptions-modify-push-config', 'subscriptions-pull', 'subscriptions-set-iam-policy', 'subscriptions-test-iam-permissions', 'topics-create', 'topics-delete', 'topics-get', 'topics-get-iam-policy', 'topics-list', 'topics-publish', 'topics-set-iam-policy', 'topics-subscriptions-list' and 'topics-test-iam-permissions'", vec![ ("subscriptions-acknowledge", - Some(r##"Acknowledges the messages associated with the ack tokens in the AcknowledgeRequest. The Pub/Sub system can remove the relevant messages from the subscription. Acknowledging a message whose ack deadline has expired may succeed, but such a message may be redelivered later. Acknowledging a message more than once will not result in an error."##), + Some(r##"Acknowledges the messages associated with the `ack_ids` in the `AcknowledgeRequest`. The Pub/Sub system can remove the relevant messages from the subscription. Acknowledging a message whose ack deadline has expired may succeed, but such a message may be redelivered later. Acknowledging a message more than once will not result in an error."##), "Details at http://byron.github.io/google-apis-rs/google_pubsub1_beta2_cli/projects_subscriptions-acknowledge", vec![ (Some(r##"subscription"##), @@ -1667,12 +1667,12 @@ fn main() { Some(false)), ]), ("subscriptions-create", - Some(r##"Creates a subscription to a given topic for a given subscriber. If the subscription already exists, returns ALREADY_EXISTS. If the corresponding topic doesn't exist, returns NOT_FOUND. If the name is not provided in the request, the server will assign a random name for this subscription on the same project as the topic."##), + Some(r##"Creates a subscription to a given topic for a given subscriber. If the subscription already exists, returns `ALREADY_EXISTS`. If the corresponding topic doesn't exist, returns `NOT_FOUND`. If the name is not provided in the request, the server will assign a random name for this subscription on the same project as the topic."##), "Details at http://byron.github.io/google-apis-rs/google_pubsub1_beta2_cli/projects_subscriptions-create", vec![ (Some(r##"name"##), None, - Some(r##"The name of the subscription. It must have the format "projects/{project}/subscriptions/{subscription}" for Google Cloud Pub/Sub API v1 and v1beta2. {subscription} must start with a letter, and contain only letters ([A-Za-z]), numbers ([0-9], dashes (-), underscores (_), periods (.), tildes (~), plus (+) or percent signs (%). It must be between 3 and 255 characters in length, and it must not start with "goog"."##), + Some(r##"The name of the subscription. It must have the format `"projects/{project}/subscriptions/{subscription}"`. `{subscription}` must start with a letter, and contain only letters (`[A-Za-z]`), numbers (`[0-9]`), dashes (`-`), underscores (`_`), periods (`.`), tildes (`~`), plus (`+`) or percent signs (`%`). It must be between 3 and 255 characters in length, and it must not start with `"goog"`."##), Some(true), Some(false)), @@ -1695,7 +1695,7 @@ fn main() { Some(false)), ]), ("subscriptions-delete", - Some(r##"Deletes an existing subscription. All pending messages in the subscription are immediately dropped. Calls to Pull after deletion will return NOT_FOUND. After a subscription is deleted, a new one may be created with the same name, but the new one has no association with the old subscription, or its topic unless the same topic is specified."##), + Some(r##"Deletes an existing subscription. All pending messages in the subscription are immediately dropped. Calls to `Pull` after deletion will return `NOT_FOUND`. After a subscription is deleted, a new one may be created with the same name, but the new one has no association with the old subscription, or its topic unless the same topic is specified."##), "Details at http://byron.github.io/google-apis-rs/google_pubsub1_beta2_cli/projects_subscriptions-delete", vec![ (Some(r##"subscription"##), @@ -1739,12 +1739,12 @@ fn main() { Some(false)), ]), ("subscriptions-get-iam-policy", - Some(r##"Gets the access control policy for a resource. Is empty if the policy or the resource does not exist."##), + Some(r##"Gets the access control policy for a `resource`. Is empty if the policy or the resource does not exist."##), "Details at http://byron.github.io/google-apis-rs/google_pubsub1_beta2_cli/projects_subscriptions-get-iam-policy", vec![ (Some(r##"resource"##), None, - Some(r##"REQUIRED: The resource for which policy is being requested. Resource is usually specified as a path, such as, projects/{project}."##), + Some(r##"REQUIRED: The resource for which policy is being requested. Resource is usually specified as a path, such as, `projects/{project}`."##), Some(true), Some(false)), @@ -1811,7 +1811,7 @@ fn main() { Some(false)), ]), ("subscriptions-modify-push-config", - Some(r##"Modifies the PushConfig for a specified subscription. This may be used to change a push subscription to a pull one (signified by an empty PushConfig) or vice versa, or change the endpoint URL and other attributes of a push subscription. Messages will accumulate for delivery continuously through the call regardless of changes to the PushConfig."##), + Some(r##"Modifies the `PushConfig` for a specified subscription. This may be used to change a push subscription to a pull one (signified by an empty `PushConfig`) or vice versa, or change the endpoint URL and other attributes of a push subscription. Messages will accumulate for delivery continuously through the call regardless of changes to the `PushConfig`."##), "Details at http://byron.github.io/google-apis-rs/google_pubsub1_beta2_cli/projects_subscriptions-modify-push-config", vec![ (Some(r##"subscription"##), @@ -1839,7 +1839,7 @@ fn main() { Some(false)), ]), ("subscriptions-pull", - Some(r##"Pulls messages from the server. Returns an empty list if there are no messages available in the backlog. The server may return UNAVAILABLE if there are too many concurrent pull requests pending for the given subscription."##), + Some(r##"Pulls messages from the server. Returns an empty list if there are no messages available in the backlog. The server may return `UNAVAILABLE` if there are too many concurrent pull requests pending for the given subscription."##), "Details at http://byron.github.io/google-apis-rs/google_pubsub1_beta2_cli/projects_subscriptions-pull", vec![ (Some(r##"subscription"##), @@ -1872,7 +1872,7 @@ fn main() { vec![ (Some(r##"resource"##), None, - Some(r##"REQUIRED: The resource for which policy is being specified. Resource is usually specified as a path, such as, projects/{project}/zones/{zone}/disks/{disk}."##), + Some(r##"REQUIRED: The resource for which policy is being specified. `resource` is usually specified as a path, such as, `projects/{project}/zones/{zone}/disks/{disk}`."##), Some(true), Some(false)), @@ -1900,7 +1900,7 @@ fn main() { vec![ (Some(r##"resource"##), None, - Some(r##"REQUIRED: The resource for which policy detail is being requested. Resource is usually specified as a path, such as, projects/{project}."##), + Some(r##"REQUIRED: The resource for which policy detail is being requested. `resource` is usually specified as a path, such as, `projects/{project}`."##), Some(true), Some(false)), @@ -1928,7 +1928,7 @@ fn main() { vec![ (Some(r##"name"##), None, - Some(r##"The name of the topic. It must have the format "projects/{project}/topics/{topic}" for Google Cloud Pub/Sub API v1 and v1beta2. {topic} must start with a letter, and contain only letters ([A-Za-z]), numbers ([0-9], dashes (-), underscores (_), periods (.), tildes (~), plus (+) or percent signs (%). It must be between 3 and 255 characters in length, and it must not start with "goog"."##), + Some(r##"The name of the topic. It must have the format `"projects/{project}/topics/{topic}"`. `{topic}` must start with a letter, and contain only letters (`[A-Za-z]`), numbers (`[0-9]`), dashes (`-`), underscores (`_`), periods (`.`), tildes (`~`), plus (`+`) or percent signs (`%`). It must be between 3 and 255 characters in length, and it must not start with `"goog"`."##), Some(true), Some(false)), @@ -1951,7 +1951,7 @@ fn main() { Some(false)), ]), ("topics-delete", - Some(r##"Deletes the topic with the given name. Returns NOT_FOUND if the topic does not exist. After a topic is deleted, a new topic may be created with the same name; this is an entirely new topic with none of the old configuration or subscriptions. Existing subscriptions to this topic are not deleted, but their `topic` field is set to `_deleted-topic_`."##), + Some(r##"Deletes the topic with the given name. Returns `NOT_FOUND` if the topic does not exist. After a topic is deleted, a new topic may be created with the same name; this is an entirely new topic with none of the old configuration or subscriptions. Existing subscriptions to this topic are not deleted, but their `topic` field is set to `_deleted-topic_`."##), "Details at http://byron.github.io/google-apis-rs/google_pubsub1_beta2_cli/projects_topics-delete", vec![ (Some(r##"topic"##), @@ -1995,12 +1995,12 @@ fn main() { Some(false)), ]), ("topics-get-iam-policy", - Some(r##"Gets the access control policy for a resource. Is empty if the policy or the resource does not exist."##), + Some(r##"Gets the access control policy for a `resource`. Is empty if the policy or the resource does not exist."##), "Details at http://byron.github.io/google-apis-rs/google_pubsub1_beta2_cli/projects_topics-get-iam-policy", vec![ (Some(r##"resource"##), None, - Some(r##"REQUIRED: The resource for which policy is being requested. Resource is usually specified as a path, such as, projects/{project}."##), + Some(r##"REQUIRED: The resource for which policy is being requested. Resource is usually specified as a path, such as, `projects/{project}`."##), Some(true), Some(false)), @@ -2039,7 +2039,7 @@ fn main() { Some(false)), ]), ("topics-publish", - Some(r##"Adds one or more messages to the topic. Returns NOT_FOUND if the topic does not exist."##), + Some(r##"Adds one or more messages to the topic. Returns `NOT_FOUND` if the topic does not exist. The message payload must not be empty; it must contain either a non-empty data field, or at least one attribute."##), "Details at http://byron.github.io/google-apis-rs/google_pubsub1_beta2_cli/projects_topics-publish", vec![ (Some(r##"topic"##), @@ -2072,7 +2072,7 @@ fn main() { vec![ (Some(r##"resource"##), None, - Some(r##"REQUIRED: The resource for which policy is being specified. Resource is usually specified as a path, such as, projects/{project}/zones/{zone}/disks/{disk}."##), + Some(r##"REQUIRED: The resource for which policy is being specified. `resource` is usually specified as a path, such as, `projects/{project}/zones/{zone}/disks/{disk}`."##), Some(true), Some(false)), @@ -2122,7 +2122,7 @@ fn main() { vec![ (Some(r##"resource"##), None, - Some(r##"REQUIRED: The resource for which policy detail is being requested. Resource is usually specified as a path, such as, projects/{project}."##), + Some(r##"REQUIRED: The resource for which policy detail is being requested. `resource` is usually specified as a path, such as, `projects/{project}`."##), Some(true), Some(false)), @@ -2150,7 +2150,7 @@ fn main() { let mut app = App::new("pubsub1-beta2") .author("Sebastian Thiel ") - .version("0.3.2+20150604") + .version("0.3.2+20150526") .about("Provides reliable, many-to-many, asynchronous messaging between applications.") .after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_pubsub1_beta2_cli") .arg(Arg::with_name("url") diff --git a/gen/pubsub1_beta2/Cargo.toml b/gen/pubsub1_beta2/Cargo.toml index 033b258c1e..5a94fcc329 100644 --- a/gen/pubsub1_beta2/Cargo.toml +++ b/gen/pubsub1_beta2/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-pubsub1_beta2" -version = "0.1.9+20150604" +version = "0.1.9+20150526" authors = ["Sebastian Thiel "] description = "A complete library to interact with pubsub (protocol v1beta2)" repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/pubsub1_beta2" diff --git a/gen/pubsub1_beta2/README.md b/gen/pubsub1_beta2/README.md index 17058e785a..bba49b0a81 100644 --- a/gen/pubsub1_beta2/README.md +++ b/gen/pubsub1_beta2/README.md @@ -5,7 +5,7 @@ DO NOT EDIT ! --> The `google-pubsub1_beta2` library allows access to all features of the *Google pubsub* service. -This documentation was generated from *pubsub* crate version *0.1.9+20150604*, where *20150604* is the exact revision of the *pubsub:v1beta2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +This documentation was generated from *pubsub* crate version *0.1.9+20150526*, where *20150526* is the exact revision of the *pubsub:v1beta2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. Everything else about the *pubsub* *v1_beta2* API can be found at the [official documentation site](https://cloud.google.com/pubsub/docs). diff --git a/gen/pubsub1_beta2/src/lib.rs b/gen/pubsub1_beta2/src/lib.rs index a6cadc8849..6f6ce51b38 100644 --- a/gen/pubsub1_beta2/src/lib.rs +++ b/gen/pubsub1_beta2/src/lib.rs @@ -2,7 +2,7 @@ // This file was generated automatically from 'src/mako/api/lib.rs.mako' // DO NOT EDIT ! -//! This documentation was generated from *pubsub* crate version *0.1.9+20150604*, where *20150604* is the exact revision of the *pubsub:v1beta2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +//! This documentation was generated from *pubsub* crate version *0.1.9+20150526*, where *20150526* is the exact revision of the *pubsub:v1beta2* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. //! //! Everything else about the *pubsub* *v1_beta2* API can be found at the //! [official documentation site](https://cloud.google.com/pubsub/docs). diff --git a/gen/pubsub1_beta2/src/lib.rs.in b/gen/pubsub1_beta2/src/lib.rs.in index d69870e280..cfa5c9d717 100644 --- a/gen/pubsub1_beta2/src/lib.rs.in +++ b/gen/pubsub1_beta2/src/lib.rs.in @@ -171,14 +171,14 @@ impl<'a, C, A> Pubsub /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct TestIamPermissionsRequest { - /// The set of permissions to check for the 'resource'. Permissions with wildcards (such as '*' or 'storage.*') are not allowed. + /// The set of permissions to check for the `resource`. Permissions with wildcards (such as '*' or 'storage.*') are not allowed. pub permissions: Option>, } impl RequestValue for TestIamPermissionsRequest {} -/// Response for the ListTopicSubscriptions method. +/// Response for the `ListTopicSubscriptions` method. /// /// # Activities /// @@ -189,7 +189,7 @@ impl RequestValue for TestIamPermissionsRequest {} /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct ListTopicSubscriptionsResponse { - /// If not empty, indicates that there may be more subscriptions that match the request; this value should be passed in a new ListTopicSubscriptionsRequest to get more subscriptions. + /// If not empty, indicates that there may be more subscriptions that match the request; this value should be passed in a new `ListTopicSubscriptionsRequest` to get more subscriptions. #[serde(rename="nextPageToken")] pub next_page_token: Option, /// The names of the subscriptions that match the request. @@ -211,7 +211,7 @@ impl ResponseResult for ListTopicSubscriptionsResponse {} /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct SetIamPolicyRequest { - /// REQUIRED: The complete policy to be applied to the 'resource'. The size of the policy is limited to a few 10s of KB. An empty policy is in general a valid policy but certain services (like Projects) might reject them. + /// REQUIRED: The complete policy to be applied to the `resource`. The size of the policy is limited to a few 10s of KB. An empty policy is a valid policy but certain Cloud Platform services (such as Projects) might reject them. pub policy: Option, } @@ -245,7 +245,7 @@ impl Part for ReceivedMessage {} /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct AcknowledgeRequest { - /// The acknowledgment ID for the messages being acknowledged that was returned by the Pub/Sub system in the Pull response. Must not be empty. + /// The acknowledgment ID for the messages being acknowledged that was returned by the Pub/Sub system in the `Pull` response. Must not be empty. #[serde(rename="ackIds")] pub ack_ids: Option>, } @@ -253,34 +253,6 @@ pub struct AcknowledgeRequest { impl RequestValue for AcknowledgeRequest {} -/// A rule to be applied in a 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 Rule { - /// The rule matches if the PRINCIPAL/AUTHORITY_SELECTOR is not in this set of entries. The formation for in and not_in entries is the same as members in a Binding above. - #[serde(rename="notIn")] - pub not_in: Option>, - /// Human-readable description of the rule. - pub description: Option, - /// The rule matches if the PRINCIPAL/AUTHORITY_SELECTOR is in this set of entries. - #[serde(rename="in")] - pub in_: Option>, - /// Required - pub action: Option, - /// Additional restrictions that must be met - pub conditions: Option>, - /// The config returned to callers of tech.iam.IAM.CheckPolicy for any entries that match the LOG action. - #[serde(rename="logConfig")] - pub log_config: Option>, - /// A permission is a string of form '..' (e.g., 'storage.buckets.list'). A value of '*' matches all permissions, and a verb part of '*' (e.g., 'storage.buckets.*') matches all verbs. - pub permissions: Option>, -} - -impl Part for Rule {} - - /// Request for the ModifyAckDeadline method. /// /// # Activities @@ -292,7 +264,7 @@ impl Part for Rule {} /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct ModifyAckDeadlineRequest { - /// The new ack deadline with respect to the time this request was sent to the Pub/Sub system. Must be >= 0. For example, if the value is 10, the new ack deadline will expire 10 seconds after the ModifyAckDeadline call was made. Specifying zero may immediately make the message available for another pull request. + /// The new ack deadline with respect to the time this request was sent to the Pub/Sub system. Must be >= 0. For example, if the value is 10, the new ack deadline will expire 10 seconds after the `ModifyAckDeadline` call was made. Specifying zero may immediately make the message available for another pull request. #[serde(rename="ackDeadlineSeconds")] pub ack_deadline_seconds: Option, /// The acknowledgment ID. Either this or ack_ids must be populated, but not both. @@ -324,23 +296,7 @@ pub struct PublishRequest { impl RequestValue for PublishRequest {} -/// Configuration for a push delivery endpoint. -/// -/// This type is not used in any activity, and only used as *part* of another schema. -/// -#[derive(Default, Clone, Debug, Serialize, Deserialize)] -pub struct PushConfig { - /// Endpoint configuration attributes. Every endpoint has a set of API supported attributes that can be used to control different aspects of the message delivery. The currently supported attribute is `x-goog-version`, which you can use to change the format of the push message. This attribute indicates the version of the data expected by the endpoint. This controls the shape of the envelope (i.e. its fields and metadata). The endpoint version is based on the version of the Pub/Sub API. If not present during the CreateSubscription call, it will default to the version of the API used to make such call. If not present during a ModifyPushConfig call, its value will not be changed. GetSubscription calls will always return a valid version, even if the subscription was created without this attribute. The possible values for this attribute are: * `v1beta1`: uses the push format defined in the v1beta1 Pub/Sub API. * `v1` or `v1beta2`: uses the push format defined in the v1 Pub/Sub API. - pub attributes: Option>, - /// A URL locating the endpoint to which messages should be pushed. For example, a Webhook endpoint might use "https://example.com/push". - #[serde(rename="pushEndpoint")] - pub push_endpoint: Option, -} - -impl Part for PushConfig {} - - -/// # Overview The `Policy` defines an access control policy language. It is used to define policies that are attached to resources like files, folders, VMs, etc. # Policy structure A `Policy` consists of a list of bindings. A `Binding` binds a set of members to a role, where the members include user accounts, user groups, user domains, and service accounts. A 'role' is a named set of permissions, defined by IAM. The definition of a role is outside the policy. A permission check first determines the roles that include the specified permission, and then determines if the principal specified is a member of a binding to at least one of these roles. The membership check is recursive when a group is bound to a role. Policy examples: ``` { "bindings": [ { "role": "roles/owner", "members": [ "user:mike@example.com", "group:admins@example.com", "domain:google.com", "serviceAccount:frontend@example.iam.gserviceaccounts.com"] }, { "role": "roles/viewer", "members": ["user:sean@example.com"] } ] } ``` +/// Defines an Identity and Access Management (IAM) policy. It is used to specify access control policies for Cloud Platform resources. A `Policy` consists of a list of `bindings`. A `Binding` binds a list of `members` to a `role`, where the members can be user accounts, Google groups, Google domains, and service accounts. A `role` is a named list of permissions defined by IAM. **Example** { "bindings": [ { "role": "roles/owner", "members": [ "user:mike@example.com", "group:admins@example.com", "domain:google.com", "serviceAccount:my-other-app@appspot.gserviceaccount.com"] }, { "role": "roles/viewer", "members": ["user:sean@example.com"] } ] } For a description of IAM and its features, see the [IAM developer's guide](https://cloud.google.com/iam). /// /// # Activities /// @@ -354,11 +310,9 @@ impl Part for PushConfig {} /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct Policy { - /// no description provided - pub rules: Option>, - /// It is an error to specify multiple bindings for the same role. It is an error to specify a binding with no members. + /// Associates a list of `members` to a `role`. Multiple `bindings` must not be specified for the same `role`. `bindings` with no members will result in an error. pub bindings: Option>, - /// The policy language version. The version of the policy is represented by the etag. The default version is 0. + /// Version of the `Policy`. The default version is 0. pub version: Option, /// Can be used to perform a read-modify-write. pub etag: Option, @@ -367,7 +321,7 @@ pub struct Policy { impl ResponseResult for Policy {} -/// Response for the ListSubscriptions method. +/// Response for the `ListSubscriptions` method. /// /// # Activities /// @@ -378,7 +332,7 @@ impl ResponseResult for Policy {} /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct ListSubscriptionsResponse { - /// If not empty, indicates that there may be more subscriptions that match the request; this value should be passed in a new ListSubscriptionsRequest to get more subscriptions. + /// If not empty, indicates that there may be more subscriptions that match the request; this value should be passed in a new `ListSubscriptionsRequest` to get more subscriptions. #[serde(rename="nextPageToken")] pub next_page_token: Option, /// The subscriptions that match the request. @@ -388,7 +342,7 @@ pub struct ListSubscriptionsResponse { impl ResponseResult for ListSubscriptionsResponse {} -/// Response for the ListTopics method. +/// Response for the `ListTopics` method. /// /// # Activities /// @@ -399,7 +353,7 @@ impl ResponseResult for ListSubscriptionsResponse {} /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct ListTopicsResponse { - /// If not empty, indicates that there may be more topics that match the request; this value should be passed in a new ListTopicsRequest. + /// If not empty, indicates that there may be more topics that match the request; this value should be passed in a new `ListTopicsRequest`. #[serde(rename="nextPageToken")] pub next_page_token: Option, /// The resulting topics. @@ -420,7 +374,7 @@ impl ResponseResult for ListTopicsResponse {} /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct ModifyPushConfigRequest { - /// The push configuration for future deliveries. An empty pushConfig indicates that the Pub/Sub system should stop pushing messages from the given subscription and allow messages to be pulled and acknowledged - effectively pausing the subscription if Pull is not called. + /// The push configuration for future deliveries. An empty `pushConfig` indicates that the Pub/Sub system should stop pushing messages from the given subscription and allow messages to be pulled and acknowledged - effectively pausing the subscription if `Pull` is not called. #[serde(rename="pushConfig")] pub push_config: Option, } @@ -447,31 +401,6 @@ pub struct Empty; impl ResponseResult for Empty {} -/// Write a Cloud Audit log -/// -/// This type is not used in any activity, and only used as *part* of another schema. -/// -#[derive(Default, Clone, Debug, Serialize, Deserialize)] -pub struct CloudAuditOptions; - -impl Part for CloudAuditOptions {} - - -/// Options for counters -/// -/// This type is not used in any activity, and only used as *part* of another schema. -/// -#[derive(Default, Clone, Debug, Serialize, Deserialize)] -pub struct CounterOptions { - /// The field value to attribute. - pub field: Option, - /// The metric to update. - pub metric: Option, -} - -impl Part for CounterOptions {} - - /// Response message for `TestIamPermissions` method. /// /// # Activities @@ -491,7 +420,7 @@ pub struct TestIamPermissionsResponse { impl ResponseResult for TestIamPermissionsResponse {} -/// Request for the Pull method. +/// Request for the `Pull` method. /// /// # Activities /// @@ -502,7 +431,7 @@ impl ResponseResult for TestIamPermissionsResponse {} /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct PullRequest { - /// If this is specified as true the system will respond immediately even if it is not able to return a message in the Pull response. Otherwise the system is allowed to wait until at least one message is available rather than returning no messages. The client may cancel the request if it does not wish to wait any longer for the response. + /// If this is specified as true the system will respond immediately even if it is not able to return a message in the `Pull` response. Otherwise the system is allowed to wait until at least one message is available rather than returning no messages. The client may cancel the request if it does not wish to wait any longer for the response. #[serde(rename="returnImmediately")] pub return_immediately: Option, /// The maximum number of messages returned for this request. The Pub/Sub system may return fewer than the number specified. @@ -513,31 +442,21 @@ pub struct PullRequest { impl RequestValue for PullRequest {} -/// Associates members with roles. See below for allowed formats of members. +/// Associates `members` with a `role`. /// /// This type is not used in any activity, and only used as *part* of another schema. /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct Binding { - /// The name of the role to which the members should be bound. Examples: "roles/viewer", "roles/editor", "roles/owner". Required + /// Role that is assigned to `members`. For example, `roles/viewer`, `roles/editor`, or `roles/owner`. Required pub role: Option, - /// Format of member entries: 1. allUsers Matches any requesting principal (users, service accounts or anonymous). 2. allAuthenticatedUsers Matches any requesting authenticated principal (users or service accounts). 3. user:{emailid} A google user account using an email address. For example alice@gmail.com, joe@example.com 4. serviceAccount:{emailid} An service account email. 5. group:{emailid} A google group with an email address. For example auth-ti-cloud@google.com 6. domain:{domain} A Google Apps domain name. For example google.com, example.com + /// Specifies the identities requesting access for a Cloud Platform resource. `members` can have the following formats: * `allUsers`: A special identifier that represents anyone who is on the internet; with or without a Google account. * `allAuthenticatedUsers`: A special identifier that represents anyone who is authenticated with a Google account or a service account. * `user:{emailid}`: An email address that represents a specific Google account. For example, `alice@gmail.com` or `joe@example.com`. * `serviceAccount:{emailid}`: An email address that represents a service account. For example, `my-other-app@appspot.gserviceaccount.com`. * `group:{emailid}`: An email address that represents a Google group. For example, `admins@example.com`. * `domain:{domain}`: A Google Apps domain name that represents all the users of that domain. For example, `google.com` or `example.com`. pub members: Option>, } impl Part for Binding {} -/// Write a Data Access (Gin) log -/// -/// This type is not used in any activity, and only used as *part* of another schema. -/// -#[derive(Default, Clone, Debug, Serialize, Deserialize)] -pub struct DataAccessOptions; - -impl Part for DataAccessOptions {} - - /// A topic resource. /// /// # Activities @@ -550,7 +469,7 @@ impl Part for DataAccessOptions {} /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct Topic { - /// The name of the topic. It must have the format "projects/{project}/topics/{topic}" for Google Cloud Pub/Sub API v1 and v1beta2. {topic} must start with a letter, and contain only letters ([A-Za-z]), numbers ([0-9], dashes (-), underscores (_), periods (.), tildes (~), plus (+) or percent signs (%). It must be between 3 and 255 characters in length, and it must not start with "goog". + /// The name of the topic. It must have the format `"projects/{project}/topics/{topic}"`. `{topic}` must start with a letter, and contain only letters (`[A-Za-z]`), numbers (`[0-9]`), dashes (`-`), underscores (`_`), periods (`.`), tildes (`~`), plus (`+`) or percent signs (`%`). It must be between 3 and 255 characters in length, and it must not start with `"goog"`. pub name: Option, } @@ -558,7 +477,7 @@ impl RequestValue for Topic {} impl ResponseResult for Topic {} -/// Response for the Publish method. +/// Response for the `Publish` method. /// /// # Activities /// @@ -577,7 +496,7 @@ pub struct PublishResponse { impl ResponseResult for PublishResponse {} -/// Response for the Pull method. +/// Response for the `Pull` method. /// /// # Activities /// @@ -588,7 +507,7 @@ impl ResponseResult for PublishResponse {} /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct PullResponse { - /// Received Pub/Sub messages. The Pub/Sub system will return zero messages if there are no more available in the backlog. The Pub/Sub system may return fewer than the maxMessages requested even if there are more messages available in the backlog. + /// Received Pub/Sub messages. The Pub/Sub system will return zero messages if there are no more available in the backlog. The Pub/Sub system may return fewer than the `maxMessages` requested even if there are more messages available in the backlog. #[serde(rename="receivedMessages")] pub received_messages: Option>, } @@ -596,7 +515,7 @@ pub struct PullResponse { impl ResponseResult for PullResponse {} -/// A message data and its attributes. +/// A message data and its attributes. The message payload must not be empty; it must contain either a non-empty data field, or at least one attribute. /// /// This type is not used in any activity, and only used as *part* of another schema. /// @@ -606,7 +525,7 @@ pub struct PubsubMessage { pub attributes: Option>, /// The message payload. For JSON requests, the value of this field must be base64-encoded. pub data: Option, - /// ID of this message assigned by the server at publication time. Guaranteed to be unique within the topic. This value may be read by a subscriber that receives a PubsubMessage via a Pull call or a push delivery. It must not be populated by a publisher in a Publish call. + /// ID of this message assigned by the server at publication time. Guaranteed to be unique within the topic. This value may be read by a subscriber that receives a `PubsubMessage` via a `Pull` call or a push delivery. It must not be populated by a publisher in a `Publish` call. #[serde(rename="messageId")] pub message_id: Option, } @@ -614,46 +533,20 @@ pub struct PubsubMessage { impl Part for PubsubMessage {} -/// Specifies what kind of log the caller must write Increment a streamz counter with the specified metric and field names. Metric names should start with a '/', generally be lowercase-only, and end in "_count". Field names should not contain an initial slash. The actual exported metric names will have "/iam/policy" prepended. Field names correspond to IAM request parameters and field values are their respective values. At present only "iam_principal", corresponding to IAMContext.principal, is supported. Examples: counter { metric: "/debug_access_count" field: "iam_principal" } ==> increment counter /iam/policy/backend_debug_access_count {iam_principal=[value of IAMContext.principal]} At this time we do not support: * multiple field names (though this may be supported in the future) * decrementing the counter * incrementing it by anything other than 1 +/// Configuration for a push delivery endpoint. /// /// This type is not used in any activity, and only used as *part* of another schema. /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] -pub struct LogConfig { - /// Counter options. - pub counter: Option, - /// Data access options. - #[serde(rename="dataAccess")] - pub data_access: Option, - /// Cloud audit options. - #[serde(rename="cloudAudit")] - pub cloud_audit: Option, +pub struct PushConfig { + /// Endpoint configuration attributes. Every endpoint has a set of API supported attributes that can be used to control different aspects of the message delivery. The currently supported attribute is `x-goog-version`, which you can use to change the format of the push message. This attribute indicates the version of the data expected by the endpoint. This controls the shape of the envelope (i.e. its fields and metadata). The endpoint version is based on the version of the Pub/Sub API. If not present during the `CreateSubscription` call, it will default to the version of the API used to make such call. If not present during a `ModifyPushConfig` call, its value will not be changed. `GetSubscription` calls will always return a valid version, even if the subscription was created without this attribute. The possible values for this attribute are: * `v1beta1`: uses the push format defined in the v1beta1 Pub/Sub API. * `v1` or `v1beta2`: uses the push format defined in the v1 Pub/Sub API. + pub attributes: Option>, + /// A URL locating the endpoint to which messages should be pushed. For example, a Webhook endpoint might use "https://example.com/push". + #[serde(rename="pushEndpoint")] + pub push_endpoint: Option, } -impl Part for LogConfig {} - - -/// A condition to be met. -/// -/// This type is not used in any activity, and only used as *part* of another schema. -/// -#[derive(Default, Clone, Debug, Serialize, Deserialize)] -pub struct Condition { - /// Trusted attributes supplied by the IAM system. - pub iam: Option, - /// Trusted attributes supplied by any service that owns resources and uses the IAM system for access control. - pub sys: Option, - /// The objects of the condition. This is mutually exclusive with 'value'. - pub values: Option>, - /// Trusted attributes discharged by the service. - pub svc: Option, - /// The object of the condition. Exactly one of these must be set. - pub value: Option, - /// An operator to apply the subject with. - pub op: Option, -} - -impl Part for Condition {} +impl Part for PushConfig {} /// A subscription resource. @@ -670,13 +563,13 @@ impl Part for Condition {} pub struct Subscription { /// The name of the topic from which this subscription is receiving messages. The value of this field will be `_deleted-topic_` if the topic has been deleted. pub topic: Option, - /// This value is the maximum time after a subscriber receives a message before the subscriber should acknowledge the message. After message delivery but before the ack deadline expires and before the message is acknowledged, it is an outstanding message and will not be delivered again during that time (on a best-effort basis). For pull delivery this value is used as the initial value for the ack deadline. It may be overridden for each message using its corresponding ack_id by calling ModifyAckDeadline. For push delivery, this value is also used to set the request timeout for the call to the push endpoint. If the subscriber never acknowledges the message, the Pub/Sub system will eventually redeliver the message. If this parameter is not set, the default value of 60 seconds is used. + /// This value is the maximum time after a subscriber receives a message before the subscriber should acknowledge the message. After message delivery but before the ack deadline expires and before the message is acknowledged, it is an outstanding message and will not be delivered again during that time (on a best-effort basis). For pull delivery this value is used as the initial value for the ack deadline. To override this value for a given message, call `ModifyAckDeadline` with the corresponding `ack_id`. For push delivery, this value is also used to set the request timeout for the call to the push endpoint. If the subscriber never acknowledges the message, the Pub/Sub system will eventually redeliver the message. If this parameter is not set, the default value of 10 seconds is used. #[serde(rename="ackDeadlineSeconds")] pub ack_deadline_seconds: Option, - /// If push delivery is used with this subscription, this field is used to configure it. An empty pushConfig signifies that the subscriber will pull and ack messages using API methods. + /// If push delivery is used with this subscription, this field is used to configure it. An empty `pushConfig` signifies that the subscriber will pull and ack messages using API methods. #[serde(rename="pushConfig")] pub push_config: Option, - /// The name of the subscription. It must have the format "projects/{project}/subscriptions/{subscription}" for Google Cloud Pub/Sub API v1 and v1beta2. {subscription} must start with a letter, and contain only letters ([A-Za-z]), numbers ([0-9], dashes (-), underscores (_), periods (.), tildes (~), plus (+) or percent signs (%). It must be between 3 and 255 characters in length, and it must not start with "goog". + /// The name of the subscription. It must have the format `"projects/{project}/subscriptions/{subscription}"`. `{subscription}` must start with a letter, and contain only letters (`[A-Za-z]`), numbers (`[0-9]`), dashes (`-`), underscores (`_`), periods (`.`), tildes (`~`), plus (`+`) or percent signs (`%`). It must be between 3 and 255 characters in length, and it must not start with `"goog"`. pub name: Option, } @@ -748,7 +641,7 @@ impl<'a, C, A> ProjectMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Pulls messages from the server. Returns an empty list if there are no messages available in the backlog. The server may return UNAVAILABLE if there are too many concurrent pull requests pending for the given subscription. + /// Pulls messages from the server. Returns an empty list if there are no messages available in the backlog. The server may return `UNAVAILABLE` if there are too many concurrent pull requests pending for the given subscription. /// /// # Arguments /// @@ -772,7 +665,7 @@ impl<'a, C, A> ProjectMethods<'a, C, A> { /// # Arguments /// /// * `request` - No description provided. - /// * `name` - The name of the topic. It must have the format "projects/{project}/topics/{topic}" for Google Cloud Pub/Sub API v1 and v1beta2. {topic} must start with a letter, and contain only letters ([A-Za-z]), numbers ([0-9], dashes (-), underscores (_), periods (.), tildes (~), plus (+) or percent signs (%). It must be between 3 and 255 characters in length, and it must not start with "goog". + /// * `name` - The name of the topic. It must have the format `"projects/{project}/topics/{topic}"`. `{topic}` must start with a letter, and contain only letters (`[A-Za-z]`), numbers (`[0-9]`), dashes (`-`), underscores (`_`), periods (`.`), tildes (`~`), plus (`+`) or percent signs (`%`). It must be between 3 and 255 characters in length, and it must not start with `"goog"`. pub fn topics_create(&self, request: Topic, name: &str) -> ProjectTopicCreateCall<'a, C, A> { ProjectTopicCreateCall { hub: self.hub, @@ -791,7 +684,7 @@ impl<'a, C, A> ProjectMethods<'a, C, A> { /// # Arguments /// /// * `request` - No description provided. - /// * `resource` - REQUIRED: The resource for which policy detail is being requested. Resource is usually specified as a path, such as, projects/{project}. + /// * `resource` - REQUIRED: The resource for which policy detail is being requested. `resource` is usually specified as a path, such as, `projects/{project}`. pub fn topics_test_iam_permissions(&self, request: TestIamPermissionsRequest, resource: &str) -> ProjectTopicTestIamPermissionCall<'a, C, A> { ProjectTopicTestIamPermissionCall { hub: self.hub, @@ -805,7 +698,7 @@ impl<'a, C, A> ProjectMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Modifies the PushConfig for a specified subscription. This may be used to change a push subscription to a pull one (signified by an empty PushConfig) or vice versa, or change the endpoint URL and other attributes of a push subscription. Messages will accumulate for delivery continuously through the call regardless of changes to the PushConfig. + /// Modifies the `PushConfig` for a specified subscription. This may be used to change a push subscription to a pull one (signified by an empty `PushConfig`) or vice versa, or change the endpoint URL and other attributes of a push subscription. Messages will accumulate for delivery continuously through the call regardless of changes to the `PushConfig`. /// /// # Arguments /// @@ -824,7 +717,7 @@ impl<'a, C, A> ProjectMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Adds one or more messages to the topic. Returns NOT_FOUND if the topic does not exist. + /// Adds one or more messages to the topic. Returns `NOT_FOUND` if the topic does not exist. The message payload must not be empty; it must contain either a non-empty data field, or at least one attribute. /// /// # Arguments /// @@ -860,11 +753,11 @@ impl<'a, C, A> ProjectMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Gets the access control policy for a resource. Is empty if the policy or the resource does not exist. + /// Gets the access control policy for a `resource`. Is empty if the policy or the resource does not exist. /// /// # Arguments /// - /// * `resource` - REQUIRED: The resource for which policy is being requested. Resource is usually specified as a path, such as, projects/{project}. + /// * `resource` - REQUIRED: The resource for which policy is being requested. Resource is usually specified as a path, such as, `projects/{project}`. pub fn topics_get_iam_policy(&self, resource: &str) -> ProjectTopicGetIamPolicyCall<'a, C, A> { ProjectTopicGetIamPolicyCall { hub: self.hub, @@ -896,7 +789,7 @@ impl<'a, C, A> ProjectMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Deletes an existing subscription. All pending messages in the subscription are immediately dropped. Calls to Pull after deletion will return NOT_FOUND. After a subscription is deleted, a new one may be created with the same name, but the new one has no association with the old subscription, or its topic unless the same topic is specified. + /// Deletes an existing subscription. All pending messages in the subscription are immediately dropped. Calls to `Pull` after deletion will return `NOT_FOUND`. After a subscription is deleted, a new one may be created with the same name, but the new one has no association with the old subscription, or its topic unless the same topic is specified. /// /// # Arguments /// @@ -918,7 +811,7 @@ impl<'a, C, A> ProjectMethods<'a, C, A> { /// # Arguments /// /// * `request` - No description provided. - /// * `resource` - REQUIRED: The resource for which policy is being specified. Resource is usually specified as a path, such as, projects/{project}/zones/{zone}/disks/{disk}. + /// * `resource` - REQUIRED: The resource for which policy is being specified. `resource` is usually specified as a path, such as, `projects/{project}/zones/{zone}/disks/{disk}`. pub fn topics_set_iam_policy(&self, request: SetIamPolicyRequest, resource: &str) -> ProjectTopicSetIamPolicyCall<'a, C, A> { ProjectTopicSetIamPolicyCall { hub: self.hub, @@ -932,12 +825,12 @@ impl<'a, C, A> ProjectMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Creates a subscription to a given topic for a given subscriber. If the subscription already exists, returns ALREADY_EXISTS. If the corresponding topic doesn't exist, returns NOT_FOUND. If the name is not provided in the request, the server will assign a random name for this subscription on the same project as the topic. + /// Creates a subscription to a given topic for a given subscriber. If the subscription already exists, returns `ALREADY_EXISTS`. If the corresponding topic doesn't exist, returns `NOT_FOUND`. If the name is not provided in the request, the server will assign a random name for this subscription on the same project as the topic. /// /// # Arguments /// /// * `request` - No description provided. - /// * `name` - The name of the subscription. It must have the format "projects/{project}/subscriptions/{subscription}" for Google Cloud Pub/Sub API v1 and v1beta2. {subscription} must start with a letter, and contain only letters ([A-Za-z]), numbers ([0-9], dashes (-), underscores (_), periods (.), tildes (~), plus (+) or percent signs (%). It must be between 3 and 255 characters in length, and it must not start with "goog". + /// * `name` - The name of the subscription. It must have the format `"projects/{project}/subscriptions/{subscription}"`. `{subscription}` must start with a letter, and contain only letters (`[A-Za-z]`), numbers (`[0-9]`), dashes (`-`), underscores (`_`), periods (`.`), tildes (`~`), plus (`+`) or percent signs (`%`). It must be between 3 and 255 characters in length, and it must not start with `"goog"`. pub fn subscriptions_create(&self, request: Subscription, name: &str) -> ProjectSubscriptionCreateCall<'a, C, A> { ProjectSubscriptionCreateCall { hub: self.hub, @@ -951,7 +844,7 @@ impl<'a, C, A> ProjectMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Acknowledges the messages associated with the ack tokens in the AcknowledgeRequest. The Pub/Sub system can remove the relevant messages from the subscription. Acknowledging a message whose ack deadline has expired may succeed, but such a message may be redelivered later. Acknowledging a message more than once will not result in an error. + /// Acknowledges the messages associated with the `ack_ids` in the `AcknowledgeRequest`. The Pub/Sub system can remove the relevant messages from the subscription. Acknowledging a message whose ack deadline has expired may succeed, but such a message may be redelivered later. Acknowledging a message more than once will not result in an error. /// /// # Arguments /// @@ -970,11 +863,11 @@ impl<'a, C, A> ProjectMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Gets the access control policy for a resource. Is empty if the policy or the resource does not exist. + /// Gets the access control policy for a `resource`. Is empty if the policy or the resource does not exist. /// /// # Arguments /// - /// * `resource` - REQUIRED: The resource for which policy is being requested. Resource is usually specified as a path, such as, projects/{project}. + /// * `resource` - REQUIRED: The resource for which policy is being requested. Resource is usually specified as a path, such as, `projects/{project}`. pub fn subscriptions_get_iam_policy(&self, resource: &str) -> ProjectSubscriptionGetIamPolicyCall<'a, C, A> { ProjectSubscriptionGetIamPolicyCall { hub: self.hub, @@ -992,7 +885,7 @@ impl<'a, C, A> ProjectMethods<'a, C, A> { /// # Arguments /// /// * `request` - No description provided. - /// * `resource` - REQUIRED: The resource for which policy detail is being requested. Resource is usually specified as a path, such as, projects/{project}. + /// * `resource` - REQUIRED: The resource for which policy detail is being requested. `resource` is usually specified as a path, such as, `projects/{project}`. pub fn subscriptions_test_iam_permissions(&self, request: TestIamPermissionsRequest, resource: &str) -> ProjectSubscriptionTestIamPermissionCall<'a, C, A> { ProjectSubscriptionTestIamPermissionCall { hub: self.hub, @@ -1006,7 +899,7 @@ impl<'a, C, A> ProjectMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Deletes the topic with the given name. Returns NOT_FOUND if the topic does not exist. After a topic is deleted, a new topic may be created with the same name; this is an entirely new topic with none of the old configuration or subscriptions. Existing subscriptions to this topic are not deleted, but their `topic` field is set to `_deleted-topic_`. + /// Deletes the topic with the given name. Returns `NOT_FOUND` if the topic does not exist. After a topic is deleted, a new topic may be created with the same name; this is an entirely new topic with none of the old configuration or subscriptions. Existing subscriptions to this topic are not deleted, but their `topic` field is set to `_deleted-topic_`. /// /// # Arguments /// @@ -1083,7 +976,7 @@ impl<'a, C, A> ProjectMethods<'a, C, A> { /// # Arguments /// /// * `request` - No description provided. - /// * `resource` - REQUIRED: The resource for which policy is being specified. Resource is usually specified as a path, such as, projects/{project}/zones/{zone}/disks/{disk}. + /// * `resource` - REQUIRED: The resource for which policy is being specified. `resource` is usually specified as a path, such as, `projects/{project}/zones/{zone}/disks/{disk}`. pub fn subscriptions_set_iam_policy(&self, request: SetIamPolicyRequest, resource: &str) -> ProjectSubscriptionSetIamPolicyCall<'a, C, A> { ProjectSubscriptionSetIamPolicyCall { hub: self.hub, @@ -1302,7 +1195,7 @@ impl<'a, C, A> ProjectTopicListCall<'a, C, A> where C: BorrowMut, self._project = new_value.to_string(); self } - /// The value returned by the last ListTopicsResponse; indicates that this is a continuation of a prior ListTopics call, and that the system should return the next page of data. + /// The value returned by the last `ListTopicsResponse`; indicates that this is a continuation of a prior `ListTopics` call, and that the system should return the next page of data. /// /// Sets the *page token* query property to the given value. pub fn page_token(mut self, new_value: &str) -> ProjectTopicListCall<'a, C, A> { @@ -1374,7 +1267,7 @@ impl<'a, C, A> ProjectTopicListCall<'a, C, A> where C: BorrowMut, } -/// Pulls messages from the server. Returns an empty list if there are no messages available in the backlog. The server may return UNAVAILABLE if there are too many concurrent pull requests pending for the given subscription. +/// Pulls messages from the server. Returns an empty list if there are no messages available in the backlog. The server may return `UNAVAILABLE` if there are too many concurrent pull requests pending for the given subscription. /// /// A builder for the *subscriptions.pull* method supported by a *project* resource. /// It is not used directly, but through a `ProjectMethods` instance. @@ -1860,7 +1753,7 @@ impl<'a, C, A> ProjectTopicCreateCall<'a, C, A> where C: BorrowMut ProjectTopicTestIamPermissionCall<'a, C, A> where C: BorrowMut ProjectTopicTestIamPermissionCall<'a, C, A> where C: BorrowMut ProjectSubscriptionModifyPushConfigCall<'a, C, A> where C: Borrow } -/// Adds one or more messages to the topic. Returns NOT_FOUND if the topic does not exist. +/// Adds one or more messages to the topic. Returns `NOT_FOUND` if the topic does not exist. The message payload must not be empty; it must contain either a non-empty data field, or at least one attribute. /// /// A builder for the *topics.publish* method supported by a *project* resource. /// It is not used directly, but through a `ProjectMethods` instance. @@ -3005,7 +2898,7 @@ impl<'a, C, A> ProjectTopicGetCall<'a, C, A> where C: BorrowMut, } -/// Gets the access control policy for a resource. Is empty if the policy or the resource does not exist. +/// Gets the access control policy for a `resource`. Is empty if the policy or the resource does not exist. /// /// A builder for the *topics.getIamPolicy* method supported by a *project* resource. /// It is not used directly, but through a `ProjectMethods` instance. @@ -3183,7 +3076,7 @@ impl<'a, C, A> ProjectTopicGetIamPolicyCall<'a, C, A> where C: BorrowMut ProjectSubscriptionModifyAckDeadlineCall<'a, C, A> where C: Borro } -/// Deletes an existing subscription. All pending messages in the subscription are immediately dropped. Calls to Pull after deletion will return NOT_FOUND. After a subscription is deleted, a new one may be created with the same name, but the new one has no association with the old subscription, or its topic unless the same topic is specified. +/// Deletes an existing subscription. All pending messages in the subscription are immediately dropped. Calls to `Pull` after deletion will return `NOT_FOUND`. After a subscription is deleted, a new one may be created with the same name, but the new one has no association with the old subscription, or its topic unless the same topic is specified. /// /// A builder for the *subscriptions.delete* method supported by a *project* resource. /// It is not used directly, but through a `ProjectMethods` instance. @@ -3983,7 +3876,7 @@ impl<'a, C, A> ProjectTopicSetIamPolicyCall<'a, C, A> where C: BorrowMut ProjectTopicSetIamPolicyCall<'a, C, A> where C: BorrowMut ProjectSubscriptionCreateCall<'a, C, A> where C: BorrowMut ProjectSubscriptionCreateCall<'a, C, A> where C: BorrowMut ProjectSubscriptionAcknowledgeCall<'a, C, A> where C: BorrowMut ProjectSubscriptionGetIamPolicyCall<'a, C, A> where C: BorrowMut< } - /// REQUIRED: The resource for which policy is being requested. Resource is usually specified as a path, such as, projects/{project}. + /// REQUIRED: The resource for which policy is being requested. Resource is usually specified as a path, such as, `projects/{project}`. /// /// Sets the *resource* path property to the given value. /// @@ -5060,7 +4953,7 @@ impl<'a, C, A> ProjectSubscriptionTestIamPermissionCall<'a, C, A> where C: Borro self._request = new_value; self } - /// REQUIRED: The resource for which policy detail is being requested. Resource is usually specified as a path, such as, projects/{project}. + /// REQUIRED: The resource for which policy detail is being requested. `resource` is usually specified as a path, such as, `projects/{project}`. /// /// Sets the *resource* path property to the given value. /// @@ -5128,7 +5021,7 @@ impl<'a, C, A> ProjectSubscriptionTestIamPermissionCall<'a, C, A> where C: Borro } -/// Deletes the topic with the given name. Returns NOT_FOUND if the topic does not exist. After a topic is deleted, a new topic may be created with the same name; this is an entirely new topic with none of the old configuration or subscriptions. Existing subscriptions to this topic are not deleted, but their `topic` field is set to `_deleted-topic_`. +/// Deletes the topic with the given name. Returns `NOT_FOUND` if the topic does not exist. After a topic is deleted, a new topic may be created with the same name; this is an entirely new topic with none of the old configuration or subscriptions. Existing subscriptions to this topic are not deleted, but their `topic` field is set to `_deleted-topic_`. /// /// A builder for the *topics.delete* method supported by a *project* resource. /// It is not used directly, but through a `ProjectMethods` instance. @@ -5818,7 +5711,7 @@ impl<'a, C, A> ProjectTopicSubscriptionListCall<'a, C, A> where C: BorrowMut ProjectTopicSubscriptionListCall<'a, C, A> { @@ -6088,7 +5981,7 @@ impl<'a, C, A> ProjectSubscriptionListCall<'a, C, A> where C: BorrowMut ProjectSubscriptionListCall<'a, C, A> { @@ -6369,7 +6262,7 @@ impl<'a, C, A> ProjectSubscriptionSetIamPolicyCall<'a, C, A> where C: BorrowMut< self._request = new_value; self } - /// REQUIRED: The resource for which policy is being specified. Resource is usually specified as a path, such as, projects/{project}/zones/{zone}/disks/{disk}. + /// REQUIRED: The resource for which policy is being specified. `resource` is usually specified as a path, such as, `projects/{project}/zones/{zone}/disks/{disk}`. /// /// Sets the *resource* path property to the given value. /// diff --git a/gen/replicapool1_beta2/src/lib.rs.in b/gen/replicapool1_beta2/src/lib.rs.in index a21d4ff4c3..861b62f0db 100644 --- a/gen/replicapool1_beta2/src/lib.rs.in +++ b/gen/replicapool1_beta2/src/lib.rs.in @@ -43,6 +43,9 @@ pub enum Scope { /// View your Google Compute Engine resources ComputeReadonly, + + /// View your data across Google Cloud Platform services + CloudPlatformReadOnly, } impl AsRef for Scope { @@ -51,6 +54,7 @@ impl AsRef for Scope { Scope::Compute => "https://www.googleapis.com/auth/compute", Scope::CloudPlatform => "https://www.googleapis.com/auth/cloud-platform", Scope::ComputeReadonly => "https://www.googleapis.com/auth/compute.readonly", + Scope::CloudPlatformReadOnly => "https://www.googleapis.com/auth/cloud-platform.read-only", } } } diff --git a/gen/replicapoolupdater1_beta1-cli/Cargo.toml b/gen/replicapoolupdater1_beta1-cli/Cargo.toml index e18da1821d..85c1ee1269 100644 --- a/gen/replicapoolupdater1_beta1-cli/Cargo.toml +++ b/gen/replicapoolupdater1_beta1-cli/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-replicapoolupdater1_beta1-cli" -version = "0.3.2+20150326" +version = "0.3.2+20150904" authors = ["Sebastian Thiel "] description = "A complete library to interact with replicapoolupdater (protocol v1beta1)" repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/replicapoolupdater1_beta1-cli" diff --git a/gen/replicapoolupdater1_beta1-cli/README.md b/gen/replicapoolupdater1_beta1-cli/README.md index 8a6c67f402..247d6e7250 100644 --- a/gen/replicapoolupdater1_beta1-cli/README.md +++ b/gen/replicapoolupdater1_beta1-cli/README.md @@ -24,7 +24,7 @@ Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/ma # Usage -This documentation was generated from the *replicapoolupdater* API at revision *20150326*. The CLI is at version *0.3.2*. +This documentation was generated from the *replicapoolupdater* API at revision *20150904*. The CLI is at version *0.3.2*. ```bash replicapoolupdater1-beta1 [options] @@ -39,6 +39,7 @@ replicapoolupdater1-beta1 [options] rollback [-p ]... [-o ] zone-operations get [-p ]... [-o ] + list [-p ]... [-o ] replicapoolupdater1-beta1 --help Configuration: diff --git a/gen/replicapoolupdater1_beta1-cli/mkdocs.yml b/gen/replicapoolupdater1_beta1-cli/mkdocs.yml index 013006c580..bfd898253c 100644 --- a/gen/replicapoolupdater1_beta1-cli/mkdocs.yml +++ b/gen/replicapoolupdater1_beta1-cli/mkdocs.yml @@ -1,4 +1,4 @@ -site_name: replicapoolupdater v0.3.2+20150326 +site_name: replicapoolupdater v0.3.2+20150904 site_url: http://byron.github.io/google-apis-rs/google-replicapoolupdater1_beta1-cli site_description: Write integrating applications with bcore @@ -18,6 +18,7 @@ pages: - ['rolling-updates_resume.md', 'Rolling Updates', 'Resume'] - ['rolling-updates_rollback.md', 'Rolling Updates', 'Rollback'] - ['zone-operations_get.md', 'Zone Operations', 'Get'] +- ['zone-operations_list.md', 'Zone Operations', 'List'] theme: readthedocs diff --git a/gen/replicapoolupdater1_beta1-cli/src/main.rs b/gen/replicapoolupdater1_beta1-cli/src/main.rs index c3c06530fb..68494a4deb 100644 --- a/gen/replicapoolupdater1_beta1-cli/src/main.rs +++ b/gen/replicapoolupdater1_beta1-cli/src/main.rs @@ -190,8 +190,9 @@ impl<'n, 'a> Engine<'n, 'a> { "creation-timestamp" => Some(("creationTimestamp", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "self-link" => Some(("selfLink", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "old-instance-template" => Some(("oldInstanceTemplate", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), _ => { - let suggestion = FieldCursor::did_you_mean(key, &vec!["action-type", "auto-pause-after-instances", "creation-timestamp", "description", "id", "instance-group", "instance-group-manager", "instance-startup-timeout-sec", "instance-template", "kind", "max-num-concurrent-instances", "max-num-failed-instances", "min-instance-update-time-sec", "policy", "progress", "self-link", "status", "status-message", "user"]); + let suggestion = FieldCursor::did_you_mean(key, &vec!["action-type", "auto-pause-after-instances", "creation-timestamp", "description", "id", "instance-group", "instance-group-manager", "instance-startup-timeout-sec", "instance-template", "kind", "max-num-concurrent-instances", "max-num-failed-instances", "min-instance-update-time-sec", "old-instance-template", "policy", "progress", "self-link", "status", "status-message", "user"]); err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); None } @@ -263,9 +264,6 @@ impl<'n, 'a> Engine<'n, 'a> { "max-results" => { call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer")); }, - "instance-group-manager" => { - call = call.instance_group_manager(value.unwrap_or("")); - }, "filter" => { call = call.filter(value.unwrap_or("")); }, @@ -282,7 +280,7 @@ impl<'n, 'a> Engine<'n, 'a> { err.issues.push(CLIError::UnknownParameter(key.to_string(), {let mut v = Vec::new(); v.extend(self.gp.iter().map(|v|*v)); - v.extend(["filter", "page-token", "max-results", "instance-group-manager"].iter().map(|v|*v)); + v.extend(["filter", "page-token", "max-results"].iter().map(|v|*v)); v } )); } } @@ -586,6 +584,68 @@ impl<'n, 'a> Engine<'n, 'a> { } } + fn _zone_operations_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.zone_operations().list(opt.value_of("project").unwrap_or(""), opt.value_of("zone").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "max-results" => { + call = call.max_results(arg_from_str(value.unwrap_or("-0"), err, "max-results", "integer")); + }, + "filter" => { + call = call.filter(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["filter", "page-token", "max-results"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + fn _doit(&self, dry_run: bool) -> Result, Option> { let mut err = InvalidOptionsError::new(); let mut call_result: Result<(), DoitError> = Ok(()); @@ -628,6 +688,9 @@ impl<'n, 'a> Engine<'n, 'a> { ("get", Some(opt)) => { call_result = self._zone_operations_get(opt, dry_run, &mut err); }, + ("list", Some(opt)) => { + call_result = self._zone_operations_list(opt, dry_run, &mut err); + }, _ => { err.issues.push(CLIError::MissingMethodError("zone-operations".to_string())); writeln!(io::stderr(), "{}\n", opt.usage()).ok(); @@ -985,7 +1048,7 @@ fn main() { ]), ]), - ("zone-operations", "methods: 'get'", vec![ + ("zone-operations", "methods: 'get' and 'list'", vec![ ("get", Some(r##"Retrieves the specified zone-specific operation resource."##), "Details at http://byron.github.io/google-apis-rs/google_replicapoolupdater1_beta1_cli/zone-operations_get", @@ -1014,6 +1077,34 @@ fn main() { Some(false), Some(true)), + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Retrieves the list of Operation resources contained within the specified zone."##), + "Details at http://byron.github.io/google-apis-rs/google_replicapoolupdater1_beta1_cli/zone-operations_list", + vec![ + (Some(r##"project"##), + None, + Some(r##"Name of the project scoping this request."##), + Some(true), + Some(false)), + + (Some(r##"zone"##), + None, + Some(r##"Name of the zone scoping this request."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + (Some(r##"out"##), Some(r##"o"##), Some(r##"Specify the file into which to write the program's output"##), @@ -1026,7 +1117,7 @@ fn main() { let mut app = App::new("replicapoolupdater1-beta1") .author("Sebastian Thiel ") - .version("0.3.2+20150326") + .version("0.3.2+20150904") .about("The Google Compute Engine Instance Group Updater API provides services for updating groups of Compute Engine Instances.") .after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_replicapoolupdater1_beta1_cli") .arg(Arg::with_name("url") diff --git a/gen/replicapoolupdater1_beta1/Cargo.toml b/gen/replicapoolupdater1_beta1/Cargo.toml index 28710eeb6a..475a46d064 100644 --- a/gen/replicapoolupdater1_beta1/Cargo.toml +++ b/gen/replicapoolupdater1_beta1/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-replicapoolupdater1_beta1" -version = "0.1.9+20150326" +version = "0.1.9+20150904" authors = ["Sebastian Thiel "] description = "A complete library to interact with replicapoolupdater (protocol v1beta1)" repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/replicapoolupdater1_beta1" diff --git a/gen/replicapoolupdater1_beta1/README.md b/gen/replicapoolupdater1_beta1/README.md index c90e4a5224..80cdfedd06 100644 --- a/gen/replicapoolupdater1_beta1/README.md +++ b/gen/replicapoolupdater1_beta1/README.md @@ -5,7 +5,7 @@ DO NOT EDIT ! --> The `google-replicapoolupdater1_beta1` library allows access to all features of the *Google replicapoolupdater* service. -This documentation was generated from *replicapoolupdater* crate version *0.1.9+20150326*, where *20150326* is the exact revision of the *replicapoolupdater:v1beta1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +This documentation was generated from *replicapoolupdater* crate version *0.1.9+20150904*, where *20150904* is the exact revision of the *replicapoolupdater:v1beta1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. Everything else about the *replicapoolupdater* *v1_beta1* API can be found at the [official documentation site](https://cloud.google.com/compute/docs/instance-groups/manager/#applying_rolling_updates_using_the_updater_service). @@ -16,7 +16,7 @@ Handle the following *Resources* with ease from the central [hub](http://byron.g * [rolling updates](http://byron.github.io/google-apis-rs/google_replicapoolupdater1_beta1/struct.RollingUpdate.html) * [*cancel*](http://byron.github.io/google-apis-rs/google_replicapoolupdater1_beta1/struct.RollingUpdateCancelCall.html), [*get*](http://byron.github.io/google-apis-rs/google_replicapoolupdater1_beta1/struct.RollingUpdateGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google_replicapoolupdater1_beta1/struct.RollingUpdateInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google_replicapoolupdater1_beta1/struct.RollingUpdateListCall.html), [*list instance updates*](http://byron.github.io/google-apis-rs/google_replicapoolupdater1_beta1/struct.RollingUpdateListInstanceUpdateCall.html), [*pause*](http://byron.github.io/google-apis-rs/google_replicapoolupdater1_beta1/struct.RollingUpdatePauseCall.html), [*resume*](http://byron.github.io/google-apis-rs/google_replicapoolupdater1_beta1/struct.RollingUpdateResumeCall.html) and [*rollback*](http://byron.github.io/google-apis-rs/google_replicapoolupdater1_beta1/struct.RollingUpdateRollbackCall.html) * zone operations - * [*get*](http://byron.github.io/google-apis-rs/google_replicapoolupdater1_beta1/struct.ZoneOperationGetCall.html) + * [*get*](http://byron.github.io/google-apis-rs/google_replicapoolupdater1_beta1/struct.ZoneOperationGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google_replicapoolupdater1_beta1/struct.ZoneOperationListCall.html) @@ -101,10 +101,9 @@ let mut hub = Replicapoolupdater::new(hyper::Client::new(), auth); // You can configure optional parameters by calling the respective setters at will, and // execute the final call using `doit()`. // Values shown here are possibly random and not representative ! -let result = hub.rolling_updates().list("project", "zone") - .page_token("Stet") - .max_results(59) - .instance_group_manager("et") +let result = hub.rolling_updates().list_instance_updates("project", "zone", "rollingUpdate") + .page_token("sed") + .max_results(16) .filter("dolores") .doit(); diff --git a/gen/replicapoolupdater1_beta1/src/lib.rs b/gen/replicapoolupdater1_beta1/src/lib.rs index a5bd0058d5..8a409d0bf8 100644 --- a/gen/replicapoolupdater1_beta1/src/lib.rs +++ b/gen/replicapoolupdater1_beta1/src/lib.rs @@ -2,7 +2,7 @@ // This file was generated automatically from 'src/mako/api/lib.rs.mako' // DO NOT EDIT ! -//! This documentation was generated from *replicapoolupdater* crate version *0.1.9+20150326*, where *20150326* is the exact revision of the *replicapoolupdater:v1beta1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +//! This documentation was generated from *replicapoolupdater* crate version *0.1.9+20150904*, where *20150904* is the exact revision of the *replicapoolupdater:v1beta1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. //! //! Everything else about the *replicapoolupdater* *v1_beta1* API can be found at the //! [official documentation site](https://cloud.google.com/compute/docs/instance-groups/manager/#applying_rolling_updates_using_the_updater_service). @@ -14,7 +14,7 @@ //! * [rolling updates](struct.RollingUpdate.html) //! * [*cancel*](struct.RollingUpdateCancelCall.html), [*get*](struct.RollingUpdateGetCall.html), [*insert*](struct.RollingUpdateInsertCall.html), [*list*](struct.RollingUpdateListCall.html), [*list instance updates*](struct.RollingUpdateListInstanceUpdateCall.html), [*pause*](struct.RollingUpdatePauseCall.html), [*resume*](struct.RollingUpdateResumeCall.html) and [*rollback*](struct.RollingUpdateRollbackCall.html) //! * zone operations -//! * [*get*](struct.ZoneOperationGetCall.html) +//! * [*get*](struct.ZoneOperationGetCall.html) and [*list*](struct.ZoneOperationListCall.html) //! //! //! @@ -102,11 +102,10 @@ //! // You can configure optional parameters by calling the respective setters at will, and //! // execute the final call using `doit()`. //! // Values shown here are possibly random and not representative ! -//! let result = hub.rolling_updates().list("project", "zone") -//! .page_token("accusam") -//! .max_results(45) -//! .instance_group_manager("sea") -//! .filter("et") +//! let result = hub.rolling_updates().list_instance_updates("project", "zone", "rollingUpdate") +//! .page_token("et") +//! .max_results(61) +//! .filter("sanctus") //! .doit(); //! //! match result { diff --git a/gen/replicapoolupdater1_beta1/src/lib.rs.in b/gen/replicapoolupdater1_beta1/src/lib.rs.in index 88489715d4..fcafa8c1eb 100644 --- a/gen/replicapoolupdater1_beta1/src/lib.rs.in +++ b/gen/replicapoolupdater1_beta1/src/lib.rs.in @@ -43,6 +43,9 @@ pub enum Scope { /// View replica pools ReplicapoolReadonly, + + /// View your data across Google Cloud Platform services + CloudPlatformReadOnly, } impl AsRef for Scope { @@ -51,6 +54,7 @@ impl AsRef for Scope { Scope::CloudPlatform => "https://www.googleapis.com/auth/cloud-platform", Scope::Replicapool => "https://www.googleapis.com/auth/replicapool", Scope::ReplicapoolReadonly => "https://www.googleapis.com/auth/replicapool.readonly", + Scope::CloudPlatformReadOnly => "https://www.googleapis.com/auth/cloud-platform.read-only", } } } @@ -98,10 +102,9 @@ impl Default for Scope { /// // You can configure optional parameters by calling the respective setters at will, and /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! -/// let result = hub.rolling_updates().list("project", "zone") -/// .page_token("takimata") -/// .max_results(31) -/// .instance_group_manager("amet.") +/// let result = hub.rolling_updates().list_instance_updates("project", "zone", "rollingUpdate") +/// .page_token("justo") +/// .max_results(100) /// .filter("erat") /// .doit(); /// @@ -179,7 +182,7 @@ pub struct InstanceUpdate { /// - "ROLLED_BACK": The instance update is finished, the instance has been reverted to the previous template. /// - "CANCELLED": The instance update is paused and no longer can be resumed, undefined in which template the instance is running. pub status: Option, - /// URL of the instance being updated. + /// Fully-qualified URL of the instance being updated. pub instance: Option, /// Errors that occurred during the instance update. pub error: Option, @@ -214,36 +217,6 @@ pub struct InstanceUpdateList { impl ResponseResult for InstanceUpdateList {} -/// [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 OperationWarningsData { - /// [Output Only] Metadata key for this warning. - pub key: Option, - /// [Output Only] Metadata value for this warning. - pub value: Option, -} - -impl NestedType for OperationWarningsData {} -impl Part for OperationWarningsData {} - - -/// Errors that occurred during the instance update. -/// -/// This type is not used in any activity, and only used as *part* of another schema. -/// -#[derive(Default, Clone, Debug, Serialize, Deserialize)] -pub struct InstanceUpdateError { - /// [Output Only] The array of errors encountered while processing this operation. - pub errors: Option>, -} - -impl NestedType for InstanceUpdateError {} -impl Part for InstanceUpdateError {} - - /// The following represents a resource describing a single update (rollout) of a group of instances to the given template. /// /// # Activities @@ -270,11 +243,6 @@ pub struct RollingUpdate { /// - "ROLLED_BACK": The update is finished, all instances have been reverted to the previous template. /// - "CANCELLED": The update is paused and no longer can be resumed, undefined how many instances are running in which template. pub status: Option, - /// [Output Only] The fully qualified URL for the resource. - #[serde(rename="selfLink")] - pub self_link: Option, - /// [Output Only] 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, /// Fully-qualified URL of an instance group being updated. Exactly one of instanceGroupManager and instanceGroup must be set. @@ -288,17 +256,25 @@ pub struct RollingUpdate { pub action_type: Option, /// [Output Only] User who requested the update, for example: user@example.com. pub user: Option, + /// [Output Only] Creation timestamp in RFC3339 text format. + #[serde(rename="creationTimestamp")] + pub creation_timestamp: Option, + /// [Output Only] Unique identifier for the resource; defined by the server. + pub id: Option, + /// [Output Only] Type of the resource. + pub kind: Option, + /// [Output Only] The fully qualified URL for the resource. + #[serde(rename="selfLink")] + pub self_link: Option, /// [Output Only] Errors that occurred during the rolling update. pub error: Option, /// Parameters of the update process. pub policy: Option, /// [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 update will be complete. This number should be monotonically increasing as the update progresses. pub progress: Option, - /// [Output Only] Creation timestamp in RFC3339 text format. - #[serde(rename="creationTimestamp")] - pub creation_timestamp: Option, - /// [Output Only] Unique identifier for the resource; defined by the server. - pub id: Option, + /// Fully-qualified URL of the instance template encountered while starting the update. + #[serde(rename="oldInstanceTemplate")] + pub old_instance_template: Option, /// [Output Only] An optional textual description of the current status of the update. #[serde(rename="statusMessage")] pub status_message: Option, @@ -312,6 +288,24 @@ impl Resource for RollingUpdate {} impl ResponseResult for RollingUpdate {} +/// [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, Serialize, Deserialize)] +pub struct OperationErrorErrors { + /// [Output Only] An optional, human-readable error message. + pub message: Option, + /// [Output Only] The error type identifier for this error. + pub code: Option, + /// [Output Only] Indicates the field in the request that caused the error. This property is optional. + pub location: Option, +} + +impl NestedType for OperationErrorErrors {} +impl Part for OperationErrorErrors {} + + /// [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. @@ -357,22 +351,80 @@ impl NestedType for RollingUpdatePolicy {} impl Part for RollingUpdatePolicy {} -/// [Output Only] The array of errors encountered while processing this operation. +/// [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 OperationErrorErrors { - /// [Output Only] An optional, human-readable error message. - pub message: Option, - /// [Output Only] The error type identifier for this error. - pub code: Option, - /// [Output Only] Indicates the field in the request that caused the error. This property is optional. - pub location: Option, +pub struct OperationWarningsData { + /// [Output Only] Metadata key for this warning. + pub key: Option, + /// [Output Only] Metadata value for this warning. + pub value: Option, } -impl NestedType for OperationErrorErrors {} -impl Part for OperationErrorErrors {} +impl NestedType for OperationWarningsData {} +impl Part for OperationWarningsData {} + + +/// Errors that occurred during the instance update. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct InstanceUpdateError { + /// [Output Only] The array of errors encountered while processing this operation. + pub errors: Option>, +} + +impl NestedType for InstanceUpdateError {} +impl Part for InstanceUpdateError {} + + +/// 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 OperationWarnings { + /// [Output only] Optional human-readable details for this warning. + pub message: Option, + /// [Output only] The warning type identifier for this warning. + pub code: Option, + /// [Output only] Metadata for this warning in key:value format. + pub data: Option>, +} + +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 zone operations](struct.ZoneOperationListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct OperationList { + /// [Output Only] A token used to continue a truncate. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// [Output Only] The Operation resources. + pub items: Option>, + /// [Output Only] Type of resource. Always replicapoolupdater#operations for Operations resource. + pub kind: Option, + /// [Output Only] Unique identifier for the resource; defined by the server. + pub id: Option, + /// [Output Only] Server-defined URL for this resource. + #[serde(rename="selfLink")] + pub self_link: Option, +} + +impl ResponseResult for OperationList {} /// [Output Only] The array of errors encountered while processing this operation. @@ -407,24 +459,6 @@ impl NestedType for OperationError {} impl Part for OperationError {} -/// 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 OperationWarnings { - /// [Output only] Optional human-readable details for this warning. - pub message: Option, - /// [Output only] The warning type identifier for this warning. - pub code: Option, - /// [Output only] Metadata for this warning in key:value format. - pub data: Option>, -} - -impl NestedType for OperationWarnings {} -impl Part for OperationWarnings {} - - /// An operation resource, used to manage asynchronous API requests. /// /// # Activities @@ -467,7 +501,7 @@ pub struct Operation { pub creation_timestamp: Option, /// [Output Only] Unique identifier for the resource; defined by the server. pub id: Option, - /// [Output Only] Type of the resource. Always kind#operation for Operation resources. + /// [Output Only] Type of the resource. Always replicapoolupdater#operation for Operation resources. pub kind: Option, /// [Output Only] Name of the resource. pub name: Option, @@ -684,7 +718,6 @@ impl<'a, C, A> RollingUpdateMethods<'a, C, A> { _zone: zone.to_string(), _page_token: Default::default(), _max_results: Default::default(), - _instance_group_manager: Default::default(), _filter: Default::default(), _delegate: Default::default(), _scopes: Default::default(), @@ -784,7 +817,7 @@ impl<'a, C, A> RollingUpdateMethods<'a, C, A> { /// ::default(), None); /// let mut hub = Replicapoolupdater::new(hyper::Client::new(), auth); /// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* -/// // like `get(...)` +/// // like `get(...)` and `list(...)` /// // to build up your call. /// let rb = hub.zone_operations(); /// # } @@ -819,6 +852,28 @@ impl<'a, C, A> ZoneOperationMethods<'a, C, A> { _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. + /// + /// # Arguments + /// + /// * `project` - Name of the project scoping this request. + /// * `zone` - Name of the zone scoping this request. + pub fn list(&self, project: &str, zone: &str) -> ZoneOperationListCall<'a, C, 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(), + } + } } @@ -1898,8 +1953,7 @@ impl<'a, C, A> RollingUpdateResumeCall<'a, C, A> where C: BorrowMut _zone: String, _page_token: Option, _max_results: Option, - _instance_group_manager: Option, _filter: Option, _delegate: Option<&'a mut Delegate>, _additional_params: HashMap, @@ -1934,7 +1987,7 @@ impl<'a, C, A> RollingUpdateListCall<'a, C, A> where C: BorrowMut }; dlg.begin(MethodInfo { id: "replicapoolupdater.rollingUpdates.list", http_method: hyper::method::Method::Get }); - let mut params: Vec<(&str, String)> = Vec::with_capacity((8 + self._additional_params.len())); + 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 { @@ -1943,13 +1996,10 @@ impl<'a, C, A> RollingUpdateListCall<'a, C, A> where C: BorrowMut if let Some(value) = self._max_results { params.push(("maxResults", value.to_string())); } - if let Some(value) = self._instance_group_manager { - params.push(("instanceGroupManager", value.to_string())); - } if let Some(value) = self._filter { params.push(("filter", value.to_string())); } - for &field in ["alt", "project", "zone", "pageToken", "maxResults", "instanceGroupManager", "filter"].iter() { + for &field in ["alt", "project", "zone", "pageToken", "maxResults", "filter"].iter() { if self._additional_params.contains_key(field) { dlg.finished(false); return Err(Error::FieldClash(field)); @@ -2099,13 +2149,6 @@ impl<'a, C, A> RollingUpdateListCall<'a, C, A> where C: BorrowMut self._max_results = Some(new_value); self } - /// The name of the instance group manager. Use this parameter to return only updates to instances that are part of a specific instance group. - /// - /// Sets the *instance group manager* query property to the given value. - pub fn instance_group_manager(mut self, new_value: &str) -> RollingUpdateListCall<'a, C, A> { - self._instance_group_manager = Some(new_value.to_string()); - self - } /// Optional. Filter expression for filtering listed resources. /// /// Sets the *filter* query property to the given value. @@ -2471,9 +2514,9 @@ impl<'a, C, A> RollingUpdateInsertCall<'a, C, A> where C: BorrowMut ZoneOperationGetCall<'a, C, A> where C: BorrowMut, } +/// 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` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_replicapoolupdater1_beta1 as replicapoolupdater1_beta1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use replicapoolupdater1_beta1::Replicapoolupdater; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Replicapoolupdater::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling 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("aliquyam") +/// .max_results(28) +/// .filter("Lorem") +/// .doit(); +/// # } +/// ``` +pub struct ZoneOperationListCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Replicapoolupdater, + _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, A> CallBuilder for ZoneOperationListCall<'a, C, A> {} + +impl<'a, C, A> ZoneOperationListCall<'a, C, A> where 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: "replicapoolupdater.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 Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/replicapoolupdater/v1beta1/projects/{project}/zones/{zone}/operations".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().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 ["zone", "project"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Name of the project scoping this request. + /// + /// 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, A> { + self._project = new_value.to_string(); + self + } + /// Name of the zone scoping this request. + /// + /// 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, A> { + self._zone = new_value.to_string(); + self + } + /// Optional. Tag returned by a previous list request truncated by maxResults. Used to continue a previous list request. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> ZoneOperationListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Optional. Maximum count of results to be returned. Maximum value is 500 and default value is 500. + /// + /// Sets the *max results* query property to the given value. + pub fn max_results(mut self, new_value: u32) -> ZoneOperationListCall<'a, C, A> { + self._max_results = Some(new_value); + self + } + /// Optional. Filter expression for filtering listed resources. + /// + /// Sets the *filter* query property to the given value. + pub fn filter(mut self, new_value: &str) -> ZoneOperationListCall<'a, C, A> { + self._filter = Some(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ZoneOperationListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which 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, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + diff --git a/gen/resourceviews1_beta2/src/lib.rs.in b/gen/resourceviews1_beta2/src/lib.rs.in index 4bc2685813..06a9afb54c 100644 --- a/gen/resourceviews1_beta2/src/lib.rs.in +++ b/gen/resourceviews1_beta2/src/lib.rs.in @@ -41,14 +41,17 @@ pub enum Scope { /// View your Google Cloud Platform management resources and deployment status information NdevCloudmanReadonly, + /// View and manage your Google Cloud Platform management resources and deployment status information + NdevCloudman, + + /// View your data across Google Cloud Platform services + CloudPlatformReadOnly, + /// View and manage your data across Google Cloud Platform services CloudPlatform, /// View your Google Compute Engine resources ComputeReadonly, - - /// View and manage your Google Cloud Platform management resources and deployment status information - NdevCloudman, } impl AsRef for Scope { @@ -56,9 +59,10 @@ impl AsRef for Scope { match *self { Scope::Compute => "https://www.googleapis.com/auth/compute", Scope::NdevCloudmanReadonly => "https://www.googleapis.com/auth/ndev.cloudman.readonly", + Scope::NdevCloudman => "https://www.googleapis.com/auth/ndev.cloudman", + Scope::CloudPlatformReadOnly => "https://www.googleapis.com/auth/cloud-platform.read-only", Scope::CloudPlatform => "https://www.googleapis.com/auth/cloud-platform", Scope::ComputeReadonly => "https://www.googleapis.com/auth/compute.readonly", - Scope::NdevCloudman => "https://www.googleapis.com/auth/ndev.cloudman", } } } diff --git a/gen/script1-cli/Cargo.toml b/gen/script1-cli/Cargo.toml new file mode 100644 index 0000000000..4d352e6aad --- /dev/null +++ b/gen/script1-cli/Cargo.toml @@ -0,0 +1,35 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-script1-cli" +version = "0.3.2+20150922" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with script (protocol v1)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/script1-cli" +homepage = "https://developers.google.com/apps-script/execution/rest/v1/run" +documentation = "http://byron.github.io/google-apis-rs/google_script1_cli" +license = "MIT" +keywords = ["script", "google", "cli"] + +[[bin]] +name = "script1" + +[dependencies] +hyper = ">= 0.6.8" +mime = "0.1.0" +serde = ">= 0.6.0" +serde_json = ">= 0.6.0" +yup-oauth2 = "*" +strsim = "*" +yup-hyper-mock = ">=1.0.0" +clap = ">= 1.0.3" + +[build-dependencies] +syntex = { version = "*" } +serde_codegen = { version = "*" } + + +[dependencies.google-script1] +path = "../script1" diff --git a/gen/script1-cli/LICENSE.md b/gen/script1-cli/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/script1-cli/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/script1-cli/README.md b/gen/script1-cli/README.md new file mode 100644 index 0000000000..b03f3e47f5 --- /dev/null +++ b/gen/script1-cli/README.md @@ -0,0 +1,113 @@ + +The `script1` command-line interface *(CLI)* allows to use most features of the *Google script* service from the comfort of your terminal. + +By default all output is printed to standard out, but flags can be set to direct it into a file independent of your shell's +capabilities. Errors will be printed to standard error, and cause the program's exit code to be non-zero. + +If data-structures are requested, these will be returned as pretty-printed JSON, to be useful as input to other tools. + +Everything else about the *script* API can be found at the +[official documentation site](https://developers.google.com/apps-script/execution/rest/v1/run). + +# Downloads + +You can download the pre-compiled 64bit binaries for the following platforms: + +* ![icon](http://megaicons.net/static/img/icons_sizes/6/140/16/ubuntu-icon.png) [ubuntu](http://dl.byronimo.de/google.rs/cli/0.3.2/ubuntu/script1.tar.gz) +* ![icon](http://hydra-media.cursecdn.com/wow.gamepedia.com/a/a2/Apple-icon-16x16.png?version=25ddd67ac3dd3b634478e3978b76cb74) [osx](http://dl.byronimo.de/google.rs/cli/0.3.2/osx/script1.tar.gz) + +Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/script1-cli). + +# Usage + +This documentation was generated from the *script* API at revision *20150922*. The CLI is at version *0.3.2*. + +```bash +script1 [options] + scripts + run (-r )... [-p ]... [-o ] + script1 --help + +Configuration: + [--scope ]... + Specify the authentication a method should be executed in. Each scope + requires the user to grant this application permission to use it. + If unset, it defaults to the shortest scope url for a particular method. + --config-dir + A directory into which we will store our persistent data. Defaults to + a user-writable directory that we will create during the first invocation. + [default: ~/.google-service-cli] + --debug + Output all server communication to standard error. `tx` and `rx` are placed + into the same stream. + --debug-auth + Output all communication related to authentication to standard error. `tx` + and `rx` are placed into the same stream. + +``` + +# Configuration + +The program will store all persistent data in the `~/.google-service-cli` directory in *JSON* files prefixed with `script1-`. You can change the directory used to store configuration with the `--config-dir` flag on a per-invocation basis. + +More information about the various kinds of persistent data are given in the following paragraphs. + +# Authentication + +Most APIs require a user to authenticate any request. If this is the case, the [scope][scopes] determines the +set of permissions granted. The granularity of these is usually no more than *read-only* or *full-access*. + +If not set, the system will automatically select the smallest feasible scope, e.g. when invoking a +method that is read-only, it will ask only for a read-only scope. +You may use the `--scope` flag to specify a scope directly. +All applicable scopes are documented in the respective method's CLI documentation. + +The first time a scope is used, the user is asked for permission. Follow the instructions given +by the CLI to grant permissions, or to decline. + +If a scope was authenticated by the user, the respective information will be stored as *JSON* in the configuration +directory, e.g. `~/.google-service-cli/script1-token-.json`. No manual management of these tokens +is necessary. + +To revoke granted authentication, please refer to the [official documentation][revoke-access]. + +# Application Secrets + +In order to allow any application to use Google services, it will need to be registered using the +[Google Developer Console][google-dev-console]. APIs the application may use are then enabled for it +one by one. Most APIs can be used for free and have a daily quota. + +To allow more comfortable usage of the CLI without forcing anyone to register an own application, the CLI +comes with a default application secret that is configured accordingly. This also means that heavy usage +all around the world may deplete the daily quota. + +You can workaround this limitation by putting your own secrets file at this location: +`~/.google-service-cli/script1-secret.json`, assuming that the required *script* API +was enabled for it. Such a secret file can be downloaded in the *Google Developer Console* at +*APIs & auth -> Credentials -> Download JSON* and used as is. + +Learn more about how to setup Google projects and enable APIs using the [official documentation][google-project-new]. + + +# Debugging + +Even though the CLI does its best to provide usable error messages, sometimes it might be desirable to know +what exactly led to a particular issue. This is done by allowing all client-server communication to be +output to standard error *as-is*. + +The `--debug` flag will print all client-server communication to standard error, whereas the `--debug-auth` flag +will cause all communication related to authentication to standard error. +If the `--debug` flag is set, error-results will be debug-printed, possibly yielding more information about the +issue at hand. + +You may consider redirecting standard error into a file for ease of use, e.g. `script1 --debug [options] 2>debug.txt`. + + +[scopes]: https://developers.google.com/+/api/oauth#scopes +[revoke-access]: http://webapps.stackexchange.com/a/30849 +[google-dev-console]: https://console.developers.google.com/ +[google-project-new]: https://developers.google.com/console/help/new/ \ No newline at end of file diff --git a/gen/script1-cli/mkdocs.yml b/gen/script1-cli/mkdocs.yml new file mode 100644 index 0000000000..50276bda00 --- /dev/null +++ b/gen/script1-cli/mkdocs.yml @@ -0,0 +1,17 @@ +site_name: script v0.3.2+20150922 +site_url: http://byron.github.io/google-apis-rs/google-script1-cli +site_description: Write integrating applications with bcore + +repo_url: https://github.com/Byron/google-apis-rs/tree/master/gen/script1-cli + +docs_dir: docs +site_dir: build_html + +pages: +- ['index.md', 'Home'] +- ['scripts_run.md', 'Scripts', 'Run'] + +theme: readthedocs + +copyright: Copyright © 2015, `Sebastian Thiel` + diff --git a/gen/script1-cli/src/cmn.rs b/gen/script1-cli/src/cmn.rs new file mode 100644 index 0000000000..8358f156fa --- /dev/null +++ b/gen/script1-cli/src/cmn.rs @@ -0,0 +1,721 @@ +// COPY OF 'src/rust/cli/cmn.rs' +// DO NOT EDIT +use oauth2::{ApplicationSecret, ConsoleApplicationSecret, TokenStorage, Token}; +use serde_json as json; +use serde_json::value::Value; +use mime::Mime; +use clap::{App, SubCommand}; +use strsim; + +use std::fs; +use std::env; +use std::io; +use std::fmt; +use std::path::{Path, PathBuf}; +use std::str::FromStr; +use std::string::ToString; +use std::io::{Write, Read, stdout}; + +use std::default::Default; + +const FIELD_SEP: char = '.'; + + +pub enum ComplexType { + Pod, + Vec, + Map, +} + + // Null, + // Bool(bool), + // I64(i64), + // U64(u64), + // F64(f64), + // String(String), + +pub enum JsonType { + Boolean, + Int, + Uint, + Float, + String, +} + +pub struct JsonTypeInfo { + pub jtype: JsonType, + pub ctype: ComplexType, +} + +// Based on @erickt user comment. Thanks for the idea ! +// Remove all keys whose values are null from given value (changed in place) +pub fn remove_json_null_values(value: &mut Value) { + match *value { + Value::Object(ref mut map) => { + let mut for_removal = Vec::new(); + + for (key, mut value) in map.iter_mut() { + if value.is_null() { + for_removal.push(key.clone()); + } else { + remove_json_null_values(&mut value); + } + } + + for key in &for_removal { + map.remove(key); + } + } + _ => {} + } +} + +fn did_you_mean<'a>(v: &str, possible_values: &[&'a str]) -> Option<&'a str> { + + let mut candidate: Option<(f64, &str)> = None; + for pv in possible_values { + let confidence = strsim::jaro_winkler(v, pv); + if confidence > 0.8 && (candidate.is_none() || (candidate.as_ref().unwrap().0 < confidence)) { + candidate = Some((confidence, pv)); + } + } + match candidate { + None => None, + Some((_, candidate)) => Some(candidate), + } +} + +pub enum CallType { + Upload(UploadProtocol), + Standard, +} + +arg_enum!{ + pub enum UploadProtocol { + Simple, + Resumable + } +} + +impl AsRef for UploadProtocol { + fn as_ref(&self) -> &str { + match *self { + UploadProtocol::Simple => "simple", + UploadProtocol::Resumable => "resumable" + } + } +} + +impl AsRef for CallType { + fn as_ref(&self) -> &str { + match *self { + CallType::Upload(ref proto) => proto.as_ref(), + CallType::Standard => "standard-request" + } + } +} + +#[derive(Clone, Default)] +pub struct FieldCursor(Vec); + +impl ToString for FieldCursor { + fn to_string(&self) -> String { + self.0.join(".") + } +} + +impl From<&'static str> for FieldCursor { + fn from(value: &'static str) -> FieldCursor { + let mut res = FieldCursor::default(); + res.set(value).unwrap(); + res + } +} + +impl FieldCursor { + pub fn set(&mut self, value: &str) -> Result<(), CLIError> { + if value.len() == 0 { + return Err(CLIError::Field(FieldError::Empty)) + } + + let mut first_is_field_sep = false; + let mut char_count: usize = 0; + let mut last_c = FIELD_SEP; + let mut num_conscutive_field_seps = 0; + + let mut field = String::new(); + let mut fields = self.0.clone(); + + let push_field = |fs: &mut Vec, f: &mut String| { + if f.len() > 0 { + fs.push(f.clone()); + f.truncate(0); + } + }; + + for (cid, c) in value.chars().enumerate() { + char_count += 1; + + if c == FIELD_SEP { + if cid == 0 { + first_is_field_sep = true; + } + num_conscutive_field_seps += 1; + if cid > 0 && last_c == FIELD_SEP { + if fields.pop().is_none() { + return Err(CLIError::Field(FieldError::PopOnEmpty(value.to_string()))) + } + } else { + push_field(&mut fields, &mut field); + } + } else { + num_conscutive_field_seps = 0; + if cid == 1 { + if first_is_field_sep { + fields.truncate(0); + } + } + field.push(c); + } + + last_c = c; + } + + push_field(&mut fields, &mut field); + + if char_count == 1 && first_is_field_sep { + fields.truncate(0); + } + if char_count > 1 && num_conscutive_field_seps == 1 { + return Err(CLIError::Field(FieldError::TrailingFieldSep(value.to_string()))) + } + + self.0 = fields; + Ok(()) + } + + pub fn did_you_mean(value: &str, possible_values: &[&str]) -> Option { + if value.len() == 0 { + return None + } + + let mut last_c = FIELD_SEP; + + let mut field = String::new(); + let mut output = String::new(); + + let push_field = |fs: &mut String, f: &mut String| { + if f.len() > 0 { + fs.push_str( + match did_you_mean(&f, possible_values) { + Some(candidate) => candidate, + None => &f, + }); + f.truncate(0); + } + }; + + for (cid, c) in value.chars().enumerate() { + if c == FIELD_SEP { + if last_c != FIELD_SEP { + push_field(&mut output, &mut field); + } + output.push(c); + } else { + field.push(c); + } + + last_c = c; + } + + push_field(&mut output, &mut field); + + if &output == value { + None + } else { + Some(output) + } + } + + pub fn set_json_value(&self, mut object: &mut Value, + value: &str, type_info: JsonTypeInfo, + err: &mut InvalidOptionsError, + orig_cursor: &FieldCursor) { + assert!(self.0.len() > 0); + + for field in &self.0[..self.0.len()-1] { + let tmp = object; + object = + match *tmp { + Value::Object(ref mut mapping) => { + mapping.entry(field.to_owned()).or_insert( + Value::Object(Default::default()) + ) + }, + _ => panic!("We don't expect non-object Values here ...") + }; + } + + match *object { + Value::Object(ref mut mapping) => { + let field = &self.0[self.0.len()-1]; + let to_jval = + |value: &str, jtype: JsonType, err: &mut InvalidOptionsError| + -> Value { + match jtype { + JsonType::Boolean => + Value::Bool(arg_from_str(value, err, &field, "boolean")), + JsonType::Int => + Value::I64(arg_from_str(value, err, &field, "int")), + JsonType::Uint => + Value::U64(arg_from_str(value, err, &field, "uint")), + JsonType::Float => + Value::F64(arg_from_str(value, err, &field, "float")), + JsonType::String => + Value::String(value.to_owned()), + } + }; + + match type_info.ctype { + ComplexType::Pod => { + if mapping.insert(field.to_owned(), to_jval(value, type_info.jtype, err)).is_some() { + err.issues.push(CLIError::Field(FieldError::Duplicate(orig_cursor.to_string()))); + } + }, + ComplexType::Vec => { + match *mapping.entry(field.to_owned()) + .or_insert(Value::Array(Default::default())) { + Value::Array(ref mut values) => values.push(to_jval(value, type_info.jtype, err)), + _ => unreachable!() + } + }, + ComplexType::Map => { + let (key, value) = parse_kv_arg(value, err, true); + let jval = to_jval(value.unwrap_or(""), type_info.jtype, err); + + match *mapping.entry(field.to_owned()) + .or_insert(Value::Object(Default::default())) { + Value::Object(ref mut value_map) => { + if value_map.insert(key.to_owned(), jval).is_some() { + err.issues.push(CLIError::Field(FieldError::Duplicate(orig_cursor.to_string()))); + } + } + _ => unreachable!() + } + } + } + }, + _ => unreachable!() + } + } + + pub fn num_fields(&self) -> usize { + self.0.len() + } +} + +pub fn parse_kv_arg<'a>(kv: &'a str, err: &mut InvalidOptionsError, for_hashmap: bool) + -> (&'a str, Option<&'a str>) { + let mut add_err = || err.issues.push(CLIError::InvalidKeyValueSyntax(kv.to_string(),for_hashmap)); + match kv.find('=') { + None => { + add_err(); + return (kv, None) + }, + Some(pos) => { + let key = &kv[..pos]; + if kv.len() <= pos + 1 { + add_err(); + return (key, Some("")) + } + (key, Some(&kv[pos+1..])) + } + } +} + +pub fn calltype_from_str(name: &str, valid_protocols: Vec, err: &mut InvalidOptionsError) -> CallType { + CallType::Upload( + match UploadProtocol::from_str(name) { + Ok(up) => up, + Err(msg) => { + err.issues.push(CLIError::InvalidUploadProtocol(name.to_string(), valid_protocols)); + UploadProtocol::Simple + } + }) +} + +pub fn input_file_from_opts(file_path: &str, err: &mut InvalidOptionsError) -> Option { + match fs::File::open(file_path) { + Ok(f) => Some(f), + Err(io_err) => { + err.issues.push(CLIError::Input(InputError::IOError((file_path.to_string(), io_err)))); + None + } + } +} + +pub fn input_mime_from_opts(mime: &str, err: &mut InvalidOptionsError) -> Option { + match mime.parse() { + Ok(m) => Some(m), + Err(_) => { + err.issues.push(CLIError::Input(InputError::Mime(mime.to_string()))); + None + } + } +} + +pub fn writer_from_opts(arg: Option<&str>) -> Result, io::Error> { + let f = arg.unwrap_or("-"); + match f { + "-" => Ok(Box::new(stdout())), + _ => match fs::OpenOptions::new().create(true).write(true).open(f) { + Ok(f) => Ok(Box::new(f)), + Err(io_err) => Err(io_err), + } + } +} + + +pub fn arg_from_str<'a, T>(arg: &str, err: &mut InvalidOptionsError, + arg_name: &'a str, + arg_type: &'a str) -> T + where T: FromStr + Default, + ::Err: fmt::Display { + match FromStr::from_str(arg) { + Err(perr) => { + err.issues.push( + CLIError::ParseError(arg_name.to_owned(), arg_type.to_owned(), arg.to_string(), format!("{}", perr)) + ); + Default::default() + }, + Ok(v) => v, + } +} + +pub struct JsonTokenStorage { + pub program_name: &'static str, + pub db_dir: String, +} + +impl JsonTokenStorage { + fn path(&self, scope_hash: u64) -> PathBuf { + Path::new(&self.db_dir).join(&format!("{}-token-{}.json", self.program_name, scope_hash)) + } +} + +impl TokenStorage for JsonTokenStorage { + type Error = json::Error; + + // NOTE: logging might be interesting, currently we swallow all errors + fn set(&mut self, scope_hash: u64, _: &Vec<&str>, token: Option) -> Result<(), json::Error> { + match token { + None => { + match fs::remove_file(self.path(scope_hash)) { + Err(err) => + match err.kind() { + io::ErrorKind::NotFound => Ok(()), + _ => Err(json::Error::IoError(err)) + }, + Ok(_) => Ok(()), + } + } + Some(token) => { + match fs::OpenOptions::new().create(true).write(true).open(&self.path(scope_hash)) { + Ok(mut f) => { + match json::to_writer_pretty(&mut f, &token) { + Ok(_) => Ok(()), + Err(serde_err) => Err(serde_err), + } + }, + Err(io_err) => Err(json::Error::IoError(io_err)) + } + } + } + } + + fn get(&self, scope_hash: u64, _: &Vec<&str>) -> Result, json::Error> { + match fs::File::open(&self.path(scope_hash)) { + Ok(mut f) => { + match json::de::from_reader(f) { + Ok(token) => Ok(Some(token)), + Err(err) => Err(err), + } + }, + Err(io_err) => { + match io_err.kind() { + io::ErrorKind::NotFound => Ok(None), + _ => Err(json::Error::IoError(io_err)) + } + } + } + } +} + + +#[derive(Debug)] +pub enum ApplicationSecretError { + DecoderError((String, json::Error)), + FormatError(String), +} + +impl fmt::Display for ApplicationSecretError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + ApplicationSecretError::DecoderError((ref path, ref err)) + => writeln!(f, "Could not decode file at '{}' with error: {}.", + path, err), + ApplicationSecretError::FormatError(ref path) + => writeln!(f, "'installed' field is unset in secret file at '{}'.", + path), + } + } +} + +#[derive(Debug)] +pub enum ConfigurationError { + DirectoryCreationFailed((String, io::Error)), + DirectoryUnset, + HomeExpansionFailed(String), + Secret(ApplicationSecretError), + IOError((String, io::Error)), +} + +impl fmt::Display for ConfigurationError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + ConfigurationError::DirectoryCreationFailed((ref dir, ref err)) + => writeln!(f, "Directory '{}' could not be created with error: {}.", dir, err), + ConfigurationError::DirectoryUnset + => writeln!(f, "--config-dir was unset or empty."), + ConfigurationError::HomeExpansionFailed(ref dir) + => writeln!(f, "Couldn't find HOME directory of current user, failed to expand '{}'.", dir), + ConfigurationError::Secret(ref err) + => writeln!(f, "Secret -> {}", err), + ConfigurationError::IOError((ref path, ref err)) + => writeln!(f, "IO operation failed on path '{}' with error: {}.", path, err), + } + } +} + +#[derive(Debug)] +pub enum InputError { + IOError((String, io::Error)), + Mime(String), +} + +impl fmt::Display for InputError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + InputError::IOError((ref file_path, ref io_err)) + => writeln!(f, "Failed to open '{}' for reading with error: {}.", file_path, io_err), + InputError::Mime(ref mime) + => writeln!(f, "'{}' is not a known mime-type.", mime), + } + } +} + +#[derive(Debug)] +pub enum FieldError { + PopOnEmpty(String), + TrailingFieldSep(String), + Unknown(String, Option, Option), + Duplicate(String), + Empty, +} + + +impl fmt::Display for FieldError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + FieldError::PopOnEmpty(ref field) + => writeln!(f, "'{}': Cannot move up on empty field cursor.", field), + FieldError::TrailingFieldSep(ref field) + => writeln!(f, "'{}': Single field separator may not be last character.", field), + FieldError::Unknown(ref field, ref suggestion, ref value) => { + let suffix = + match *suggestion { + Some(ref s) => { + let kv = + match *value { + Some(ref v) => format!("{}={}", s, v), + None => s.clone(), + }; + format!(" Did you mean '{}' ?", kv) + }, + None => String::new(), + }; + writeln!(f, "Field '{}' does not exist.{}", field, suffix) + }, + FieldError::Duplicate(ref cursor) + => writeln!(f, "Value at '{}' was already set", cursor), + FieldError::Empty + => writeln!(f, "Field names must not be empty."), + } + } +} + + +#[derive(Debug)] +pub enum CLIError { + Configuration(ConfigurationError), + ParseError(String, String, String, String), + UnknownParameter(String, Vec<&'static str>), + InvalidUploadProtocol(String, Vec), + InvalidKeyValueSyntax(String, bool), + Input(InputError), + Field(FieldError), + MissingCommandError, + MissingMethodError(String), +} + +impl fmt::Display for CLIError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + CLIError::Configuration(ref err) => write!(f, "Configuration -> {}", err), + CLIError::Input(ref err) => write!(f, "Input -> {}", err), + CLIError::Field(ref err) => write!(f, "Field -> {}", err), + CLIError::InvalidUploadProtocol(ref proto_name, ref valid_names) + => writeln!(f, "'{}' is not a valid upload protocol. Choose from one of {}.", proto_name, valid_names.join(", ")), + CLIError::ParseError(ref arg_name, ref type_name, ref value, ref err_desc) + => writeln!(f, "Failed to parse argument '{}' with value '{}' as {} with error: {}.", + arg_name, value, type_name, err_desc), + CLIError::UnknownParameter(ref param_name, ref possible_values) => { + let mut suffix = + match did_you_mean(param_name, &possible_values) { + Some(v) => format!(" Did you mean '{}' ?", v), + None => String::new(), + }; + write!(f, "Parameter '{}' is unknown.{}\n", param_name, suffix) + }, + CLIError::InvalidKeyValueSyntax(ref kv, is_hashmap) => { + let hashmap_info = if is_hashmap { "hashmap " } else { "" }; + writeln!(f, "'{}' does not match {}pattern =.", kv, hashmap_info) + }, + CLIError::MissingCommandError => writeln!(f, "Please specify the main sub-command."), + CLIError::MissingMethodError(ref cmd) => writeln!(f, "Please specify the method to call on the '{}' command.", cmd), + } + } +} + +#[derive(Debug)] +pub struct InvalidOptionsError { + pub issues: Vec, + pub exit_code: i32, +} + +impl fmt::Display for InvalidOptionsError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + for issue in &self.issues { + try!(issue.fmt(f)); + } + Ok(()) + } +} + +impl InvalidOptionsError { + pub fn single(err: CLIError, exit_code: i32) -> InvalidOptionsError { + InvalidOptionsError { + issues: vec![err], + exit_code: exit_code, + } + } + + pub fn new() -> InvalidOptionsError { + InvalidOptionsError { + issues: Vec::new(), + exit_code: 1, + } + } +} + +pub fn assure_config_dir_exists(dir: &str) -> Result { + let trdir = dir.trim(); + if trdir.len() == 0 { + return Err(CLIError::Configuration(ConfigurationError::DirectoryUnset)) + } + + let expanded_config_dir = + if trdir.as_bytes()[0] == b'~' { + match env::var("HOME").ok().or(env::var("UserProfile").ok()) { + None => return Err(CLIError::Configuration(ConfigurationError::HomeExpansionFailed(trdir.to_string()))), + Some(mut user) => { + user.push_str(&trdir[1..]); + user + } + } + } else { + trdir.to_string() + }; + + if let Err(err) = fs::create_dir(&expanded_config_dir) { + if err.kind() != io::ErrorKind::AlreadyExists { + return Err(CLIError::Configuration( + ConfigurationError::DirectoryCreationFailed((expanded_config_dir, err)))) + } + } + + Ok(expanded_config_dir) +} + +pub fn application_secret_from_directory(dir: &str, + secret_basename: &str, + json_console_secret: &str) + -> Result { + let secret_path = Path::new(dir).join(secret_basename); + let secret_str = || secret_path.as_path().to_str().unwrap().to_string(); + let secret_io_error = |io_err: io::Error| { + Err(CLIError::Configuration(ConfigurationError::IOError( + (secret_str(), io_err) + ))) + }; + + for _ in 0..2 { + match fs::File::open(&secret_path) { + Err(mut err) => { + if err.kind() == io::ErrorKind::NotFound { + // Write our built-in one - user may adjust the written file at will + + err = match fs::OpenOptions::new().create(true).write(true).open(&secret_path) { + Err(cfe) => cfe, + Ok(mut f) => { + // Assure we convert 'ugly' json string into pretty one + let console_secret: ConsoleApplicationSecret + = json::from_str(json_console_secret).unwrap(); + match json::to_writer_pretty(&mut f, &console_secret) { + Err(serde_err) => match serde_err { + json::Error::IoError(err) => err, + _ => panic!("Unexpected serde error: {:#?}", serde_err) + }, + Ok(_) => continue, + } + } + }; + // fall through to IO error handling + } + return secret_io_error(err) + }, + Ok(mut f) => { + match json::de::from_reader::<_, ConsoleApplicationSecret>(f) { + Err(json::Error::IoError(err)) => + return secret_io_error(err), + Err(json_err) => + return Err(CLIError::Configuration( + ConfigurationError::Secret( + ApplicationSecretError::DecoderError( + (secret_str(), json_err) + )))), + Ok(console_secret) => + match console_secret.installed { + Some(secret) => return Ok(secret), + None => return Err( + CLIError::Configuration( + ConfigurationError::Secret( + ApplicationSecretError::FormatError(secret_str()) + ))) + }, + } + } + } + } + unreachable!(); +} diff --git a/gen/script1-cli/src/main.rs b/gen/script1-cli/src/main.rs new file mode 100644 index 0000000000..05d9fcae59 --- /dev/null +++ b/gen/script1-cli/src/main.rs @@ -0,0 +1,365 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/cli/main.rs.mako' +// DO NOT EDIT ! +#![allow(unused_variables, unused_imports, dead_code, unused_mut)] + +#[macro_use] +extern crate clap; +extern crate yup_oauth2 as oauth2; +extern crate yup_hyper_mock as mock; +extern crate serde; +extern crate serde_json; +extern crate hyper; +extern crate mime; +extern crate strsim; +extern crate google_script1 as api; + +use std::env; +use std::io::{self, Write}; +use clap::{App, SubCommand, Arg}; + +mod cmn; + +use cmn::{InvalidOptionsError, CLIError, JsonTokenStorage, arg_from_str, writer_from_opts, parse_kv_arg, + input_file_from_opts, input_mime_from_opts, FieldCursor, FieldError, CallType, UploadProtocol, + calltype_from_str, remove_json_null_values, ComplexType, JsonType, JsonTypeInfo}; + +use std::default::Default; +use std::str::FromStr; + +use oauth2::{Authenticator, DefaultAuthenticatorDelegate}; +use serde_json as json; +use clap::ArgMatches; + +enum DoitError { + IoError(String, io::Error), + ApiError(api::Error), +} + +struct Engine<'n, 'a> { + opt: ArgMatches<'n, 'a>, + hub: api::Script>, + gp: Vec<&'static str>, + gpm: Vec<(&'static str, &'static str)>, +} + + +impl<'n, 'a> Engine<'n, 'a> { + fn _scripts_run(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "function" => Some(("function", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "dev-mode" => Some(("devMode", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "session-state" => Some(("sessionState", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["dev-mode", "function", "session-state"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::ExecutionRequest = json::value::from_value(object).unwrap(); + let mut call = self.hub.scripts().run(request, opt.value_of("script-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _doit(&self, dry_run: bool) -> Result, Option> { + let mut err = InvalidOptionsError::new(); + let mut call_result: Result<(), DoitError> = Ok(()); + let mut err_opt: Option = None; + match self.opt.subcommand() { + ("scripts", Some(opt)) => { + match opt.subcommand() { + ("run", Some(opt)) => { + call_result = self._scripts_run(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("scripts".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + _ => { + err.issues.push(CLIError::MissingCommandError); + writeln!(io::stderr(), "{}\n", self.opt.usage()).ok(); + } + } + + if dry_run { + if err.issues.len() > 0 { + err_opt = Some(err); + } + Err(err_opt) + } else { + Ok(call_result) + } + } + + // Please note that this call will fail if any part of the opt can't be handled + fn new(opt: ArgMatches<'a, 'n>) -> Result, InvalidOptionsError> { + let (config_dir, secret) = { + let config_dir = match cmn::assure_config_dir_exists(opt.value_of("folder").unwrap_or("~/.google-service-cli")) { + Err(e) => return Err(InvalidOptionsError::single(e, 3)), + Ok(p) => p, + }; + + match cmn::application_secret_from_directory(&config_dir, "script1-secret.json", + "{\"installed\":{\"auth_uri\":\"https://accounts.google.com/o/oauth2/auth\",\"client_secret\":\"hCsslbCUyfehWMmbkG8vTYxG\",\"token_uri\":\"https://accounts.google.com/o/oauth2/token\",\"client_email\":\"\",\"redirect_uris\":[\"urn:ietf:wg:oauth:2.0:oob\",\"oob\"],\"client_x509_cert_url\":\"\",\"client_id\":\"620010449518-9ngf7o4dhs0dka470npqvor6dc5lqb9b.apps.googleusercontent.com\",\"auth_provider_x509_cert_url\":\"https://www.googleapis.com/oauth2/v1/certs\"}}") { + Ok(secret) => (config_dir, secret), + Err(e) => return Err(InvalidOptionsError::single(e, 4)) + } + }; + + let auth = Authenticator::new( &secret, DefaultAuthenticatorDelegate, + if opt.is_present("debug-auth") { + hyper::Client::with_connector(mock::TeeConnector { + connector: hyper::net::HttpsConnector::::default() + }) + } else { + hyper::Client::new() + }, + JsonTokenStorage { + program_name: "script1", + db_dir: config_dir.clone(), + }, None); + + let client = + if opt.is_present("debug") { + hyper::Client::with_connector(mock::TeeConnector { + connector: hyper::net::HttpsConnector::::default() + }) + } else { + hyper::Client::new() + }; + let engine = Engine { + opt: opt, + hub: api::Script::new(client, auth), + gp: vec!["$-xgafv", "access-token", "alt", "bearer-token", "callback", "fields", "key", "oauth-token", "pp", "pretty-print", "quota-user", "upload-type", "upload-protocol"], + gpm: vec![ + ("$-xgafv", "$.xgafv"), + ("access-token", "access_token"), + ("bearer-token", "bearer_token"), + ("oauth-token", "oauth_token"), + ("pretty-print", "prettyPrint"), + ("quota-user", "quotaUser"), + ("upload-type", "uploadType"), + ("upload-protocol", "upload_protocol"), + ] + }; + + match engine._doit(true) { + Err(Some(err)) => Err(err), + Err(None) => Ok(engine), + Ok(_) => unreachable!(), + } + } + + fn doit(&self) -> Result<(), DoitError> { + match self._doit(false) { + Ok(res) => res, + Err(_) => unreachable!(), + } + } +} + +fn main() { + let mut exit_status = 0i32; + let arg_data = [ + ("scripts", "methods: 'run'", vec![ + ("run", + Some(r##"Runs a function in an Apps Script project that has been deployed for use with the Apps Script Execution API. This method requires authorization with an OAuth 2.0 token that includes at least one of the scopes listed in the [Authentication](#authentication) section; script projects that do not require authorization cannot be executed through this API. To find the correct scopes to include in the authentication token, open the project in the script editor, then select **File > Project properties** and click the **Scopes** tab."##), + "Details at http://byron.github.io/google-apis-rs/google_script1_cli/scripts_run", + vec![ + (Some(r##"script-id"##), + None, + Some(r##"The project key of the script to be executed. To find the project key, open the project in the script editor, then select **File > Project properties**."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ]; + + let mut app = App::new("script1") + .author("Sebastian Thiel ") + .version("0.3.2+20150922") + .about("An API for executing Google Apps Script projects.") + .after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_script1_cli") + .arg(Arg::with_name("url") + .long("scope") + .help("Specify the authentication a method should be executed in. Each scope requires the user to grant this application permission to use it.If unset, it defaults to the shortest scope url for a particular method.") + .multiple(true) + .takes_value(true)) + .arg(Arg::with_name("folder") + .long("config-dir") + .help("A directory into which we will store our persistent data. Defaults to a user-writable directory that we will create during the first invocation.[default: ~/.google-service-cli") + .multiple(false) + .takes_value(true)) + .arg(Arg::with_name("debug") + .long("debug") + .help("Output all server communication to standard error. `tx` and `rx` are placed into the same stream.") + .multiple(false) + .takes_value(false)) + .arg(Arg::with_name("debug-auth") + .long("debug-auth") + .help("Output all communication related to authentication to standard error. `tx` and `rx` are placed into the same stream.") + .multiple(false) + .takes_value(false)); + + for &(main_command_name, ref about, ref subcommands) in arg_data.iter() { + let mut mcmd = SubCommand::with_name(main_command_name).about(about); + + for &(sub_command_name, ref desc, url_info, ref args) in subcommands { + let mut scmd = SubCommand::with_name(sub_command_name); + if let &Some(desc) = desc { + scmd = scmd.about(desc); + } + scmd = scmd.after_help(url_info); + + for &(ref arg_name, ref flag, ref desc, ref required, ref multi) in args { + let arg_name_str = + match (arg_name, flag) { + (&Some(an), _ ) => an, + (_ , &Some(f)) => f, + _ => unreachable!(), + }; + let mut arg = Arg::with_name(arg_name_str) + .empty_values(false); + if let &Some(short_flag) = flag { + arg = arg.short(short_flag); + } + if let &Some(desc) = desc { + arg = arg.help(desc); + } + if arg_name.is_some() && flag.is_some() { + arg = arg.takes_value(true); + } + if let &Some(required) = required { + arg = arg.required(required); + } + if let &Some(multi) = multi { + arg = arg.multiple(multi); + } + scmd = scmd.arg(arg); + } + mcmd = mcmd.subcommand(scmd); + } + app = app.subcommand(mcmd); + } + + let matches = app.get_matches(); + + let debug = matches.is_present("debug"); + match Engine::new(matches) { + Err(err) => { + exit_status = err.exit_code; + writeln!(io::stderr(), "{}", err).ok(); + }, + Ok(engine) => { + if let Err(doit_err) = engine.doit() { + exit_status = 1; + match doit_err { + DoitError::IoError(path, err) => { + writeln!(io::stderr(), "Failed to open output file '{}': {}", path, err).ok(); + }, + DoitError::ApiError(err) => { + if debug { + writeln!(io::stderr(), "{:#?}", err).ok(); + } else { + writeln!(io::stderr(), "{}", err).ok(); + } + } + } + } + } + } + + std::process::exit(exit_status); +} \ No newline at end of file diff --git a/gen/script1/Cargo.toml b/gen/script1/Cargo.toml new file mode 100644 index 0000000000..c1509abd4e --- /dev/null +++ b/gen/script1/Cargo.toml @@ -0,0 +1,29 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-script1" +version = "0.1.9+20150922" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with script (protocol v1)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/script1" +homepage = "https://developers.google.com/apps-script/execution/rest/v1/run" +documentation = "http://byron.github.io/google-apis-rs/google_script1" +license = "MIT" +keywords = ["script", "google", "protocol", "web", "api"] +build = "src/build.rs" + + +[dependencies] +hyper = ">= 0.6.8" +mime = "0.1.0" +serde = ">= 0.6.0" +serde_json = ">= 0.6.0" +yup-oauth2 = "*" +url = "*" + +[build-dependencies] +syntex = { version = "*" } +serde_codegen = { version = "*" } + diff --git a/gen/script1/LICENSE.md b/gen/script1/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/script1/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/script1/README.md b/gen/script1/README.md new file mode 100644 index 0000000000..5c5d1c311f --- /dev/null +++ b/gen/script1/README.md @@ -0,0 +1,179 @@ + +The `google-script1` library allows access to all features of the *Google script* service. + +This documentation was generated from *script* crate version *0.1.9+20150922*, where *20150922* is the exact revision of the *script:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. + +Everything else about the *script* *v1* API can be found at the +[official documentation site](https://developers.google.com/apps-script/execution/rest/v1/run). +# Features + +Handle the following *Resources* with ease from the central [hub](http://byron.github.io/google-apis-rs/google_script1/struct.Script.html) ... + +* scripts + * [*run*](http://byron.github.io/google-apis-rs/google_script1/struct.ScriptRunCall.html) + + + + +# Structure of this Library + +The API is structured into the following primary items: + +* **[Hub](http://byron.github.io/google-apis-rs/google_script1/struct.Script.html)** + * a central object to maintain state and allow accessing all *Activities* + * creates [*Method Builders*](http://byron.github.io/google-apis-rs/google_script1/trait.MethodsBuilder.html) which in turn + allow access to individual [*Call Builders*](http://byron.github.io/google-apis-rs/google_script1/trait.CallBuilder.html) +* **[Resources](http://byron.github.io/google-apis-rs/google_script1/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_script1/trait.Part.html)** + * a collection of properties + * never directly used in *Activities* +* **[Activities](http://byron.github.io/google-apis-rs/google_script1/trait.CallBuilder.html)** + * operations to apply to *Resources* + +All *structures* are marked with applicable traits to further categorize them and ease browsing. + +Generally speaking, you can invoke *Activities* like this: + +```Rust,ignore +let r = hub.resource().activity(...).doit() +``` + +Or specifically ... + +```ignore +let r = hub.scripts().run(...).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-script1 = "*" +``` + +## A complete example + +```Rust +extern crate hyper; +extern crate yup_oauth2 as oauth2; +extern crate google_script1 as script1; +use script1::ExecutionRequest; +use script1::{Result, Error}; +use std::default::Default; +use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +use script1::Script; + +// 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 = Script::new(hyper::Client::new(), auth); +// As the method needs a request, you would usually fill it with the desired information +// into the respective structure. Some of the parts shown here might not be applicable ! +// Values shown here are possibly random and not representative ! +let mut req = ExecutionRequest::default(); + +// You can configure optional parameters by calling the respective setters at will, and +// execute the final call using `doit()`. +// Values shown here are possibly random and not representative ! +let result = hub.scripts().run(req, "scriptId") + .doit(); + +match result { + Err(e) => match e { + // The Error enum provides details about what exactly happened. + // You can also just use its `Debug`, `Display` or `Error` traits + Error::HttpError(_) + |Error::MissingAPIKey + |Error::MissingToken(_) + |Error::Cancelled + |Error::UploadSizeLimitExceeded(_, _) + |Error::Failure(_) + |Error::BadRequest(_) + |Error::FieldClash(_) + |Error::JsonDecodeError(_, _) => println!("{}", e), + }, + Ok(res) => println!("Success: {:?}", res), +} + +``` +## Handling Errors + +All errors produced by the system are provided either as [Result](http://byron.github.io/google-apis-rs/google_script1/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_script1/trait.Delegate.html), or the [Authenticator Delegate](http://byron.github.io/google-apis-rs/google_script1/../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 Downloads +If a method supports downloads, the response body, which is part of the [Result](http://byron.github.io/google-apis-rs/google_script1/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_script1/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_script1/trait.Delegate.html) to the +[Method Builder](http://byron.github.io/google-apis-rs/google_script1/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_script1/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_script1/trait.RequestValue.html) and +[decodable](http://byron.github.io/google-apis-rs/google_script1/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_script1/trait.Part.html) which are identifiable 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_script1/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_script1/trait.RequestValue.html) are moved + +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 **script1** 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/script1/src/build.rs b/gen/script1/src/build.rs new file mode 100644 index 0000000000..dea7368edf --- /dev/null +++ b/gen/script1/src/build.rs @@ -0,0 +1,16 @@ +extern crate syntex; +extern crate serde_codegen; + +use std::env; +use std::path::Path; + +pub fn main() { + let out_dir = env::var_os("OUT_DIR").unwrap(); + + let src = Path::new("src/lib.rs.in"); + let dst = Path::new(&out_dir).join("lib.rs"); + + let mut registry = syntex::Registry::new(); + serde_codegen::register(&mut registry); + registry.expand("google-script1", &src, &dst).unwrap(); +} diff --git a/gen/script1/src/cmn.rs b/gen/script1/src/cmn.rs new file mode 100644 index 0000000000..0e31353ba3 --- /dev/null +++ b/gen/script1/src/cmn.rs @@ -0,0 +1,762 @@ +// COPY OF 'src/rust/api/cmn.rs' +// DO NOT EDIT +use std::io::{self, Read, Seek, Cursor, Write, SeekFrom}; +use std; +use std::fmt::{self, Display}; +use std::str::FromStr; +use std::error; +use std::thread::sleep_ms; + +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::h1::LINE_ENDING; +use hyper::method::Method; +use hyper::status::StatusCode; + +use serde_json as json; + +/// 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 {} + +/// Identifies types for building methods of a particular resource type +pub trait MethodsBuilder {} + +/// Identifies types which represent builders for a particular resource method +pub trait CallBuilder {} + +/// Identifies types which can be inserted and deleted. +/// Types with this trait are most commonly used by clients of this API. +pub trait Resource {} + +/// Identifies types which are used in API responses. +pub trait ResponseResult {} + +/// Identifies types which are used in API requests. +pub trait RequestValue {} + +/// Identifies types which are not actually used by the API +/// This might be a bug within the google API schema. +pub trait UnusedType {} + +/// Identifies types which are only used as part of other types, which +/// usually are carrying the `Resource` trait. +pub trait Part {} + +/// 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 {} + +/// 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 +} + +/// A utility to represent detailed errors we might see in case there are BadRequests. +/// The latter happen if the sent parameters or request structures are unsound +#[derive(Deserialize, Serialize, Debug)] +pub struct ErrorResponse { + error: ServerError, +} + +#[derive(Deserialize, Serialize, Debug)] +pub struct ServerError { + errors: Vec, + code: u16, + message: String, +} + +#[derive(Deserialize, Serialize, Debug)] +pub struct ServerMessage { + domain: String, + reason: String, + message: String, + #[serde(rename="locationType")] + location_type: Option, + location: 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 successful. That way, the delegate 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. + /// + /// If you choose to retry after a duration, the duration should be chosen using the + /// [exponential backoff algorithm](http://en.wikipedia.org/wiki/Exponential_backoff). + /// + /// Return retry information. + fn http_error(&mut self, &hyper::Error) -> 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 it as a general information about the + /// impending failure. + /// The given Error provides information about why the token couldn't be acquired in the + /// first place + fn token(&mut self, err: &error::Error) -> Option { + let _ = err; + 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/canceled, 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()`. + /// It will also be called with None after a successful upload, which allows the delegate + /// to forget the URL. That way, we will not attempt to resume an upload that has already + /// finished. + fn store_upload_url(&mut self, url: Option<&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: &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. + /// + /// If you choose to retry after a duration, the duration should be chosen using the + /// [exponential backoff algorithm](http://en.wikipedia.org/wiki/Exponential_backoff). + fn http_failure(&mut self, _: &hyper::client::Response, Option, _: 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 {} + + +#[derive(Debug)] +pub enum Error { + /// The http connection failed + HttpError(hyper::Error), + + /// 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), + + /// Represents information about a request that was not understood by the server. + /// Details are included. + BadRequest(ErrorResponse), + + /// 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(Box), + + /// 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(String, json::Error), + + /// Indicates an HTTP repsonse with a non-success status code + Failure(hyper::client::Response), +} + + +impl Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + Error::HttpError(ref err) => err.fmt(f), + Error::UploadSizeLimitExceeded(ref resource_size, ref max_size) => + writeln!(f, "The media size {} exceeds the maximum allowed upload size of {}" + , resource_size, max_size), + Error::MissingAPIKey => { + (writeln!(f, "The application's API key was not found in the configuration")).ok(); + writeln!(f, "It is used as there are no Scopes defined for this method.") + }, + Error::BadRequest(ref err) => { + try!(writeln!(f, "Bad Requst ({}): {}", err.error.code, err.error.message)); + for err in err.error.errors.iter() { + try!(writeln!(f, " {}: {}, {}{}", + err.domain, + err.message, + err.reason, + match &err.location { + &Some(ref loc) => format!("@{}", loc), + &None => String::new(), + })); + } + Ok(()) + }, + Error::MissingToken(ref err) => + writeln!(f, "Token retrieval failed with error: {}", err), + Error::Cancelled => + writeln!(f, "Operation cancelled by delegate"), + Error::FieldClash(field) => + writeln!(f, "The custom parameter '{}' is already provided natively by the CallBuilder.", field), + Error::JsonDecodeError(ref json_str, ref err) + => writeln!(f, "{}: {}", err, json_str), + Error::Failure(ref response) => + writeln!(f, "Http status indicates failure: {:?}", response), + } + } +} + +impl error::Error for Error { + fn description(&self) -> &str { + match *self { + Error::HttpError(ref err) => err.description(), + Error::JsonDecodeError(_, ref err) => err.description(), + _ => "NO DESCRIPTION POSSIBLE - use `Display.fmt()` instead" + } + } + + fn cause(&self) -> Option<&error::Error> { + match *self { + Error::HttpError(ref err) => err.cause(), + Error::JsonDecodeError(_, ref err) => err.cause(), + _ => None + } + } +} + +/// A universal result type used as return for all calls. +pub type Result = std::result::Result; + +/// 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 + 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 following macro invocation needs to be expanded, as `include!` +// doens't support external macros +// header!{ +// #[doc="The `X-Upload-Content-Type` header."] +// (XUploadContentType, "X-Upload-Content-Type") => [Mime] + +// xupload_content_type { +// test_header!( +// test1, +// vec![b"text/plain"], +// Some(HeaderField( +// vec![Mime(TopLevel::Text, SubLevel::Plain, Vec::new())] +// ))); + +// } +// } + +/// The `X-Upload-Content-Type` header. +/// +/// Generated via rustc --pretty expanded -Z unstable-options, and manually +/// processed to be more readable. +#[derive(PartialEq, Debug, Clone)] +pub struct XUploadContentType(pub Mime); + +impl ::std::ops::Deref for XUploadContentType { + type Target = Mime; + fn deref<'a>(&'a self) -> &'a Mime { &self.0 } +} +impl ::std::ops::DerefMut for XUploadContentType { + fn deref_mut<'a>(&'a mut self) -> &'a mut Mime { &mut self.0 } +} +impl Header for XUploadContentType { + fn header_name() -> &'static str { "X-Upload-Content-Type" } + fn parse_header(raw: &[Vec]) -> hyper::error::Result { + hyper::header::parsing::from_one_raw_str(raw).map(XUploadContentType) + } +} +impl HeaderFormat for XUploadContentType { + fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { + Display::fmt(&**self, f) + } +} +impl Display for XUploadContentType { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Display::fmt(&**self, f) + } +} + +#[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]) -> hyper::error::Result { + Err(hyper::error::Error::Method) + } +} + + +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]) -> hyper::error::Result { + if raw.len() > 0 { + let v = &raw[0]; + if let Ok(s) = std::str::from_utf8(v) { + const PREFIX: &'static str = "bytes "; + if s.starts_with(PREFIX) { + if let Ok(c) = ::from_str(&s[PREFIX.len()..]) { + return Ok(RangeResponseHeader(c)) + } + } + } + } + Err(hyper::error::Error::Method) + } +} + +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, 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, A> ResumableUploadHelper<'a, A> + where A: oauth2::GetToken { + + fn query_transfer_status(&mut self) -> std::result::Result> { + 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, None) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + return Err(Ok(r)) + } + }; + return Ok(h.0.last) + } + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + return Err(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() { + Ok(s) => s, + Err(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 + }; + + self.reader.seek(SeekFrom::Start(start)).unwrap(); + loop { + let request_size = match self.content_length - start { + rs if rs > chunk_size => chunk_size, + rs => rs + }; + + 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 + } + // workaround https://github.com/rust-lang/rust/issues/22252 + let res = 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(); + match res { + 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, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + } + return Some(Ok(res)) + }, + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + return Some(Err(err)) + } + } + } + } +} + +// Copy of src/rust/cli/cmn.rs +// TODO(ST): Allow sharing common code between program types +pub fn remove_json_null_values(value: &mut json::value::Value) { + match *value { + json::value::Value::Object(ref mut map) => { + let mut for_removal = Vec::new(); + + for (key, mut value) in map.iter_mut() { + if value.is_null() { + for_removal.push(key.clone()); + } else { + remove_json_null_values(&mut value); + } + } + + for key in &for_removal { + map.remove(key); + } + } + _ => {} + } +} diff --git a/gen/script1/src/lib.rs b/gen/script1/src/lib.rs new file mode 100644 index 0000000000..562cb0d3fc --- /dev/null +++ b/gen/script1/src/lib.rs @@ -0,0 +1,183 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/api/lib.rs.mako' +// DO NOT EDIT ! + +//! This documentation was generated from *script* crate version *0.1.9+20150922*, where *20150922* is the exact revision of the *script:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +//! +//! Everything else about the *script* *v1* API can be found at the +//! [official documentation site](https://developers.google.com/apps-script/execution/rest/v1/run). +//! The original source code is [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/script1). +//! # Features +//! +//! Handle the following *Resources* with ease from the central [hub](struct.Script.html) ... +//! +//! * scripts +//! * [*run*](struct.ScriptRunCall.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.Script.html)** +//! * a central object to maintain state and allow accessing all *Activities* +//! * creates [*Method Builders*](trait.MethodsBuilder.html) which in turn +//! allow access to individual [*Call Builders*](trait.CallBuilder.html) +//! * **[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* +//! +//! All *structures* are marked with applicable traits to further categorize them and ease browsing. +//! +//! Generally speaking, you can invoke *Activities* like this: +//! +//! ```Rust,ignore +//! let r = hub.resource().activity(...).doit() +//! ``` +//! +//! Or specifically ... +//! +//! ```ignore +//! let r = hub.scripts().run(...).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-script1 = "*" +//! ``` +//! +//! ## A complete example +//! +//! ```test_harness,no_run +//! extern crate hyper; +//! extern crate yup_oauth2 as oauth2; +//! extern crate google_script1 as script1; +//! use script1::ExecutionRequest; +//! use script1::{Result, Error}; +//! # #[test] fn egal() { +//! use std::default::Default; +//! use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +//! use script1::Script; +//! +//! // 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 = Script::new(hyper::Client::new(), auth); +//! // As the method needs a request, you would usually fill it with the desired information +//! // into the respective structure. Some of the parts shown here might not be applicable ! +//! // Values shown here are possibly random and not representative ! +//! let mut req = ExecutionRequest::default(); +//! +//! // You can configure optional parameters by calling the respective setters at will, and +//! // execute the final call using `doit()`. +//! // Values shown here are possibly random and not representative ! +//! let result = hub.scripts().run(req, "scriptId") +//! .doit(); +//! +//! match result { +//! Err(e) => match e { +//! // The Error enum provides details about what exactly happened. +//! // You can also just use its `Debug`, `Display` or `Error` traits +//! Error::HttpError(_) +//! |Error::MissingAPIKey +//! |Error::MissingToken(_) +//! |Error::Cancelled +//! |Error::UploadSizeLimitExceeded(_, _) +//! |Error::Failure(_) +//! |Error::BadRequest(_) +//! |Error::FieldClash(_) +//! |Error::JsonDecodeError(_, _) => println!("{}", e), +//! }, +//! Ok(res) => println!("Success: {:?}", res), +//! } +//! # } +//! ``` +//! ## 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 Downloads +//! 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 identifiable 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 moved +//! +//! 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 +//! +//! + +// 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)] + +include!(concat!(env!("OUT_DIR"), "/lib.rs")); \ No newline at end of file diff --git a/gen/script1/src/lib.rs.in b/gen/script1/src/lib.rs.in new file mode 100644 index 0000000000..6962bbc652 --- /dev/null +++ b/gen/script1/src/lib.rs.in @@ -0,0 +1,611 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/api/lib.rs.in.mako' +// DO NOT EDIT ! + +extern crate hyper; +extern crate serde; +extern crate serde_json; +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 serde_json as json; +use std::io; +use std::fs; +use std::thread::sleep_ms; + +pub use cmn::{MultiPartReader, ToParts, MethodInfo, Result, Error, CallBuilder, Hub, ReadSeek, Part, + ResponseResult, RequestValue, NestedType, Delegate, DefaultDelegate, MethodsBuilder, + Resource, ErrorResponse, remove_json_null_values}; + + +// ############## +// 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 and manage your mail + Scrip, + + /// View and manage forms that this application has been installed in + FormCurrentonly, + + /// View and manage the provisioning of users on your domain + AdminDirectoryUser, + + /// Manage your contacts + Feed, + + /// View and manage your Google Groups + Group, + + /// View and manage the provisioning of groups on your domain + AdminDirectoryGroup, + + /// View and manage your forms in Google Drive + Form, + + /// Manage your calendars + Feed, + + /// View your email address + UserinfoEmail, +} + +impl AsRef for Scope { + fn as_ref(&self) -> &str { + match *self { + Scope::Drive => "https://www.googleapis.com/auth/drive", + Scope::Scrip => "https://mail.google.com/", + Scope::FormCurrentonly => "https://www.googleapis.com/auth/forms.currentonly", + Scope::AdminDirectoryUser => "https://www.googleapis.com/auth/admin.directory.user", + Scope::Feed => "https://www.google.com/m8/feeds", + Scope::Group => "https://www.googleapis.com/auth/groups", + Scope::AdminDirectoryGroup => "https://www.googleapis.com/auth/admin.directory.group", + Scope::Form => "https://www.googleapis.com/auth/forms", + Scope::Feed => "https://www.google.com/calendar/feeds", + Scope::UserinfoEmail => "https://www.googleapis.com/auth/userinfo.email", + } + } +} + +impl Default for Scope { + fn default() -> Scope { + Scope::Scrip + } +} + + + +// ######## +// HUB ### +// ###### + +/// Central instance to access all Script related resource activities +/// +/// # Examples +/// +/// Instantiate a new hub +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate yup_oauth2 as oauth2; +/// extern crate google_script1 as script1; +/// use script1::ExecutionRequest; +/// use script1::{Result, Error}; +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use script1::Script; +/// +/// // 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 = Script::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req = ExecutionRequest::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.scripts().run(req, "scriptId") +/// .doit(); +/// +/// match result { +/// Err(e) => match e { +/// // The Error enum provides details about what exactly happened. +/// // You can also just use its `Debug`, `Display` or `Error` traits +/// Error::HttpError(_) +/// |Error::MissingAPIKey +/// |Error::MissingToken(_) +/// |Error::Cancelled +/// |Error::UploadSizeLimitExceeded(_, _) +/// |Error::Failure(_) +/// |Error::BadRequest(_) +/// |Error::FieldClash(_) +/// |Error::JsonDecodeError(_, _) => println!("{}", e), +/// }, +/// Ok(res) => println!("Success: {:?}", res), +/// } +/// # } +/// ``` +pub struct Script { + client: RefCell, + auth: RefCell, + _user_agent: String, +} + +impl<'a, C, A> Hub for Script {} + +impl<'a, C, A> Script + where C: BorrowMut, A: oauth2::GetToken { + + pub fn new(client: C, authenticator: A) -> Script { + Script { + client: RefCell::new(client), + auth: RefCell::new(authenticator), + _user_agent: "google-api-rust-client/0.1.9".to_string(), + } + } + + pub fn scripts(&'a self) -> ScriptMethods<'a, C, A> { + ScriptMethods { 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.9`. + /// + /// 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 ### +// ########## +/// If a `run` call succeeds but the script function (or Apps Script itself) throws an exception, the response body's `error` field will contain this `Status` object. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Status { + /// A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the google.rpc.Status.details field, or localized by the client. + pub message: Option, + /// The status code, which should be an enum value of google.rpc.Code. + pub code: Option, + /// An array that contains a single `ExecutionError` object that provides information about the nature of the error. + pub details: Option>>, +} + +impl Part for Status {} + + +/// A request to run the function in a script. The script is identified by the specified `script_id`. Executing a function on a script will return results based on the implementation of the script. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where 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 scripts](struct.ScriptRunCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ExecutionRequest { + /// The name of the function to execute in the given script. The name does not include parentheses or parameters. + pub function: Option, + /// This field is not used. + #[serde(rename="sessionState")] + pub session_state: Option, + /// The parameters to be passed to the function being executed. The type for each parameter should match the expected type in Apps Script. Parameters cannot be Apps Script-specific objects (such as a `Document` or `Calendar`); they can only be primitive types such as a `string`, `number`, `array`, `object`, or `boolean`. Optional. + pub parameters: Option>, + /// If `true` and the user is an owner of the script, the script runs at the most recently saved version rather than the version deployed for use with the Execution API. Optional; default is `false`. + #[serde(rename="devMode")] + pub dev_mode: Option, +} + +impl RequestValue for ExecutionRequest {} + + +/// The response will not arrive until the function finishes executing. The maximum runtime is listed in the guide to [limitations in Apps Script](https://developers.google.com/apps-script/guides/services/quotas#current_limitations). +/// If the script function returns successfully, the `response` field will contain an `ExecutionResponse` object with the function's return value in the object's `result` field. +/// +/// If the script function (or Apps Script itself) throws an exception, the `error` field will contain a `Status` object. The `Status` object's `details` field will contain an array with a single `ExecutionError` object that provides information about the nature of the error. +/// +/// If the `run` call itself fails (for example, because of a malformed request or an authorization error), the method will return an HTTP response code in the 4XX range with a different format for the response body. Client libraries will automatically convert a 4XX response into an exception class. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where 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 scripts](struct.ScriptRunCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Operation { + /// This field is not used. + pub metadata: Option>, + /// This field is not used. + pub done: Option, + /// If the script function returns successfully, this field will contain an `ExecutionResponse` object with the function's return value as the object's `result` field. + pub response: Option>, + /// This field is not used. + pub name: Option, + /// If a `run` call succeeds but the script function (or Apps Script itself) throws an exception, this field will contain a `Status` object. The `Status` object's `details` field will contain an array with a single `ExecutionError` object that provides information about the nature of the error. + pub error: Option, +} + +impl ResponseResult for Operation {} + + + +// ################### +// MethodBuilders ### +// ################# + +/// A builder providing access to all methods supported on *script* resources. +/// It is not used directly, but through the `Script` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate yup_oauth2 as oauth2; +/// extern crate google_script1 as script1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use script1::Script; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Script::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `run(...)` +/// // to build up your call. +/// let rb = hub.scripts(); +/// # } +/// ``` +pub struct ScriptMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Script, +} + +impl<'a, C, A> MethodsBuilder for ScriptMethods<'a, C, A> {} + +impl<'a, C, A> ScriptMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Runs a function in an Apps Script project that has been deployed for use with the Apps Script Execution API. This method requires authorization with an OAuth 2.0 token that includes at least one of the scopes listed in the [Authentication](#authentication) section; script projects that do not require authorization cannot be executed through this API. To find the correct scopes to include in the authentication token, open the project in the script editor, then select **File > Project properties** and click the **Scopes** tab. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `scriptId` - The project key of the script to be executed. To find the project key, open the project in the script editor, then select **File > Project properties**. + pub fn run(&self, request: ExecutionRequest, script_id: &str) -> ScriptRunCall<'a, C, A> { + ScriptRunCall { + hub: self.hub, + _request: request, + _script_id: script_id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + + + +// ################### +// CallBuilders ### +// ################# + +/// Runs a function in an Apps Script project that has been deployed for use with the Apps Script Execution API. This method requires authorization with an OAuth 2.0 token that includes at least one of the scopes listed in the [Authentication](#authentication) section; script projects that do not require authorization cannot be executed through this API. To find the correct scopes to include in the authentication token, open the project in the script editor, then select **File > Project properties** and click the **Scopes** tab. +/// +/// A builder for the *run* method supported by a *script* resource. +/// It is not used directly, but through a `ScriptMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_script1 as script1; +/// use script1::ExecutionRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use script1::Script; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Script::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req = ExecutionRequest::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.scripts().run(req, "scriptId") +/// .doit(); +/// # } +/// ``` +pub struct ScriptRunCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Script, + _request: ExecutionRequest, + _script_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ScriptRunCall<'a, C, A> {} + +impl<'a, C, A> ScriptRunCall<'a, C, A> where 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: "script.scripts.run", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("scriptId", self._script_id.to_string())); + for &field in ["alt", "scriptId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://script.googleapis.com/v1/scripts/{scriptId}:run".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Scrip.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{scriptId}", "scriptId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["scriptId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: ExecutionRequest) -> ScriptRunCall<'a, C, A> { + self._request = new_value; + self + } + /// The project key of the script to be executed. To find the project key, open the project in the script editor, then select **File > Project properties**. + /// + /// Sets the *script id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn script_id(mut self, new_value: &str) -> ScriptRunCall<'a, C, A> { + self._script_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ScriptRunCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> ScriptRunCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Scrip`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ScriptRunCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + diff --git a/gen/siteverification1-cli/Cargo.toml b/gen/siteverification1-cli/Cargo.toml index bc90e55651..f76d0a219a 100644 --- a/gen/siteverification1-cli/Cargo.toml +++ b/gen/siteverification1-cli/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-siteverification1-cli" -version = "0.3.2+20131007" +version = "0.3.2+20151007" authors = ["Sebastian Thiel "] description = "A complete library to interact with siteVerification (protocol v1)" repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/siteverification1-cli" diff --git a/gen/siteverification1-cli/README.md b/gen/siteverification1-cli/README.md index 1d7f6bb93e..0ba4f23b91 100644 --- a/gen/siteverification1-cli/README.md +++ b/gen/siteverification1-cli/README.md @@ -24,7 +24,7 @@ Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/ma # Usage -This documentation was generated from the *siteVerification* API at revision *20131007*. The CLI is at version *0.3.2*. +This documentation was generated from the *siteVerification* API at revision *20151007*. The CLI is at version *0.3.2*. ```bash siteverification1 [options] diff --git a/gen/siteverification1-cli/mkdocs.yml b/gen/siteverification1-cli/mkdocs.yml index 10ad496626..3a7022e30b 100644 --- a/gen/siteverification1-cli/mkdocs.yml +++ b/gen/siteverification1-cli/mkdocs.yml @@ -1,4 +1,4 @@ -site_name: siteVerification v0.3.2+20131007 +site_name: siteVerification v0.3.2+20151007 site_url: http://byron.github.io/google-apis-rs/google-siteverification1-cli site_description: Write integrating applications with bcore diff --git a/gen/siteverification1-cli/src/main.rs b/gen/siteverification1-cli/src/main.rs index 5a0f6bd01c..6e39a0259b 100644 --- a/gen/siteverification1-cli/src/main.rs +++ b/gen/siteverification1-cli/src/main.rs @@ -827,7 +827,7 @@ fn main() { let mut app = App::new("siteverification1") .author("Sebastian Thiel ") - .version("0.3.2+20131007") + .version("0.3.2+20151007") .about("Lets you programatically verify ownership of websites or domains with Google.") .after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_siteverification1_cli") .arg(Arg::with_name("url") diff --git a/gen/siteverification1/Cargo.toml b/gen/siteverification1/Cargo.toml index ba45956bba..4e88dbf011 100644 --- a/gen/siteverification1/Cargo.toml +++ b/gen/siteverification1/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-siteverification1" -version = "0.1.9+20131007" +version = "0.1.9+20151007" authors = ["Sebastian Thiel "] description = "A complete library to interact with siteVerification (protocol v1)" repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/siteverification1" diff --git a/gen/siteverification1/README.md b/gen/siteverification1/README.md index d50a9909ad..a3cf506325 100644 --- a/gen/siteverification1/README.md +++ b/gen/siteverification1/README.md @@ -5,7 +5,7 @@ DO NOT EDIT ! --> The `google-siteverification1` library allows access to all features of the *Google siteVerification* service. -This documentation was generated from *siteVerification* crate version *0.1.9+20131007*, where *20131007* is the exact revision of the *siteVerification:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +This documentation was generated from *siteVerification* crate version *0.1.9+20151007*, where *20151007* is the exact revision of the *siteVerification:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. Everything else about the *siteVerification* *v1* API can be found at the [official documentation site](https://developers.google.com/site-verification/). diff --git a/gen/siteverification1/src/lib.rs b/gen/siteverification1/src/lib.rs index 1c2633d439..80d9446baa 100644 --- a/gen/siteverification1/src/lib.rs +++ b/gen/siteverification1/src/lib.rs @@ -2,7 +2,7 @@ // This file was generated automatically from 'src/mako/api/lib.rs.mako' // DO NOT EDIT ! -//! This documentation was generated from *siteVerification* crate version *0.1.9+20131007*, where *20131007* is the exact revision of the *siteVerification:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +//! This documentation was generated from *siteVerification* crate version *0.1.9+20151007*, where *20151007* is the exact revision of the *siteVerification:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. //! //! Everything else about the *siteVerification* *v1* API can be found at the //! [official documentation site](https://developers.google.com/site-verification/). diff --git a/gen/spectrum1_explorer-cli/Cargo.toml b/gen/spectrum1_explorer-cli/Cargo.toml index dd354e60ff..4da5920ea1 100644 --- a/gen/spectrum1_explorer-cli/Cargo.toml +++ b/gen/spectrum1_explorer-cli/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-spectrum1_explorer-cli" -version = "0.3.2+20150112" +version = "0.3.2+20150716" authors = ["Sebastian Thiel "] description = "A complete library to interact with spectrum (protocol v1explorer)" repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/spectrum1_explorer-cli" diff --git a/gen/spectrum1_explorer-cli/README.md b/gen/spectrum1_explorer-cli/README.md index d5771333aa..f27598b9d1 100644 --- a/gen/spectrum1_explorer-cli/README.md +++ b/gen/spectrum1_explorer-cli/README.md @@ -24,7 +24,7 @@ Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/ma # Usage -This documentation was generated from the *spectrum* API at revision *20150112*. The CLI is at version *0.3.2*. +This documentation was generated from the *spectrum* API at revision *20150716*. The CLI is at version *0.3.2*. ```bash spectrum1-explorer [options] diff --git a/gen/spectrum1_explorer-cli/mkdocs.yml b/gen/spectrum1_explorer-cli/mkdocs.yml index 26562d8233..86a920bf27 100644 --- a/gen/spectrum1_explorer-cli/mkdocs.yml +++ b/gen/spectrum1_explorer-cli/mkdocs.yml @@ -1,4 +1,4 @@ -site_name: spectrum v0.3.2+20150112 +site_name: spectrum v0.3.2+20150716 site_url: http://byron.github.io/google-apis-rs/google-spectrum1_explorer-cli site_description: Write integrating applications with bcore diff --git a/gen/spectrum1_explorer-cli/src/main.rs b/gen/spectrum1_explorer-cli/src/main.rs index 72ffa7540b..13ad970c31 100644 --- a/gen/spectrum1_explorer-cli/src/main.rs +++ b/gen/spectrum1_explorer-cli/src/main.rs @@ -960,7 +960,7 @@ fn main() { let mut app = App::new("spectrum1-explorer") .author("Sebastian Thiel ") - .version("0.3.2+20150112") + .version("0.3.2+20150716") .about("API for spectrum-management functions.") .after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_spectrum1_explorer_cli") .arg(Arg::with_name("folder") diff --git a/gen/spectrum1_explorer/Cargo.toml b/gen/spectrum1_explorer/Cargo.toml index 0e551411fc..38f100a3c2 100644 --- a/gen/spectrum1_explorer/Cargo.toml +++ b/gen/spectrum1_explorer/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-spectrum1_explorer" -version = "0.1.9+20150112" +version = "0.1.9+20150716" authors = ["Sebastian Thiel "] description = "A complete library to interact with spectrum (protocol v1explorer)" repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/spectrum1_explorer" diff --git a/gen/spectrum1_explorer/README.md b/gen/spectrum1_explorer/README.md index 5a47170407..750d16f998 100644 --- a/gen/spectrum1_explorer/README.md +++ b/gen/spectrum1_explorer/README.md @@ -5,7 +5,7 @@ DO NOT EDIT ! --> The `google-spectrum1_explorer` library allows access to all features of the *Google spectrum* service. -This documentation was generated from *spectrum* crate version *0.1.9+20150112*, where *20150112* is the exact revision of the *spectrum:v1explorer* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +This documentation was generated from *spectrum* crate version *0.1.9+20150716*, where *20150716* is the exact revision of the *spectrum:v1explorer* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. Everything else about the *spectrum* *v1_explorer* API can be found at the [official documentation site](http://developers.google.com/spectrum). diff --git a/gen/spectrum1_explorer/src/lib.rs b/gen/spectrum1_explorer/src/lib.rs index 1a2246f36f..5c43d3ba03 100644 --- a/gen/spectrum1_explorer/src/lib.rs +++ b/gen/spectrum1_explorer/src/lib.rs @@ -2,7 +2,7 @@ // This file was generated automatically from 'src/mako/api/lib.rs.mako' // DO NOT EDIT ! -//! This documentation was generated from *spectrum* crate version *0.1.9+20150112*, where *20150112* is the exact revision of the *spectrum:v1explorer* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +//! This documentation was generated from *spectrum* crate version *0.1.9+20150716*, where *20150716* is the exact revision of the *spectrum:v1explorer* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. //! //! Everything else about the *spectrum* *v1_explorer* API can be found at the //! [official documentation site](http://developers.google.com/spectrum). diff --git a/gen/sqladmin1_beta4-cli/Cargo.toml b/gen/sqladmin1_beta4-cli/Cargo.toml index f441932dfa..d208f5efc6 100644 --- a/gen/sqladmin1_beta4-cli/Cargo.toml +++ b/gen/sqladmin1_beta4-cli/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-sqladmin1_beta4-cli" -version = "0.3.2+20150305" +version = "0.3.2+20151013" authors = ["Sebastian Thiel "] description = "A complete library to interact with SQL Admin (protocol v1beta4)" repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/sqladmin1_beta4-cli" diff --git a/gen/sqladmin1_beta4-cli/README.md b/gen/sqladmin1_beta4-cli/README.md index 3e80858584..a5351f019e 100644 --- a/gen/sqladmin1_beta4-cli/README.md +++ b/gen/sqladmin1_beta4-cli/README.md @@ -24,11 +24,12 @@ Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/ma # Usage -This documentation was generated from the *SQL Admin* API at revision *20150305*. The CLI is at version *0.3.2*. +This documentation was generated from the *SQL Admin* API at revision *20151013*. The CLI is at version *0.3.2*. ```bash sqladmin1-beta4 [options] backup-runs + delete [-p ]... [-o ] get [-p ]... [-o ] list [-p ]... [-o ] databases @@ -44,6 +45,7 @@ sqladmin1-beta4 [options] clone (-r )... [-p ]... [-o ] delete [-p ]... [-o ] export (-r )... [-p ]... [-o ] + failover (-r )... [-p ]... [-o ] get [-p ]... [-o ] import (-r )... [-p ]... [-o ] insert (-r )... [-p ]... [-o ] @@ -60,6 +62,7 @@ sqladmin1-beta4 [options] get [-p ]... [-o ] list [-p ]... [-o ] ssl-certs + create-ephemeral (-r )... [-p ]... [-o ] delete [-p ]... [-o ] get [-p ]... [-o ] insert (-r )... [-p ]... [-o ] diff --git a/gen/sqladmin1_beta4-cli/mkdocs.yml b/gen/sqladmin1_beta4-cli/mkdocs.yml index e2d6ce7afc..b9a3db07bf 100644 --- a/gen/sqladmin1_beta4-cli/mkdocs.yml +++ b/gen/sqladmin1_beta4-cli/mkdocs.yml @@ -1,4 +1,4 @@ -site_name: SQL Admin v0.3.2+20150305 +site_name: SQL Admin v0.3.2+20151013 site_url: http://byron.github.io/google-apis-rs/google-sqladmin1_beta4-cli site_description: Write integrating applications with bcore @@ -9,6 +9,7 @@ site_dir: build_html pages: - ['index.md', 'Home'] +- ['backup-runs_delete.md', 'Backup Runs', 'Delete'] - ['backup-runs_get.md', 'Backup Runs', 'Get'] - ['backup-runs_list.md', 'Backup Runs', 'List'] - ['databases_delete.md', 'Databases', 'Delete'] @@ -21,6 +22,7 @@ pages: - ['instances_clone.md', 'Instances', 'Clone'] - ['instances_delete.md', 'Instances', 'Delete'] - ['instances_export.md', 'Instances', 'Export'] +- ['instances_failover.md', 'Instances', 'Failover'] - ['instances_get.md', 'Instances', 'Get'] - ['instances_import.md', 'Instances', 'Import'] - ['instances_insert.md', 'Instances', 'Insert'] @@ -35,6 +37,7 @@ pages: - ['instances_update.md', 'Instances', 'Update'] - ['operations_get.md', 'Operations', 'Get'] - ['operations_list.md', 'Operations', 'List'] +- ['ssl-certs_create-ephemeral.md', 'Ssl Certs', 'Create Ephemeral'] - ['ssl-certs_delete.md', 'Ssl Certs', 'Delete'] - ['ssl-certs_get.md', 'Ssl Certs', 'Get'] - ['ssl-certs_insert.md', 'Ssl Certs', 'Insert'] diff --git a/gen/sqladmin1_beta4-cli/src/main.rs b/gen/sqladmin1_beta4-cli/src/main.rs index 5a9622741a..d3d29440e6 100644 --- a/gen/sqladmin1_beta4-cli/src/main.rs +++ b/gen/sqladmin1_beta4-cli/src/main.rs @@ -45,6 +45,58 @@ struct Engine<'n, 'a> { impl<'n, 'a> Engine<'n, 'a> { + fn _backup_runs_delete(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.backup_runs().delete(opt.value_of("project").unwrap_or(""), opt.value_of("instance").unwrap_or(""), opt.value_of("id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + fn _backup_runs_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) -> Result<(), DoitError> { let mut call = self.hub.backup_runs().get(opt.value_of("project").unwrap_or(""), opt.value_of("instance").unwrap_or(""), opt.value_of("id").unwrap_or("")); @@ -810,8 +862,9 @@ impl<'n, 'a> Engine<'n, 'a> { "export-context.csv-export-options.select-query" => Some(("exportContext.csvExportOptions.selectQuery", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "export-context.databases" => Some(("exportContext.databases", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), "export-context.sql-export-options.tables" => Some(("exportContext.sqlExportOptions.tables", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "export-context.sql-export-options.schema-only" => Some(("exportContext.sqlExportOptions.schemaOnly", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), _ => { - let suggestion = FieldCursor::did_you_mean(key, &vec!["csv-export-options", "databases", "export-context", "file-type", "kind", "select-query", "sql-export-options", "tables", "uri"]); + let suggestion = FieldCursor::did_you_mean(key, &vec!["csv-export-options", "databases", "export-context", "file-type", "kind", "schema-only", "select-query", "sql-export-options", "tables", "uri"]); err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); None } @@ -871,6 +924,92 @@ impl<'n, 'a> Engine<'n, 'a> { } } + fn _instances_failover(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "failover-context.kind" => Some(("failoverContext.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "failover-context.settings-version" => Some(("failoverContext.settingsVersion", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["failover-context", "kind", "settings-version"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::InstancesFailoverRequest = json::value::from_value(object).unwrap(); + let mut call = self.hub.instances().failover(request, opt.value_of("project").unwrap_or(""), opt.value_of("instance").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + fn _instances_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) -> Result<(), DoitError> { let mut call = self.hub.instances().get(opt.value_of("project").unwrap_or(""), opt.value_of("instance").unwrap_or("")); @@ -1071,12 +1210,14 @@ impl<'n, 'a> Engine<'n, 'a> { "settings.location-preference.kind" => Some(("settings.locationPreference.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "settings.location-preference.zone" => Some(("settings.locationPreference.zone", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "settings.location-preference.follow-gae-application" => Some(("settings.locationPreference.followGaeApplication", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "settings.data-disk-size-gb" => Some(("settings.dataDiskSizeGb", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "master-instance-name" => Some(("masterInstanceName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "current-disk-size" => Some(("currentDiskSize", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "state" => Some(("state", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "etag" => Some(("etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "service-account-email-address" => Some(("serviceAccountEmailAddress", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "replica-configuration.kind" => Some(("replicaConfiguration.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "replica-configuration.failover-target" => Some(("replicaConfiguration.failoverTarget", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), "replica-configuration.mysql-replica-configuration.username" => Some(("replicaConfiguration.mysqlReplicaConfiguration.username", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "replica-configuration.mysql-replica-configuration.kind" => Some(("replicaConfiguration.mysqlReplicaConfiguration.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "replica-configuration.mysql-replica-configuration.connect-retry-interval" => Some(("replicaConfiguration.mysqlReplicaConfiguration.connectRetryInterval", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), @@ -1093,7 +1234,7 @@ impl<'n, 'a> Engine<'n, 'a> { "self-link" => Some(("selfLink", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), _ => { - let suggestion = FieldCursor::did_you_mean(key, &vec!["activation-policy", "authorized-gae-applications", "backup-configuration", "binary-log-enabled", "ca-certificate", "cert", "cert-serial-number", "client-certificate", "client-key", "common-name", "connect-retry-interval", "crash-safe-replication-enabled", "create-time", "current-disk-size", "database-replication-enabled", "database-version", "dump-file-path", "enabled", "etag", "expiration-time", "follow-gae-application", "host-port", "instance", "instance-type", "ip-configuration", "ipv4-enabled", "ipv6-address", "kind", "location-preference", "master-heartbeat-period", "master-instance-name", "max-disk-size", "mysql-replica-configuration", "name", "on-premises-configuration", "password", "pricing-plan", "project", "region", "replica-configuration", "replica-names", "replication-type", "require-ssl", "self-link", "server-ca-cert", "service-account-email-address", "settings", "settings-version", "sha1-fingerprint", "ssl-cipher", "start-time", "state", "tier", "username", "verify-server-certificate", "zone"]); + let suggestion = FieldCursor::did_you_mean(key, &vec!["activation-policy", "authorized-gae-applications", "backup-configuration", "binary-log-enabled", "ca-certificate", "cert", "cert-serial-number", "client-certificate", "client-key", "common-name", "connect-retry-interval", "crash-safe-replication-enabled", "create-time", "current-disk-size", "data-disk-size-gb", "database-replication-enabled", "database-version", "dump-file-path", "enabled", "etag", "expiration-time", "failover-target", "follow-gae-application", "host-port", "instance", "instance-type", "ip-configuration", "ipv4-enabled", "ipv6-address", "kind", "location-preference", "master-heartbeat-period", "master-instance-name", "max-disk-size", "mysql-replica-configuration", "name", "on-premises-configuration", "password", "pricing-plan", "project", "region", "replica-configuration", "replica-names", "replication-type", "require-ssl", "self-link", "server-ca-cert", "service-account-email-address", "settings", "settings-version", "sha1-fingerprint", "ssl-cipher", "start-time", "state", "tier", "username", "verify-server-certificate", "zone"]); err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); None } @@ -1270,12 +1411,14 @@ impl<'n, 'a> Engine<'n, 'a> { "settings.location-preference.kind" => Some(("settings.locationPreference.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "settings.location-preference.zone" => Some(("settings.locationPreference.zone", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "settings.location-preference.follow-gae-application" => Some(("settings.locationPreference.followGaeApplication", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "settings.data-disk-size-gb" => Some(("settings.dataDiskSizeGb", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "master-instance-name" => Some(("masterInstanceName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "current-disk-size" => Some(("currentDiskSize", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "state" => Some(("state", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "etag" => Some(("etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "service-account-email-address" => Some(("serviceAccountEmailAddress", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "replica-configuration.kind" => Some(("replicaConfiguration.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "replica-configuration.failover-target" => Some(("replicaConfiguration.failoverTarget", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), "replica-configuration.mysql-replica-configuration.username" => Some(("replicaConfiguration.mysqlReplicaConfiguration.username", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "replica-configuration.mysql-replica-configuration.kind" => Some(("replicaConfiguration.mysqlReplicaConfiguration.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "replica-configuration.mysql-replica-configuration.connect-retry-interval" => Some(("replicaConfiguration.mysqlReplicaConfiguration.connectRetryInterval", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), @@ -1292,7 +1435,7 @@ impl<'n, 'a> Engine<'n, 'a> { "self-link" => Some(("selfLink", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), _ => { - let suggestion = FieldCursor::did_you_mean(key, &vec!["activation-policy", "authorized-gae-applications", "backup-configuration", "binary-log-enabled", "ca-certificate", "cert", "cert-serial-number", "client-certificate", "client-key", "common-name", "connect-retry-interval", "crash-safe-replication-enabled", "create-time", "current-disk-size", "database-replication-enabled", "database-version", "dump-file-path", "enabled", "etag", "expiration-time", "follow-gae-application", "host-port", "instance", "instance-type", "ip-configuration", "ipv4-enabled", "ipv6-address", "kind", "location-preference", "master-heartbeat-period", "master-instance-name", "max-disk-size", "mysql-replica-configuration", "name", "on-premises-configuration", "password", "pricing-plan", "project", "region", "replica-configuration", "replica-names", "replication-type", "require-ssl", "self-link", "server-ca-cert", "service-account-email-address", "settings", "settings-version", "sha1-fingerprint", "ssl-cipher", "start-time", "state", "tier", "username", "verify-server-certificate", "zone"]); + let suggestion = FieldCursor::did_you_mean(key, &vec!["activation-policy", "authorized-gae-applications", "backup-configuration", "binary-log-enabled", "ca-certificate", "cert", "cert-serial-number", "client-certificate", "client-key", "common-name", "connect-retry-interval", "crash-safe-replication-enabled", "create-time", "current-disk-size", "data-disk-size-gb", "database-replication-enabled", "database-version", "dump-file-path", "enabled", "etag", "expiration-time", "failover-target", "follow-gae-application", "host-port", "instance", "instance-type", "ip-configuration", "ipv4-enabled", "ipv6-address", "kind", "location-preference", "master-heartbeat-period", "master-instance-name", "max-disk-size", "mysql-replica-configuration", "name", "on-premises-configuration", "password", "pricing-plan", "project", "region", "replica-configuration", "replica-names", "replication-type", "require-ssl", "self-link", "server-ca-cert", "service-account-email-address", "settings", "settings-version", "sha1-fingerprint", "ssl-cipher", "start-time", "state", "tier", "username", "verify-server-certificate", "zone"]); err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); None } @@ -1757,12 +1900,14 @@ impl<'n, 'a> Engine<'n, 'a> { "settings.location-preference.kind" => Some(("settings.locationPreference.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "settings.location-preference.zone" => Some(("settings.locationPreference.zone", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "settings.location-preference.follow-gae-application" => Some(("settings.locationPreference.followGaeApplication", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "settings.data-disk-size-gb" => Some(("settings.dataDiskSizeGb", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "master-instance-name" => Some(("masterInstanceName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "current-disk-size" => Some(("currentDiskSize", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "state" => Some(("state", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "etag" => Some(("etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "service-account-email-address" => Some(("serviceAccountEmailAddress", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "replica-configuration.kind" => Some(("replicaConfiguration.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "replica-configuration.failover-target" => Some(("replicaConfiguration.failoverTarget", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), "replica-configuration.mysql-replica-configuration.username" => Some(("replicaConfiguration.mysqlReplicaConfiguration.username", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "replica-configuration.mysql-replica-configuration.kind" => Some(("replicaConfiguration.mysqlReplicaConfiguration.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "replica-configuration.mysql-replica-configuration.connect-retry-interval" => Some(("replicaConfiguration.mysqlReplicaConfiguration.connectRetryInterval", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), @@ -1779,7 +1924,7 @@ impl<'n, 'a> Engine<'n, 'a> { "self-link" => Some(("selfLink", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), _ => { - let suggestion = FieldCursor::did_you_mean(key, &vec!["activation-policy", "authorized-gae-applications", "backup-configuration", "binary-log-enabled", "ca-certificate", "cert", "cert-serial-number", "client-certificate", "client-key", "common-name", "connect-retry-interval", "crash-safe-replication-enabled", "create-time", "current-disk-size", "database-replication-enabled", "database-version", "dump-file-path", "enabled", "etag", "expiration-time", "follow-gae-application", "host-port", "instance", "instance-type", "ip-configuration", "ipv4-enabled", "ipv6-address", "kind", "location-preference", "master-heartbeat-period", "master-instance-name", "max-disk-size", "mysql-replica-configuration", "name", "on-premises-configuration", "password", "pricing-plan", "project", "region", "replica-configuration", "replica-names", "replication-type", "require-ssl", "self-link", "server-ca-cert", "service-account-email-address", "settings", "settings-version", "sha1-fingerprint", "ssl-cipher", "start-time", "state", "tier", "username", "verify-server-certificate", "zone"]); + let suggestion = FieldCursor::did_you_mean(key, &vec!["activation-policy", "authorized-gae-applications", "backup-configuration", "binary-log-enabled", "ca-certificate", "cert", "cert-serial-number", "client-certificate", "client-key", "common-name", "connect-retry-interval", "crash-safe-replication-enabled", "create-time", "current-disk-size", "data-disk-size-gb", "database-replication-enabled", "database-version", "dump-file-path", "enabled", "etag", "expiration-time", "failover-target", "follow-gae-application", "host-port", "instance", "instance-type", "ip-configuration", "ipv4-enabled", "ipv6-address", "kind", "location-preference", "master-heartbeat-period", "master-instance-name", "max-disk-size", "mysql-replica-configuration", "name", "on-premises-configuration", "password", "pricing-plan", "project", "region", "replica-configuration", "replica-names", "replication-type", "require-ssl", "self-link", "server-ca-cert", "service-account-email-address", "settings", "settings-version", "sha1-fingerprint", "ssl-cipher", "start-time", "state", "tier", "username", "verify-server-certificate", "zone"]); err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); None } @@ -1950,6 +2095,91 @@ impl<'n, 'a> Engine<'n, 'a> { } } + fn _ssl_certs_create_ephemeral(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "public-key" => Some(("public_key", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["public-key"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::SslCertsCreateEphemeralRequest = json::value::from_value(object).unwrap(); + let mut call = self.hub.ssl_certs().create_ephemeral(request, opt.value_of("project").unwrap_or(""), opt.value_of("instance").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + fn _ssl_certs_delete(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) -> Result<(), DoitError> { let mut call = self.hub.ssl_certs().delete(opt.value_of("project").unwrap_or(""), opt.value_of("instance").unwrap_or(""), opt.value_of("sha1-fingerprint").unwrap_or("")); @@ -2536,6 +2766,9 @@ impl<'n, 'a> Engine<'n, 'a> { match self.opt.subcommand() { ("backup-runs", Some(opt)) => { match opt.subcommand() { + ("delete", Some(opt)) => { + call_result = self._backup_runs_delete(opt, dry_run, &mut err); + }, ("get", Some(opt)) => { call_result = self._backup_runs_get(opt, dry_run, &mut err); }, @@ -2596,6 +2829,9 @@ impl<'n, 'a> Engine<'n, 'a> { ("export", Some(opt)) => { call_result = self._instances_export(opt, dry_run, &mut err); }, + ("failover", Some(opt)) => { + call_result = self._instances_failover(opt, dry_run, &mut err); + }, ("get", Some(opt)) => { call_result = self._instances_get(opt, dry_run, &mut err); }, @@ -2654,6 +2890,9 @@ impl<'n, 'a> Engine<'n, 'a> { }, ("ssl-certs", Some(opt)) => { match opt.subcommand() { + ("create-ephemeral", Some(opt)) => { + call_result = self._ssl_certs_create_ephemeral(opt, dry_run, &mut err); + }, ("delete", Some(opt)) => { call_result = self._ssl_certs_delete(opt, dry_run, &mut err); }, @@ -2785,7 +3024,41 @@ impl<'n, 'a> Engine<'n, 'a> { fn main() { let mut exit_status = 0i32; let arg_data = [ - ("backup-runs", "methods: 'get' and 'list'", vec![ + ("backup-runs", "methods: 'delete', 'get' and 'list'", vec![ + ("delete", + Some(r##"Deletes the backup taken by a backup run."##), + "Details at http://byron.github.io/google-apis-rs/google_sqladmin1_beta4_cli/backup-runs_delete", + vec![ + (Some(r##"project"##), + None, + Some(r##"Project ID of the project that contains the instance."##), + Some(true), + Some(false)), + + (Some(r##"instance"##), + None, + Some(r##"Cloud SQL instance ID. This does not include the project ID."##), + Some(true), + Some(false)), + + (Some(r##"id"##), + None, + Some(r##"The ID of the Backup Run to delete. To find a Backup Run ID, use the list method."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), ("get", Some(r##"Retrieves a resource containing information about a backup run."##), "Details at http://byron.github.io/google-apis-rs/google_sqladmin1_beta4_cli/backup-runs_get", @@ -3082,7 +3355,7 @@ fn main() { ]), ]), - ("instances", "methods: 'clone', 'delete', 'export', 'get', 'import', 'insert', 'list', 'patch', 'promote-replica', 'reset-ssl-config', 'restart', 'restore-backup', 'start-replica', 'stop-replica' and 'update'", vec![ + ("instances", "methods: 'clone', 'delete', 'export', 'failover', 'get', 'import', 'insert', 'list', 'patch', 'promote-replica', 'reset-ssl-config', 'restart', 'restore-backup', 'start-replica', 'stop-replica' and 'update'", vec![ ("clone", Some(r##"Creates a Cloud SQL instance as a clone of the source instance."##), "Details at http://byron.github.io/google-apis-rs/google_sqladmin1_beta4_cli/instances_clone", @@ -3173,6 +3446,40 @@ fn main() { Some(false), Some(true)), + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("failover", + Some(r##"Failover the instance to its failover replica instance."##), + "Details at http://byron.github.io/google-apis-rs/google_sqladmin1_beta4_cli/instances_failover", + vec![ + (Some(r##"project"##), + None, + Some(r##"ID of the project that contains the read replica."##), + Some(true), + Some(false)), + + (Some(r##"instance"##), + None, + Some(r##"Cloud SQL instance ID. This does not include the project ID."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + (Some(r##"out"##), Some(r##"o"##), Some(r##"Specify the file into which to write the program's output"##), @@ -3594,7 +3901,41 @@ fn main() { ]), ]), - ("ssl-certs", "methods: 'delete', 'get', 'insert' and 'list'", vec![ + ("ssl-certs", "methods: 'create-ephemeral', 'delete', 'get', 'insert' and 'list'", vec![ + ("create-ephemeral", + Some(r##"Generates a short-lived X509 certificate containing the provided public key and signed by a private key specific to the target instance. Users may use the certificate to authenticate as themselves when connecting to the database."##), + "Details at http://byron.github.io/google-apis-rs/google_sqladmin1_beta4_cli/ssl-certs_create-ephemeral", + vec![ + (Some(r##"project"##), + None, + Some(r##"Project ID of the Cloud SQL project."##), + Some(true), + Some(false)), + + (Some(r##"instance"##), + None, + Some(r##"Cloud SQL instance ID. This does not include the project ID."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), ("delete", Some(r##"Deletes the SSL certificate. The change will not take effect until the instance is restarted."##), "Details at http://byron.github.io/google-apis-rs/google_sqladmin1_beta4_cli/ssl-certs_delete", @@ -3907,7 +4248,7 @@ fn main() { let mut app = App::new("sqladmin1-beta4") .author("Sebastian Thiel ") - .version("0.3.2+20150305") + .version("0.3.2+20151013") .about("API for Cloud SQL database instance management.") .after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_sqladmin1_beta4_cli") .arg(Arg::with_name("url") diff --git a/gen/sqladmin1_beta4/Cargo.toml b/gen/sqladmin1_beta4/Cargo.toml index c353f42ced..278fc262ea 100644 --- a/gen/sqladmin1_beta4/Cargo.toml +++ b/gen/sqladmin1_beta4/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-sqladmin1_beta4" -version = "0.1.9+20150305" +version = "0.1.9+20151013" authors = ["Sebastian Thiel "] description = "A complete library to interact with SQL Admin (protocol v1beta4)" repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/sqladmin1_beta4" diff --git a/gen/sqladmin1_beta4/README.md b/gen/sqladmin1_beta4/README.md index 3f59cca010..e08489462f 100644 --- a/gen/sqladmin1_beta4/README.md +++ b/gen/sqladmin1_beta4/README.md @@ -5,7 +5,7 @@ DO NOT EDIT ! --> The `google-sqladmin1_beta4` library allows access to all features of the *Google SQL Admin* service. -This documentation was generated from *SQL Admin* crate version *0.1.9+20150305*, where *20150305* is the exact revision of the *sqladmin:v1beta4* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +This documentation was generated from *SQL Admin* crate version *0.1.9+20151013*, where *20151013* is the exact revision of the *sqladmin:v1beta4* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. Everything else about the *SQL Admin* *v1_beta4* API can be found at the [official documentation site](https://cloud.google.com/sql/docs/reference/latest). @@ -14,17 +14,17 @@ Everything else about the *SQL Admin* *v1_beta4* API can be found at the Handle the following *Resources* with ease from the central [hub](http://byron.github.io/google-apis-rs/google_sqladmin1_beta4/struct.SQLAdmin.html) ... * [backup runs](http://byron.github.io/google-apis-rs/google_sqladmin1_beta4/struct.BackupRun.html) - * [*get*](http://byron.github.io/google-apis-rs/google_sqladmin1_beta4/struct.BackupRunGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google_sqladmin1_beta4/struct.BackupRunListCall.html) + * [*delete*](http://byron.github.io/google-apis-rs/google_sqladmin1_beta4/struct.BackupRunDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google_sqladmin1_beta4/struct.BackupRunGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google_sqladmin1_beta4/struct.BackupRunListCall.html) * [databases](http://byron.github.io/google-apis-rs/google_sqladmin1_beta4/struct.Database.html) * [*delete*](http://byron.github.io/google-apis-rs/google_sqladmin1_beta4/struct.DatabaseDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google_sqladmin1_beta4/struct.DatabaseGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google_sqladmin1_beta4/struct.DatabaseInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google_sqladmin1_beta4/struct.DatabaseListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google_sqladmin1_beta4/struct.DatabasePatchCall.html) and [*update*](http://byron.github.io/google-apis-rs/google_sqladmin1_beta4/struct.DatabaseUpdateCall.html) * [flags](http://byron.github.io/google-apis-rs/google_sqladmin1_beta4/struct.Flag.html) * [*list*](http://byron.github.io/google-apis-rs/google_sqladmin1_beta4/struct.FlagListCall.html) * instances - * [*clone*](http://byron.github.io/google-apis-rs/google_sqladmin1_beta4/struct.InstanceCloneCall.html), [*delete*](http://byron.github.io/google-apis-rs/google_sqladmin1_beta4/struct.InstanceDeleteCall.html), [*export*](http://byron.github.io/google-apis-rs/google_sqladmin1_beta4/struct.InstanceExportCall.html), [*get*](http://byron.github.io/google-apis-rs/google_sqladmin1_beta4/struct.InstanceGetCall.html), [*import*](http://byron.github.io/google-apis-rs/google_sqladmin1_beta4/struct.InstanceImportCall.html), [*insert*](http://byron.github.io/google-apis-rs/google_sqladmin1_beta4/struct.InstanceInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google_sqladmin1_beta4/struct.InstanceListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google_sqladmin1_beta4/struct.InstancePatchCall.html), [*promote replica*](http://byron.github.io/google-apis-rs/google_sqladmin1_beta4/struct.InstancePromoteReplicaCall.html), [*reset ssl config*](http://byron.github.io/google-apis-rs/google_sqladmin1_beta4/struct.InstanceResetSslConfigCall.html), [*restart*](http://byron.github.io/google-apis-rs/google_sqladmin1_beta4/struct.InstanceRestartCall.html), [*restore backup*](http://byron.github.io/google-apis-rs/google_sqladmin1_beta4/struct.InstanceRestoreBackupCall.html), [*start replica*](http://byron.github.io/google-apis-rs/google_sqladmin1_beta4/struct.InstanceStartReplicaCall.html), [*stop replica*](http://byron.github.io/google-apis-rs/google_sqladmin1_beta4/struct.InstanceStopReplicaCall.html) and [*update*](http://byron.github.io/google-apis-rs/google_sqladmin1_beta4/struct.InstanceUpdateCall.html) + * [*clone*](http://byron.github.io/google-apis-rs/google_sqladmin1_beta4/struct.InstanceCloneCall.html), [*delete*](http://byron.github.io/google-apis-rs/google_sqladmin1_beta4/struct.InstanceDeleteCall.html), [*export*](http://byron.github.io/google-apis-rs/google_sqladmin1_beta4/struct.InstanceExportCall.html), [*failover*](http://byron.github.io/google-apis-rs/google_sqladmin1_beta4/struct.InstanceFailoverCall.html), [*get*](http://byron.github.io/google-apis-rs/google_sqladmin1_beta4/struct.InstanceGetCall.html), [*import*](http://byron.github.io/google-apis-rs/google_sqladmin1_beta4/struct.InstanceImportCall.html), [*insert*](http://byron.github.io/google-apis-rs/google_sqladmin1_beta4/struct.InstanceInsertCall.html), [*list*](http://byron.github.io/google-apis-rs/google_sqladmin1_beta4/struct.InstanceListCall.html), [*patch*](http://byron.github.io/google-apis-rs/google_sqladmin1_beta4/struct.InstancePatchCall.html), [*promote replica*](http://byron.github.io/google-apis-rs/google_sqladmin1_beta4/struct.InstancePromoteReplicaCall.html), [*reset ssl config*](http://byron.github.io/google-apis-rs/google_sqladmin1_beta4/struct.InstanceResetSslConfigCall.html), [*restart*](http://byron.github.io/google-apis-rs/google_sqladmin1_beta4/struct.InstanceRestartCall.html), [*restore backup*](http://byron.github.io/google-apis-rs/google_sqladmin1_beta4/struct.InstanceRestoreBackupCall.html), [*start replica*](http://byron.github.io/google-apis-rs/google_sqladmin1_beta4/struct.InstanceStartReplicaCall.html), [*stop replica*](http://byron.github.io/google-apis-rs/google_sqladmin1_beta4/struct.InstanceStopReplicaCall.html) and [*update*](http://byron.github.io/google-apis-rs/google_sqladmin1_beta4/struct.InstanceUpdateCall.html) * [operations](http://byron.github.io/google-apis-rs/google_sqladmin1_beta4/struct.Operation.html) * [*get*](http://byron.github.io/google-apis-rs/google_sqladmin1_beta4/struct.OperationGetCall.html) and [*list*](http://byron.github.io/google-apis-rs/google_sqladmin1_beta4/struct.OperationListCall.html) * [ssl certs](http://byron.github.io/google-apis-rs/google_sqladmin1_beta4/struct.SslCert.html) - * [*delete*](http://byron.github.io/google-apis-rs/google_sqladmin1_beta4/struct.SslCertDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google_sqladmin1_beta4/struct.SslCertGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google_sqladmin1_beta4/struct.SslCertInsertCall.html) and [*list*](http://byron.github.io/google-apis-rs/google_sqladmin1_beta4/struct.SslCertListCall.html) + * [*create ephemeral*](http://byron.github.io/google-apis-rs/google_sqladmin1_beta4/struct.SslCertCreateEphemeralCall.html), [*delete*](http://byron.github.io/google-apis-rs/google_sqladmin1_beta4/struct.SslCertDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google_sqladmin1_beta4/struct.SslCertGetCall.html), [*insert*](http://byron.github.io/google-apis-rs/google_sqladmin1_beta4/struct.SslCertInsertCall.html) and [*list*](http://byron.github.io/google-apis-rs/google_sqladmin1_beta4/struct.SslCertListCall.html) * [tiers](http://byron.github.io/google-apis-rs/google_sqladmin1_beta4/struct.Tier.html) * [*list*](http://byron.github.io/google-apis-rs/google_sqladmin1_beta4/struct.TierListCall.html) * [users](http://byron.github.io/google-apis-rs/google_sqladmin1_beta4/struct.User.html) @@ -64,6 +64,7 @@ Or specifically ... let r = hub.ssl_certs().delete(...).doit() let r = hub.users().delete(...).doit() let r = hub.databases().delete(...).doit() +let r = hub.instances().failover(...).doit() let r = hub.databases().patch(...).doit() let r = hub.instances().reset_ssl_config(...).doit() let r = hub.instances().promote_replica(...).doit() @@ -71,6 +72,7 @@ let r = hub.databases().update(...).doit() let r = hub.operations().list(...).doit() let r = hub.users().update(...).doit() let r = hub.databases().insert(...).doit() +let r = hub.backup_runs().delete(...).doit() let r = hub.instances().patch(...).doit() let r = hub.instances().clone(...).doit() let r = hub.instances().delete(...).doit() diff --git a/gen/sqladmin1_beta4/src/lib.rs b/gen/sqladmin1_beta4/src/lib.rs index 36efafeb3f..b8a6148d28 100644 --- a/gen/sqladmin1_beta4/src/lib.rs +++ b/gen/sqladmin1_beta4/src/lib.rs @@ -2,7 +2,7 @@ // This file was generated automatically from 'src/mako/api/lib.rs.mako' // DO NOT EDIT ! -//! This documentation was generated from *SQL Admin* crate version *0.1.9+20150305*, where *20150305* is the exact revision of the *sqladmin:v1beta4* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +//! This documentation was generated from *SQL Admin* crate version *0.1.9+20151013*, where *20151013* is the exact revision of the *sqladmin:v1beta4* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. //! //! Everything else about the *SQL Admin* *v1_beta4* API can be found at the //! [official documentation site](https://cloud.google.com/sql/docs/reference/latest). @@ -12,17 +12,17 @@ //! Handle the following *Resources* with ease from the central [hub](struct.SQLAdmin.html) ... //! //! * [backup runs](struct.BackupRun.html) -//! * [*get*](struct.BackupRunGetCall.html) and [*list*](struct.BackupRunListCall.html) +//! * [*delete*](struct.BackupRunDeleteCall.html), [*get*](struct.BackupRunGetCall.html) and [*list*](struct.BackupRunListCall.html) //! * [databases](struct.Database.html) //! * [*delete*](struct.DatabaseDeleteCall.html), [*get*](struct.DatabaseGetCall.html), [*insert*](struct.DatabaseInsertCall.html), [*list*](struct.DatabaseListCall.html), [*patch*](struct.DatabasePatchCall.html) and [*update*](struct.DatabaseUpdateCall.html) //! * [flags](struct.Flag.html) //! * [*list*](struct.FlagListCall.html) //! * instances -//! * [*clone*](struct.InstanceCloneCall.html), [*delete*](struct.InstanceDeleteCall.html), [*export*](struct.InstanceExportCall.html), [*get*](struct.InstanceGetCall.html), [*import*](struct.InstanceImportCall.html), [*insert*](struct.InstanceInsertCall.html), [*list*](struct.InstanceListCall.html), [*patch*](struct.InstancePatchCall.html), [*promote replica*](struct.InstancePromoteReplicaCall.html), [*reset ssl config*](struct.InstanceResetSslConfigCall.html), [*restart*](struct.InstanceRestartCall.html), [*restore backup*](struct.InstanceRestoreBackupCall.html), [*start replica*](struct.InstanceStartReplicaCall.html), [*stop replica*](struct.InstanceStopReplicaCall.html) and [*update*](struct.InstanceUpdateCall.html) +//! * [*clone*](struct.InstanceCloneCall.html), [*delete*](struct.InstanceDeleteCall.html), [*export*](struct.InstanceExportCall.html), [*failover*](struct.InstanceFailoverCall.html), [*get*](struct.InstanceGetCall.html), [*import*](struct.InstanceImportCall.html), [*insert*](struct.InstanceInsertCall.html), [*list*](struct.InstanceListCall.html), [*patch*](struct.InstancePatchCall.html), [*promote replica*](struct.InstancePromoteReplicaCall.html), [*reset ssl config*](struct.InstanceResetSslConfigCall.html), [*restart*](struct.InstanceRestartCall.html), [*restore backup*](struct.InstanceRestoreBackupCall.html), [*start replica*](struct.InstanceStartReplicaCall.html), [*stop replica*](struct.InstanceStopReplicaCall.html) and [*update*](struct.InstanceUpdateCall.html) //! * [operations](struct.Operation.html) //! * [*get*](struct.OperationGetCall.html) and [*list*](struct.OperationListCall.html) //! * [ssl certs](struct.SslCert.html) -//! * [*delete*](struct.SslCertDeleteCall.html), [*get*](struct.SslCertGetCall.html), [*insert*](struct.SslCertInsertCall.html) and [*list*](struct.SslCertListCall.html) +//! * [*create ephemeral*](struct.SslCertCreateEphemeralCall.html), [*delete*](struct.SslCertDeleteCall.html), [*get*](struct.SslCertGetCall.html), [*insert*](struct.SslCertInsertCall.html) and [*list*](struct.SslCertListCall.html) //! * [tiers](struct.Tier.html) //! * [*list*](struct.TierListCall.html) //! * [users](struct.User.html) @@ -64,6 +64,7 @@ //! let r = hub.ssl_certs().delete(...).doit() //! let r = hub.users().delete(...).doit() //! let r = hub.databases().delete(...).doit() +//! let r = hub.instances().failover(...).doit() //! let r = hub.databases().patch(...).doit() //! let r = hub.instances().reset_ssl_config(...).doit() //! let r = hub.instances().promote_replica(...).doit() @@ -71,6 +72,7 @@ //! let r = hub.operations().list(...).doit() //! let r = hub.users().update(...).doit() //! let r = hub.databases().insert(...).doit() +//! let r = hub.backup_runs().delete(...).doit() //! let r = hub.instances().patch(...).doit() //! let r = hub.instances().clone(...).doit() //! let r = hub.instances().delete(...).doit() diff --git a/gen/sqladmin1_beta4/src/lib.rs.in b/gen/sqladmin1_beta4/src/lib.rs.in index e07dae79b0..c1afb7044a 100644 --- a/gen/sqladmin1_beta4/src/lib.rs.in +++ b/gen/sqladmin1_beta4/src/lib.rs.in @@ -202,6 +202,7 @@ impl Part for OperationErrors {} /// This type is used in activities, which are methods you may call on this type or where 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 backup runs](struct.BackupRunDeleteCall.html) (none) /// * [get backup runs](struct.BackupRunGetCall.html) (response) /// * [list backup runs](struct.BackupRunListCall.html) (none) /// @@ -265,6 +266,7 @@ impl Part for SslCertDetail {} /// * [insert ssl certs](struct.SslCertInsertCall.html) (none) /// * [get ssl certs](struct.SslCertGetCall.html) (response) /// * [list ssl certs](struct.SslCertListCall.html) (none) +/// * [create ephemeral ssl certs](struct.SslCertCreateEphemeralCall.html) (response) /// * [delete ssl certs](struct.SslCertDeleteCall.html) (none) /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] @@ -381,6 +383,10 @@ impl RequestValue for InstancesCloneRequest {} pub struct ReplicaConfiguration { /// This is always sql#replicaConfiguration. pub kind: Option, + /// Specifies if the replica is the failover target. If the field is set to true the replica will be designated as a failover replica. In case the master instance fails, the replica instance will be promoted as the new master instance. + /// Only one replica can be specified as failover target, and the replica has to be in different zone with the master instance. + #[serde(rename="failoverTarget")] + pub failover_target: Option, /// MySQL specific configuration when replicating from a MySQL on-premises master. Replication configuration information such as the username, password, certificates, and keys are not stored in the instance metadata. The configuration information is used only to set up the replication connection and is stored by MySQL in a file named master.info in the data directory. #[serde(rename="mysqlReplicaConfiguration")] pub mysql_replica_configuration: Option, @@ -660,7 +666,7 @@ pub struct Flag { /// For STRING flags, a list of strings that the value can be set to. #[serde(rename="allowedStringValues")] pub allowed_string_values: Option>, - /// The database version this flag applies to. Currently this can only be [MYSQL_5_5]. + /// The database version this flag applies to. Can be MYSQL_5_5, MYSQL_5_6, or both. #[serde(rename="appliesTo")] pub applies_to: Option>, /// The type of the flag. Flags are typed to being BOOLEAN, STRING, INTEGER or NONE. NONE is used for flags which do not take a value, such as skip_grant_tables. @@ -899,11 +905,33 @@ pub struct Settings { /// The location preference settings. This allows the instance to be located as near as possible to either an App Engine app or GCE zone for better performance. #[serde(rename="locationPreference")] pub location_preference: Option, + /// The size of data disk for the performance instance, specified in GB. Setting this value for non-performance instances will result in an error. + #[serde(rename="dataDiskSizeGb")] + pub data_disk_size_gb: Option, } impl Part for Settings {} +/// Instance failover 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*). +/// +/// * [failover instances](struct.InstanceFailoverCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct InstancesFailoverRequest { + /// Failover Context. + #[serde(rename="failoverContext")] + pub failover_context: Option, +} + +impl RequestValue for InstancesFailoverRequest {} + + /// SslCerts insert request. /// /// # Activities @@ -963,6 +991,24 @@ pub struct AclEntry { impl Part for AclEntry {} +/// SslCerts create ephemeral certificate 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*). +/// +/// * [create ephemeral ssl certs](struct.SslCertCreateEphemeralCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct SslCertsCreateEphemeralRequest { + /// PEM encoded public key to include in the signed certificate. + pub public_key: Option, +} + +impl RequestValue for SslCertsCreateEphemeralRequest {} + + /// Database instances list response. /// /// # Activities @@ -1129,6 +1175,22 @@ pub struct InstancesImportRequest { impl RequestValue for InstancesImportRequest {} +/// Database instance failover context. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct FailoverContext { + /// This is always sql#failoverContext. + pub kind: Option, + /// The current settings version of this instance. Request will be rejected if this version doesn't match the current settings version. + #[serde(rename="settingsVersion")] + pub settings_version: Option, +} + +impl Part for FailoverContext {} + + /// Database list response. /// /// # Activities @@ -1178,6 +1240,7 @@ impl Part for BinLogCoordinates {} /// * [delete ssl certs](struct.SslCertDeleteCall.html) (response) /// * [delete users](struct.UserDeleteCall.html) (response) /// * [delete databases](struct.DatabaseDeleteCall.html) (response) +/// * [failover instances](struct.InstanceFailoverCall.html) (response) /// * [patch databases](struct.DatabasePatchCall.html) (response) /// * [reset ssl config instances](struct.InstanceResetSslConfigCall.html) (response) /// * [promote replica instances](struct.InstancePromoteReplicaCall.html) (response) @@ -1185,6 +1248,7 @@ impl Part for BinLogCoordinates {} /// * [list operations](struct.OperationListCall.html) (none) /// * [update users](struct.UserUpdateCall.html) (response) /// * [insert databases](struct.DatabaseInsertCall.html) (response) +/// * [delete backup runs](struct.BackupRunDeleteCall.html) (response) /// * [patch instances](struct.InstancePatchCall.html) (response) /// * [clone instances](struct.InstanceCloneCall.html) (response) /// * [delete instances](struct.InstanceDeleteCall.html) (response) @@ -1273,6 +1337,9 @@ impl Part for LocationPreference {} pub struct ExportContextSqlExportOptions { /// Tables to export, or that were exported, from the specified database. If you specify tables, specify one and only one database. pub tables: Option>, + /// Export only schemas. + #[serde(rename="schemaOnly")] + pub schema_only: Option, } impl NestedType for ExportContextSqlExportOptions {} @@ -1591,7 +1658,7 @@ impl<'a, C, A> UserMethods<'a, C, A> { /// ::default(), None); /// let mut hub = SQLAdmin::new(hyper::Client::new(), auth); /// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* -/// // like `clone(...)`, `delete(...)`, `export(...)`, `get(...)`, `import(...)`, `insert(...)`, `list(...)`, `patch(...)`, `promote_replica(...)`, `reset_ssl_config(...)`, `restart(...)`, `restore_backup(...)`, `start_replica(...)`, `stop_replica(...)` and `update(...)` +/// // like `clone(...)`, `delete(...)`, `export(...)`, `failover(...)`, `get(...)`, `import(...)`, `insert(...)`, `list(...)`, `patch(...)`, `promote_replica(...)`, `reset_ssl_config(...)`, `restart(...)`, `restore_backup(...)`, `start_replica(...)`, `stop_replica(...)` and `update(...)` /// // to build up your call. /// let rb = hub.instances(); /// # } @@ -1606,6 +1673,27 @@ impl<'a, C, A> MethodsBuilder for InstanceMethods<'a, C, A> {} impl<'a, C, A> InstanceMethods<'a, C, A> { + /// Create a builder to help you perform the following task: + /// + /// Failover the instance to its failover replica instance. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `project` - ID of the project that contains the read replica. + /// * `instance` - Cloud SQL instance ID. This does not include the project ID. + pub fn failover(&self, request: InstancesFailoverRequest, project: &str, instance: &str) -> InstanceFailoverCall<'a, C, A> { + InstanceFailoverCall { + hub: self.hub, + _request: request, + _project: project.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 all client certificates and generates a new server SSL certificate for the instance. The changes will not take effect until the instance is restarted. Existing instances without a server certificate will need to call this once to set a server certificate. @@ -1686,15 +1774,17 @@ impl<'a, C, A> InstanceMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Restarts a Cloud SQL instance. + /// Creates a Cloud SQL instance as a clone of the source instance. /// /// # Arguments /// - /// * `project` - Project ID of the project that contains the instance to be restarted. - /// * `instance` - Cloud SQL instance ID. This does not include the project ID. - pub fn restart(&self, project: &str, instance: &str) -> InstanceRestartCall<'a, C, A> { - InstanceRestartCall { + /// * `request` - No description provided. + /// * `project` - Project ID of the source as well as the clone Cloud SQL instance. + /// * `instance` - The ID of the Cloud SQL instance to be cloned (source). This does not include the project ID. + pub fn clone(&self, request: InstancesCloneRequest, project: &str, instance: &str) -> InstanceCloneCall<'a, C, A> { + InstanceCloneCall { hub: self.hub, + _request: request, _project: project.to_string(), _instance: instance.to_string(), _delegate: Default::default(), @@ -1842,17 +1932,15 @@ impl<'a, C, A> InstanceMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Creates a Cloud SQL instance as a clone of the source instance. + /// Restarts a Cloud SQL instance. /// /// # Arguments /// - /// * `request` - No description provided. - /// * `project` - Project ID of the source as well as the clone Cloud SQL instance. - /// * `instance` - The ID of the Cloud SQL instance to be cloned (source). This does not include the project ID. - pub fn clone(&self, request: InstancesCloneRequest, project: &str, instance: &str) -> InstanceCloneCall<'a, C, A> { - InstanceCloneCall { + /// * `project` - Project ID of the project that contains the instance to be restarted. + /// * `instance` - Cloud SQL instance ID. This does not include the project ID. + pub fn restart(&self, project: &str, instance: &str) -> InstanceRestartCall<'a, C, A> { + InstanceRestartCall { hub: self.hub, - _request: request, _project: project.to_string(), _instance: instance.to_string(), _delegate: Default::default(), @@ -2151,7 +2239,7 @@ impl<'a, C, A> DatabaseMethods<'a, C, A> { /// ::default(), None); /// let mut hub = SQLAdmin::new(hyper::Client::new(), auth); /// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* -/// // like `delete(...)`, `get(...)`, `insert(...)` and `list(...)` +/// // like `create_ephemeral(...)`, `delete(...)`, `get(...)`, `insert(...)` and `list(...)` /// // to build up your call. /// let rb = hub.ssl_certs(); /// # } @@ -2229,6 +2317,27 @@ impl<'a, C, A> SslCertMethods<'a, C, A> { } } + /// Create a builder to help you perform the following task: + /// + /// Generates a short-lived X509 certificate containing the provided public key and signed by a private key specific to the target instance. Users may use the certificate to authenticate as themselves when connecting to the database. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `project` - Project ID of the Cloud SQL project. + /// * `instance` - Cloud SQL instance ID. This does not include the project ID. + pub fn create_ephemeral(&self, request: SslCertsCreateEphemeralRequest, project: &str, instance: &str) -> SslCertCreateEphemeralCall<'a, C, A> { + SslCertCreateEphemeralCall { + hub: self.hub, + _request: request, + _project: project.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: /// /// Lists all of the current SSL certificates for the instance. @@ -2274,7 +2383,7 @@ impl<'a, C, A> SslCertMethods<'a, C, A> { /// ::default(), None); /// let mut hub = SQLAdmin::new(hyper::Client::new(), auth); /// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* -/// // like `get(...)` and `list(...)` +/// // like `delete(...)`, `get(...)` and `list(...)` /// // to build up your call. /// let rb = hub.backup_runs(); /// # } @@ -2330,6 +2439,27 @@ impl<'a, C, A> BackupRunMethods<'a, C, A> { _additional_params: Default::default(), } } + + /// Create a builder to help you perform the following task: + /// + /// Deletes the backup taken by a backup run. + /// + /// # Arguments + /// + /// * `project` - Project ID of the project that contains the instance. + /// * `instance` - Cloud SQL instance ID. This does not include the project ID. + /// * `id` - The ID of the Backup Run to delete. To find a Backup Run ID, use the list method. + pub fn delete(&self, project: &str, instance: &str, id: &str) -> BackupRunDeleteCall<'a, C, A> { + BackupRunDeleteCall { + hub: self.hub, + _project: project.to_string(), + _instance: instance.to_string(), + _id: id.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } } @@ -4198,6 +4328,285 @@ impl<'a, C, A> UserInsertCall<'a, C, A> where C: BorrowMut, A: oa } +/// Failover the instance to its failover replica instance. +/// +/// A builder for the *failover* method supported by a *instance* resource. +/// It is not used directly, but through a `InstanceMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_sqladmin1_beta4 as sqladmin1_beta4; +/// use sqladmin1_beta4::InstancesFailoverRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use sqladmin1_beta4::SQLAdmin; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = SQLAdmin::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req = InstancesFailoverRequest::default(); +/// +/// // You can configure optional parameters by calling 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().failover(req, "project", "instance") +/// .doit(); +/// # } +/// ``` +pub struct InstanceFailoverCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a SQLAdmin, + _request: InstancesFailoverRequest, + _project: String, + _instance: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for InstanceFailoverCall<'a, C, A> {} + +impl<'a, C, A> InstanceFailoverCall<'a, C, A> where 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: "sql.instances.failover", + 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(("instance", self._instance.to_string())); + for &field in ["alt", "project", "instance"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/sql/v1beta4/projects/{project}/instances/{instance}/failover".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{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(2); + for param_name in ["instance", "project"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: InstancesFailoverRequest) -> InstanceFailoverCall<'a, C, A> { + self._request = new_value; + self + } + /// ID of the project that contains the read replica. + /// + /// 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) -> InstanceFailoverCall<'a, C, A> { + self._project = new_value.to_string(); + self + } + /// Cloud SQL instance ID. This does not include the project ID. + /// + /// 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. + pub fn instance(mut self, new_value: &str) -> InstanceFailoverCall<'a, C, A> { + self._instance = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> InstanceFailoverCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> InstanceFailoverCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> InstanceFailoverCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + /// Deletes all client certificates and generates a new server SSL certificate for the instance. The changes will not take effect until the instance is restarted. Existing instances without a server certificate will need to call this once to set a server certificate. /// /// A builder for the *resetSslConfig* method supported by a *instance* resource. @@ -5221,9 +5630,9 @@ impl<'a, C, A> InstancePatchCall<'a, C, A> where C: BorrowMut, A: } -/// Restarts a Cloud SQL instance. +/// Creates a Cloud SQL instance as a clone of the source instance. /// -/// A builder for the *restart* method supported by a *instance* resource. +/// A builder for the *clone* method supported by a *instance* resource. /// It is not used directly, but through a `InstanceMethods` instance. /// /// # Example @@ -5234,6 +5643,7 @@ impl<'a, C, A> InstancePatchCall<'a, C, A> where C: BorrowMut, A: /// # extern crate hyper; /// # extern crate yup_oauth2 as oauth2; /// # extern crate google_sqladmin1_beta4 as sqladmin1_beta4; +/// use sqladmin1_beta4::InstancesCloneRequest; /// # #[test] fn egal() { /// # use std::default::Default; /// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; @@ -5244,17 +5654,23 @@ impl<'a, C, A> InstancePatchCall<'a, C, A> where C: BorrowMut, A: /// # hyper::Client::new(), /// # ::default(), None); /// # let mut hub = SQLAdmin::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req = InstancesCloneRequest::default(); +/// /// // You can configure optional parameters by calling 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().restart("project", "instance") +/// let result = hub.instances().clone(req, "project", "instance") /// .doit(); /// # } /// ``` -pub struct InstanceRestartCall<'a, C, A> +pub struct InstanceCloneCall<'a, C, A> where C: 'a, A: 'a { hub: &'a SQLAdmin, + _request: InstancesCloneRequest, _project: String, _instance: String, _delegate: Option<&'a mut Delegate>, @@ -5262,9 +5678,9 @@ pub struct InstanceRestartCall<'a, C, A> _scopes: BTreeMap } -impl<'a, C, A> CallBuilder for InstanceRestartCall<'a, C, A> {} +impl<'a, C, A> CallBuilder for InstanceCloneCall<'a, C, A> {} -impl<'a, C, A> InstanceRestartCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { +impl<'a, C, A> InstanceCloneCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { /// Perform the operation you have build so far. @@ -5276,9 +5692,9 @@ impl<'a, C, A> InstanceRestartCall<'a, C, A> where C: BorrowMut, Some(d) => d, None => &mut dd }; - dlg.begin(MethodInfo { id: "sql.instances.restart", + dlg.begin(MethodInfo { id: "sql.instances.clone", http_method: hyper::method::Method::Post }); - let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); params.push(("project", self._project.to_string())); params.push(("instance", self._instance.to_string())); for &field in ["alt", "project", "instance"].iter() { @@ -5293,7 +5709,7 @@ impl<'a, C, A> InstanceRestartCall<'a, C, A> where C: BorrowMut, params.push(("alt", "json".to_string())); - let mut url = "https://www.googleapis.com/sql/v1beta4/projects/{project}/instances/{instance}/restart".to_string(); + let mut url = "https://www.googleapis.com/sql/v1beta4/projects/{project}/instances/{instance}/clone".to_string(); if self._scopes.len() == 0 { self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); } @@ -5325,6 +5741,17 @@ impl<'a, C, A> InstanceRestartCall<'a, C, A> where C: BorrowMut, url.push_str(&url::form_urlencoded::serialize(params)); } + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); loop { @@ -5342,11 +5769,15 @@ impl<'a, C, A> InstanceRestartCall<'a, C, A> where C: BorrowMut, }; let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()); + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); dlg.pre_request(); req.send() @@ -5397,23 +5828,32 @@ impl<'a, C, A> InstanceRestartCall<'a, C, A> where C: BorrowMut, } - /// Project ID of the project that contains the instance to be restarted. + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: InstancesCloneRequest) -> InstanceCloneCall<'a, C, A> { + self._request = new_value; + self + } + /// Project ID of the source as well as the clone Cloud SQL instance. /// /// 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) -> InstanceRestartCall<'a, C, A> { + pub fn project(mut self, new_value: &str) -> InstanceCloneCall<'a, C, A> { self._project = new_value.to_string(); self } - /// Cloud SQL instance ID. This does not include the project ID. + /// The ID of the Cloud SQL instance to be cloned (source). This does not include the project ID. /// /// 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. - pub fn instance(mut self, new_value: &str) -> InstanceRestartCall<'a, C, A> { + pub fn instance(mut self, new_value: &str) -> InstanceCloneCall<'a, C, A> { self._instance = new_value.to_string(); self } @@ -5423,7 +5863,7 @@ impl<'a, C, A> InstanceRestartCall<'a, C, A> where C: BorrowMut, /// It should be used to handle progress information, and to implement a certain level of resilience. /// /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> InstanceRestartCall<'a, C, A> { + pub fn delegate(mut self, new_value: &'a mut Delegate) -> InstanceCloneCall<'a, C, A> { self._delegate = Some(new_value); self } @@ -5444,7 +5884,7 @@ impl<'a, C, A> InstanceRestartCall<'a, C, A> where C: BorrowMut, /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. /// * *alt* (query-string) - Data format for the response. - pub fn param(mut self, name: T, value: T) -> InstanceRestartCall<'a, C, A> + pub fn param(mut self, name: T, value: T) -> InstanceCloneCall<'a, C, A> where T: AsRef { self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); self @@ -5461,7 +5901,7 @@ impl<'a, C, A> InstanceRestartCall<'a, C, A> where C: BorrowMut, /// Usually there is more than one suitable scope to authorize an operation, some of which may /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be /// sufficient, a read-write scope will do as well. - pub fn add_scope(mut self, scope: T) -> InstanceRestartCall<'a, C, A> + pub fn add_scope(mut self, scope: T) -> InstanceCloneCall<'a, C, A> where T: AsRef { self._scopes.insert(scope.as_ref().to_string(), ()); self @@ -6507,8 +6947,8 @@ impl<'a, C, A> InstanceInsertCall<'a, C, A> where C: BorrowMut, A /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.instances().list("project") -/// .page_token("aliquyam") -/// .max_results(28) +/// .page_token("Lorem") +/// .max_results(92) /// .doit(); /// # } /// ``` @@ -7298,9 +7738,9 @@ impl<'a, C, A> InstanceUpdateCall<'a, C, A> where C: BorrowMut, A } -/// Creates a Cloud SQL instance as a clone of the source instance. +/// Restarts a Cloud SQL instance. /// -/// A builder for the *clone* method supported by a *instance* resource. +/// A builder for the *restart* method supported by a *instance* resource. /// It is not used directly, but through a `InstanceMethods` instance. /// /// # Example @@ -7311,7 +7751,6 @@ impl<'a, C, A> InstanceUpdateCall<'a, C, A> where C: BorrowMut, A /// # extern crate hyper; /// # extern crate yup_oauth2 as oauth2; /// # extern crate google_sqladmin1_beta4 as sqladmin1_beta4; -/// use sqladmin1_beta4::InstancesCloneRequest; /// # #[test] fn egal() { /// # use std::default::Default; /// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; @@ -7322,23 +7761,17 @@ impl<'a, C, A> InstanceUpdateCall<'a, C, A> where C: BorrowMut, A /// # hyper::Client::new(), /// # ::default(), None); /// # let mut hub = SQLAdmin::new(hyper::Client::new(), auth); -/// // As the method needs a request, you would usually fill it with the desired information -/// // into the respective structure. Some of the parts shown here might not be applicable ! -/// // Values shown here are possibly random and not representative ! -/// let mut req = InstancesCloneRequest::default(); -/// /// // You can configure optional parameters by calling 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().clone(req, "project", "instance") +/// let result = hub.instances().restart("project", "instance") /// .doit(); /// # } /// ``` -pub struct InstanceCloneCall<'a, C, A> +pub struct InstanceRestartCall<'a, C, A> where C: 'a, A: 'a { hub: &'a SQLAdmin, - _request: InstancesCloneRequest, _project: String, _instance: String, _delegate: Option<&'a mut Delegate>, @@ -7346,9 +7779,9 @@ pub struct InstanceCloneCall<'a, C, A> _scopes: BTreeMap } -impl<'a, C, A> CallBuilder for InstanceCloneCall<'a, C, A> {} +impl<'a, C, A> CallBuilder for InstanceRestartCall<'a, C, A> {} -impl<'a, C, A> InstanceCloneCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { +impl<'a, C, A> InstanceRestartCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { /// Perform the operation you have build so far. @@ -7360,9 +7793,9 @@ impl<'a, C, A> InstanceCloneCall<'a, C, A> where C: BorrowMut, A: Some(d) => d, None => &mut dd }; - dlg.begin(MethodInfo { id: "sql.instances.clone", + dlg.begin(MethodInfo { id: "sql.instances.restart", http_method: hyper::method::Method::Post }); - let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); params.push(("project", self._project.to_string())); params.push(("instance", self._instance.to_string())); for &field in ["alt", "project", "instance"].iter() { @@ -7377,7 +7810,7 @@ impl<'a, C, A> InstanceCloneCall<'a, C, A> where C: BorrowMut, A: params.push(("alt", "json".to_string())); - let mut url = "https://www.googleapis.com/sql/v1beta4/projects/{project}/instances/{instance}/clone".to_string(); + let mut url = "https://www.googleapis.com/sql/v1beta4/projects/{project}/instances/{instance}/restart".to_string(); if self._scopes.len() == 0 { self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); } @@ -7409,17 +7842,6 @@ impl<'a, C, A> InstanceCloneCall<'a, C, A> where C: BorrowMut, A: url.push_str(&url::form_urlencoded::serialize(params)); } - let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); - let mut request_value_reader = - { - let mut value = json::value::to_value(&self._request); - remove_json_null_values(&mut value); - let mut dst = io::Cursor::new(Vec::with_capacity(128)); - json::to_writer(&mut dst, &value).unwrap(); - dst - }; - let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); - request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); loop { @@ -7437,15 +7859,11 @@ impl<'a, C, A> InstanceCloneCall<'a, C, A> where C: BorrowMut, A: }; let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, access_token: token.access_token }); - request_value_reader.seek(io::SeekFrom::Start(0)).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) .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()) - .header(ContentType(json_mime_type.clone())) - .header(ContentLength(request_size as u64)) - .body(&mut request_value_reader); + .header(auth_header.clone()); dlg.pre_request(); req.send() @@ -7496,32 +7914,23 @@ impl<'a, C, A> InstanceCloneCall<'a, C, A> where C: BorrowMut, A: } - /// - /// Sets the *request* property to the given value. - /// - /// Even though the property as already been set when instantiating this call, - /// we provide this method for API completeness. - pub fn request(mut self, new_value: InstancesCloneRequest) -> InstanceCloneCall<'a, C, A> { - self._request = new_value; - self - } - /// Project ID of the source as well as the clone Cloud SQL instance. + /// Project ID of the project that contains the instance to be restarted. /// /// 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) -> InstanceCloneCall<'a, C, A> { + pub fn project(mut self, new_value: &str) -> InstanceRestartCall<'a, C, A> { self._project = new_value.to_string(); self } - /// The ID of the Cloud SQL instance to be cloned (source). This does not include the project ID. + /// Cloud SQL instance ID. This does not include the project ID. /// /// 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. - pub fn instance(mut self, new_value: &str) -> InstanceCloneCall<'a, C, A> { + pub fn instance(mut self, new_value: &str) -> InstanceRestartCall<'a, C, A> { self._instance = new_value.to_string(); self } @@ -7531,7 +7940,7 @@ impl<'a, C, A> InstanceCloneCall<'a, C, A> where C: BorrowMut, A: /// It should be used to handle progress information, and to implement a certain level of resilience. /// /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> InstanceCloneCall<'a, C, A> { + pub fn delegate(mut self, new_value: &'a mut Delegate) -> InstanceRestartCall<'a, C, A> { self._delegate = Some(new_value); self } @@ -7552,7 +7961,7 @@ impl<'a, C, A> InstanceCloneCall<'a, C, A> where C: BorrowMut, A: /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. /// * *alt* (query-string) - Data format for the response. - pub fn param(mut self, name: T, value: T) -> InstanceCloneCall<'a, C, A> + pub fn param(mut self, name: T, value: T) -> InstanceRestartCall<'a, C, A> where T: AsRef { self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); self @@ -7569,7 +7978,7 @@ impl<'a, C, A> InstanceCloneCall<'a, C, A> where C: BorrowMut, A: /// Usually there is more than one suitable scope to authorize an operation, some of which may /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be /// sufficient, a read-write scope will do as well. - pub fn add_scope(mut self, scope: T) -> InstanceCloneCall<'a, C, A> + pub fn add_scope(mut self, scope: T) -> InstanceRestartCall<'a, C, A> where T: AsRef { self._scopes.insert(scope.as_ref().to_string(), ()); self @@ -10766,6 +11175,285 @@ impl<'a, C, A> SslCertGetCall<'a, C, A> where C: BorrowMut, A: oa } +/// Generates a short-lived X509 certificate containing the provided public key and signed by a private key specific to the target instance. Users may use the certificate to authenticate as themselves when connecting to the database. +/// +/// A builder for the *createEphemeral* method supported by a *sslCert* resource. +/// It is not used directly, but through a `SslCertMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_sqladmin1_beta4 as sqladmin1_beta4; +/// use sqladmin1_beta4::SslCertsCreateEphemeralRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use sqladmin1_beta4::SQLAdmin; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = SQLAdmin::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req = SslCertsCreateEphemeralRequest::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.ssl_certs().create_ephemeral(req, "project", "instance") +/// .doit(); +/// # } +/// ``` +pub struct SslCertCreateEphemeralCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a SQLAdmin, + _request: SslCertsCreateEphemeralRequest, + _project: String, + _instance: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for SslCertCreateEphemeralCall<'a, C, A> {} + +impl<'a, C, A> SslCertCreateEphemeralCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, SslCert)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "sql.sslCerts.createEphemeral", + 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(("instance", self._instance.to_string())); + for &field in ["alt", "project", "instance"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/sql/v1beta4/projects/{project}/instances/{instance}/createEphemeral".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{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(2); + for param_name in ["instance", "project"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: SslCertsCreateEphemeralRequest) -> SslCertCreateEphemeralCall<'a, C, A> { + self._request = new_value; + self + } + /// Project ID of the Cloud SQL project. + /// + /// 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) -> SslCertCreateEphemeralCall<'a, C, A> { + self._project = new_value.to_string(); + self + } + /// Cloud SQL instance ID. This does not include the project ID. + /// + /// 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. + pub fn instance(mut self, new_value: &str) -> SslCertCreateEphemeralCall<'a, C, A> { + self._instance = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> SslCertCreateEphemeralCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> SslCertCreateEphemeralCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> SslCertCreateEphemeralCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + /// Lists all of the current SSL certificates for the instance. /// /// A builder for the *list* method supported by a *sslCert* resource. @@ -11041,7 +11729,7 @@ impl<'a, C, A> SslCertListCall<'a, C, A> where C: BorrowMut, A: o /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.backup_runs().list("project", "instance") -/// .page_token("et") +/// .page_token("nonumy") /// .max_results(-13) /// .doit(); /// # } @@ -11546,3 +12234,263 @@ impl<'a, C, A> BackupRunGetCall<'a, C, A> where C: BorrowMut, A: } +/// Deletes the backup taken by a backup run. +/// +/// A builder for the *delete* method supported by a *backupRun* resource. +/// It is not used directly, but through a `BackupRunMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_sqladmin1_beta4 as sqladmin1_beta4; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use sqladmin1_beta4::SQLAdmin; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = SQLAdmin::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.backup_runs().delete("project", "instance", "id") +/// .doit(); +/// # } +/// ``` +pub struct BackupRunDeleteCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a SQLAdmin, + _project: String, + _instance: String, + _id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for BackupRunDeleteCall<'a, C, A> {} + +impl<'a, C, A> BackupRunDeleteCall<'a, C, A> where 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: "sql.backupRuns.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(("instance", self._instance.to_string())); + params.push(("id", self._id.to_string())); + for &field in ["alt", "project", "instance", "id"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/sql/v1beta4/projects/{project}/instances/{instance}/backupRuns/{id}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{project}", "project"), ("{instance}", "instance"), ("{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 ["id", "instance", "project"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Project ID of the project that contains the instance. + /// + /// 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) -> BackupRunDeleteCall<'a, C, A> { + self._project = new_value.to_string(); + self + } + /// Cloud SQL instance ID. This does not include the project ID. + /// + /// 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. + pub fn instance(mut self, new_value: &str) -> BackupRunDeleteCall<'a, C, A> { + self._instance = new_value.to_string(); + self + } + /// The ID of the Backup Run to delete. To find a Backup Run ID, use the list method. + /// + /// 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. + pub fn id(mut self, new_value: &str) -> BackupRunDeleteCall<'a, C, A> { + self._id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> BackupRunDeleteCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> BackupRunDeleteCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> BackupRunDeleteCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + diff --git a/gen/storage1-cli/Cargo.toml b/gen/storage1-cli/Cargo.toml index 626c1f8ddf..e38ed6c41b 100644 --- a/gen/storage1-cli/Cargo.toml +++ b/gen/storage1-cli/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-storage1-cli" -version = "0.3.2+20150710" +version = "0.3.2+20151007" authors = ["Sebastian Thiel "] description = "A complete library to interact with storage (protocol v1)" repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/storage1-cli" diff --git a/gen/storage1-cli/README.md b/gen/storage1-cli/README.md index 33789f48b4..f0f05b2653 100644 --- a/gen/storage1-cli/README.md +++ b/gen/storage1-cli/README.md @@ -24,7 +24,7 @@ Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/ma # Usage -This documentation was generated from the *storage* API at revision *20150710*. The CLI is at version *0.3.2*. +This documentation was generated from the *storage* API at revision *20151007*. The CLI is at version *0.3.2*. ```bash storage1 [options] diff --git a/gen/storage1-cli/mkdocs.yml b/gen/storage1-cli/mkdocs.yml index 4855cf77c8..3af7e6c665 100644 --- a/gen/storage1-cli/mkdocs.yml +++ b/gen/storage1-cli/mkdocs.yml @@ -1,4 +1,4 @@ -site_name: storage v0.3.2+20150710 +site_name: storage v0.3.2+20151007 site_url: http://byron.github.io/google-apis-rs/google-storage1-cli site_description: Write integrating applications with bcore diff --git a/gen/storage1-cli/src/main.rs b/gen/storage1-cli/src/main.rs index 6dcb86dc7e..3adf6b6929 100644 --- a/gen/storage1-cli/src/main.rs +++ b/gen/storage1-cli/src/main.rs @@ -620,12 +620,13 @@ impl<'n, 'a> Engine<'n, 'a> { "website.not-found-page" => Some(("website.notFoundPage", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "website.main-page-suffix" => Some(("website.mainPageSuffix", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "self-link" => Some(("selfLink", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), - "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "updated" => Some(("updated", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "logging.log-object-prefix" => Some(("logging.logObjectPrefix", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "logging.log-bucket" => Some(("logging.logBucket", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "time-created" => Some(("timeCreated", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "location" => Some(("location", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "project-number" => Some(("projectNumber", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "metageneration" => Some(("metageneration", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "etag" => Some(("etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), @@ -635,7 +636,7 @@ impl<'n, 'a> Engine<'n, 'a> { "versioning.enabled" => Some(("versioning.enabled", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), "storage-class" => Some(("storageClass", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), _ => { - let suggestion = FieldCursor::did_you_mean(key, &vec!["enabled", "entity", "entity-id", "etag", "id", "kind", "location", "log-bucket", "log-object-prefix", "logging", "main-page-suffix", "metageneration", "name", "not-found-page", "owner", "project-number", "self-link", "storage-class", "time-created", "versioning", "website"]); + let suggestion = FieldCursor::did_you_mean(key, &vec!["enabled", "entity", "entity-id", "etag", "id", "kind", "location", "log-bucket", "log-object-prefix", "logging", "main-page-suffix", "metageneration", "name", "not-found-page", "owner", "project-number", "self-link", "storage-class", "time-created", "updated", "versioning", "website"]); err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); None } @@ -796,12 +797,13 @@ impl<'n, 'a> Engine<'n, 'a> { "website.not-found-page" => Some(("website.notFoundPage", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "website.main-page-suffix" => Some(("website.mainPageSuffix", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "self-link" => Some(("selfLink", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), - "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "updated" => Some(("updated", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "logging.log-object-prefix" => Some(("logging.logObjectPrefix", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "logging.log-bucket" => Some(("logging.logBucket", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "time-created" => Some(("timeCreated", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "location" => Some(("location", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "project-number" => Some(("projectNumber", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "metageneration" => Some(("metageneration", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "etag" => Some(("etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), @@ -811,7 +813,7 @@ impl<'n, 'a> Engine<'n, 'a> { "versioning.enabled" => Some(("versioning.enabled", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), "storage-class" => Some(("storageClass", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), _ => { - let suggestion = FieldCursor::did_you_mean(key, &vec!["enabled", "entity", "entity-id", "etag", "id", "kind", "location", "log-bucket", "log-object-prefix", "logging", "main-page-suffix", "metageneration", "name", "not-found-page", "owner", "project-number", "self-link", "storage-class", "time-created", "versioning", "website"]); + let suggestion = FieldCursor::did_you_mean(key, &vec!["enabled", "entity", "entity-id", "etag", "id", "kind", "location", "log-bucket", "log-object-prefix", "logging", "main-page-suffix", "metageneration", "name", "not-found-page", "owner", "project-number", "self-link", "storage-class", "time-created", "updated", "versioning", "website"]); err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); None } @@ -913,12 +915,13 @@ impl<'n, 'a> Engine<'n, 'a> { "website.not-found-page" => Some(("website.notFoundPage", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "website.main-page-suffix" => Some(("website.mainPageSuffix", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "self-link" => Some(("selfLink", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), - "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "updated" => Some(("updated", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "logging.log-object-prefix" => Some(("logging.logObjectPrefix", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "logging.log-bucket" => Some(("logging.logBucket", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "time-created" => Some(("timeCreated", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "location" => Some(("location", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "project-number" => Some(("projectNumber", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "metageneration" => Some(("metageneration", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "etag" => Some(("etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), @@ -928,7 +931,7 @@ impl<'n, 'a> Engine<'n, 'a> { "versioning.enabled" => Some(("versioning.enabled", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), "storage-class" => Some(("storageClass", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), _ => { - let suggestion = FieldCursor::did_you_mean(key, &vec!["enabled", "entity", "entity-id", "etag", "id", "kind", "location", "log-bucket", "log-object-prefix", "logging", "main-page-suffix", "metageneration", "name", "not-found-page", "owner", "project-number", "self-link", "storage-class", "time-created", "versioning", "website"]); + let suggestion = FieldCursor::did_you_mean(key, &vec!["enabled", "entity", "entity-id", "etag", "id", "kind", "location", "log-bucket", "log-object-prefix", "logging", "main-page-suffix", "metageneration", "name", "not-found-page", "owner", "project-number", "self-link", "storage-class", "time-created", "updated", "versioning", "website"]); err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); None } @@ -2029,7 +2032,6 @@ impl<'n, 'a> Engine<'n, 'a> { let type_info: Option<(&'static str, JsonTypeInfo)> = match &temp_cursor.to_string()[..] { "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), - "destination.self-link" => Some(("destination.selfLink", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "destination.generation" => Some(("destination.generation", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "destination.component-count" => Some(("destination.componentCount", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), "destination.media-link" => Some(("destination.mediaLink", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), @@ -2039,12 +2041,14 @@ impl<'n, 'a> Engine<'n, 'a> { "destination.id" => Some(("destination.id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "destination.size" => Some(("destination.size", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "destination.time-deleted" => Some(("destination.timeDeleted", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "destination.time-created" => Some(("destination.timeCreated", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "destination.md5-hash" => Some(("destination.md5Hash", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "destination.crc32c" => Some(("destination.crc32c", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "destination.etag" => Some(("destination.etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "destination.metadata" => Some(("destination.metadata", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Map })), "destination.updated" => Some(("destination.updated", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "destination.content-type" => Some(("destination.contentType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "destination.content-disposition" => Some(("destination.contentDisposition", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "destination.content-language" => Some(("destination.contentLanguage", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "destination.metageneration" => Some(("destination.metageneration", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "destination.kind" => Some(("destination.kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), @@ -2052,9 +2056,9 @@ impl<'n, 'a> Engine<'n, 'a> { "destination.bucket" => Some(("destination.bucket", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "destination.content-encoding" => Some(("destination.contentEncoding", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "destination.storage-class" => Some(("destination.storageClass", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), - "destination.content-disposition" => Some(("destination.contentDisposition", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "destination.self-link" => Some(("destination.selfLink", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), _ => { - let suggestion = FieldCursor::did_you_mean(key, &vec!["bucket", "cache-control", "component-count", "content-disposition", "content-encoding", "content-language", "content-type", "crc32c", "destination", "entity", "entity-id", "etag", "generation", "id", "kind", "md5-hash", "media-link", "metadata", "metageneration", "name", "owner", "self-link", "size", "storage-class", "time-deleted", "updated"]); + let suggestion = FieldCursor::did_you_mean(key, &vec!["bucket", "cache-control", "component-count", "content-disposition", "content-encoding", "content-language", "content-type", "crc32c", "destination", "entity", "entity-id", "etag", "generation", "id", "kind", "md5-hash", "media-link", "metadata", "metageneration", "name", "owner", "self-link", "size", "storage-class", "time-created", "time-deleted", "updated"]); err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); None } @@ -2156,7 +2160,6 @@ impl<'n, 'a> Engine<'n, 'a> { let type_info: Option<(&'static str, JsonTypeInfo)> = match &temp_cursor.to_string()[..] { - "self-link" => Some(("selfLink", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "generation" => Some(("generation", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "component-count" => Some(("componentCount", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), "media-link" => Some(("mediaLink", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), @@ -2166,12 +2169,14 @@ impl<'n, 'a> Engine<'n, 'a> { "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "size" => Some(("size", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "time-deleted" => Some(("timeDeleted", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "time-created" => Some(("timeCreated", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "md5-hash" => Some(("md5Hash", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "crc32c" => Some(("crc32c", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "etag" => Some(("etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "metadata" => Some(("metadata", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Map })), "updated" => Some(("updated", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "content-type" => Some(("contentType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "content-disposition" => Some(("contentDisposition", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "content-language" => Some(("contentLanguage", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "metageneration" => Some(("metageneration", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), @@ -2179,9 +2184,9 @@ impl<'n, 'a> Engine<'n, 'a> { "bucket" => Some(("bucket", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "content-encoding" => Some(("contentEncoding", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "storage-class" => Some(("storageClass", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), - "content-disposition" => Some(("contentDisposition", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "self-link" => Some(("selfLink", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), _ => { - let suggestion = FieldCursor::did_you_mean(key, &vec!["bucket", "cache-control", "component-count", "content-disposition", "content-encoding", "content-language", "content-type", "crc32c", "entity", "entity-id", "etag", "generation", "id", "kind", "md5-hash", "media-link", "metadata", "metageneration", "name", "owner", "self-link", "size", "storage-class", "time-deleted", "updated"]); + let suggestion = FieldCursor::did_you_mean(key, &vec!["bucket", "cache-control", "component-count", "content-disposition", "content-encoding", "content-language", "content-type", "crc32c", "entity", "entity-id", "etag", "generation", "id", "kind", "md5-hash", "media-link", "metadata", "metageneration", "name", "owner", "self-link", "size", "storage-class", "time-created", "time-deleted", "updated"]); err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); None } @@ -2447,7 +2452,6 @@ impl<'n, 'a> Engine<'n, 'a> { let type_info: Option<(&'static str, JsonTypeInfo)> = match &temp_cursor.to_string()[..] { - "self-link" => Some(("selfLink", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "generation" => Some(("generation", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "component-count" => Some(("componentCount", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), "media-link" => Some(("mediaLink", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), @@ -2457,12 +2461,14 @@ impl<'n, 'a> Engine<'n, 'a> { "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "size" => Some(("size", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "time-deleted" => Some(("timeDeleted", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "time-created" => Some(("timeCreated", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "md5-hash" => Some(("md5Hash", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "crc32c" => Some(("crc32c", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "etag" => Some(("etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "metadata" => Some(("metadata", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Map })), "updated" => Some(("updated", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "content-type" => Some(("contentType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "content-disposition" => Some(("contentDisposition", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "content-language" => Some(("contentLanguage", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "metageneration" => Some(("metageneration", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), @@ -2470,9 +2476,9 @@ impl<'n, 'a> Engine<'n, 'a> { "bucket" => Some(("bucket", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "content-encoding" => Some(("contentEncoding", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "storage-class" => Some(("storageClass", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), - "content-disposition" => Some(("contentDisposition", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "self-link" => Some(("selfLink", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), _ => { - let suggestion = FieldCursor::did_you_mean(key, &vec!["bucket", "cache-control", "component-count", "content-disposition", "content-encoding", "content-language", "content-type", "crc32c", "entity", "entity-id", "etag", "generation", "id", "kind", "md5-hash", "media-link", "metadata", "metageneration", "name", "owner", "self-link", "size", "storage-class", "time-deleted", "updated"]); + let suggestion = FieldCursor::did_you_mean(key, &vec!["bucket", "cache-control", "component-count", "content-disposition", "content-encoding", "content-language", "content-type", "crc32c", "entity", "entity-id", "etag", "generation", "id", "kind", "md5-hash", "media-link", "metadata", "metageneration", "name", "owner", "self-link", "size", "storage-class", "time-created", "time-deleted", "updated"]); err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); None } @@ -2657,7 +2663,6 @@ impl<'n, 'a> Engine<'n, 'a> { let type_info: Option<(&'static str, JsonTypeInfo)> = match &temp_cursor.to_string()[..] { - "self-link" => Some(("selfLink", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "generation" => Some(("generation", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "component-count" => Some(("componentCount", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), "media-link" => Some(("mediaLink", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), @@ -2667,12 +2672,14 @@ impl<'n, 'a> Engine<'n, 'a> { "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "size" => Some(("size", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "time-deleted" => Some(("timeDeleted", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "time-created" => Some(("timeCreated", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "md5-hash" => Some(("md5Hash", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "crc32c" => Some(("crc32c", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "etag" => Some(("etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "metadata" => Some(("metadata", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Map })), "updated" => Some(("updated", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "content-type" => Some(("contentType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "content-disposition" => Some(("contentDisposition", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "content-language" => Some(("contentLanguage", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "metageneration" => Some(("metageneration", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), @@ -2680,9 +2687,9 @@ impl<'n, 'a> Engine<'n, 'a> { "bucket" => Some(("bucket", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "content-encoding" => Some(("contentEncoding", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "storage-class" => Some(("storageClass", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), - "content-disposition" => Some(("contentDisposition", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "self-link" => Some(("selfLink", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), _ => { - let suggestion = FieldCursor::did_you_mean(key, &vec!["bucket", "cache-control", "component-count", "content-disposition", "content-encoding", "content-language", "content-type", "crc32c", "entity", "entity-id", "etag", "generation", "id", "kind", "md5-hash", "media-link", "metadata", "metageneration", "name", "owner", "self-link", "size", "storage-class", "time-deleted", "updated"]); + let suggestion = FieldCursor::did_you_mean(key, &vec!["bucket", "cache-control", "component-count", "content-disposition", "content-encoding", "content-language", "content-type", "crc32c", "entity", "entity-id", "etag", "generation", "id", "kind", "md5-hash", "media-link", "metadata", "metageneration", "name", "owner", "self-link", "size", "storage-class", "time-created", "time-deleted", "updated"]); err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); None } @@ -2787,7 +2794,6 @@ impl<'n, 'a> Engine<'n, 'a> { let type_info: Option<(&'static str, JsonTypeInfo)> = match &temp_cursor.to_string()[..] { - "self-link" => Some(("selfLink", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "generation" => Some(("generation", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "component-count" => Some(("componentCount", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), "media-link" => Some(("mediaLink", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), @@ -2797,12 +2803,14 @@ impl<'n, 'a> Engine<'n, 'a> { "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "size" => Some(("size", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "time-deleted" => Some(("timeDeleted", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "time-created" => Some(("timeCreated", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "md5-hash" => Some(("md5Hash", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "crc32c" => Some(("crc32c", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "etag" => Some(("etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "metadata" => Some(("metadata", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Map })), "updated" => Some(("updated", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "content-type" => Some(("contentType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "content-disposition" => Some(("contentDisposition", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "content-language" => Some(("contentLanguage", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "metageneration" => Some(("metageneration", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), @@ -2810,9 +2818,9 @@ impl<'n, 'a> Engine<'n, 'a> { "bucket" => Some(("bucket", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "content-encoding" => Some(("contentEncoding", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "storage-class" => Some(("storageClass", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), - "content-disposition" => Some(("contentDisposition", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "self-link" => Some(("selfLink", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), _ => { - let suggestion = FieldCursor::did_you_mean(key, &vec!["bucket", "cache-control", "component-count", "content-disposition", "content-encoding", "content-language", "content-type", "crc32c", "entity", "entity-id", "etag", "generation", "id", "kind", "md5-hash", "media-link", "metadata", "metageneration", "name", "owner", "self-link", "size", "storage-class", "time-deleted", "updated"]); + let suggestion = FieldCursor::did_you_mean(key, &vec!["bucket", "cache-control", "component-count", "content-disposition", "content-encoding", "content-language", "content-type", "crc32c", "entity", "entity-id", "etag", "generation", "id", "kind", "md5-hash", "media-link", "metadata", "metageneration", "name", "owner", "self-link", "size", "storage-class", "time-created", "time-deleted", "updated"]); err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); None } @@ -2935,7 +2943,6 @@ impl<'n, 'a> Engine<'n, 'a> { let type_info: Option<(&'static str, JsonTypeInfo)> = match &temp_cursor.to_string()[..] { - "self-link" => Some(("selfLink", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "generation" => Some(("generation", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "component-count" => Some(("componentCount", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), "media-link" => Some(("mediaLink", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), @@ -2945,12 +2952,14 @@ impl<'n, 'a> Engine<'n, 'a> { "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "size" => Some(("size", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "time-deleted" => Some(("timeDeleted", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "time-created" => Some(("timeCreated", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "md5-hash" => Some(("md5Hash", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "crc32c" => Some(("crc32c", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "etag" => Some(("etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "metadata" => Some(("metadata", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Map })), "updated" => Some(("updated", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "content-type" => Some(("contentType", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "content-disposition" => Some(("contentDisposition", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "content-language" => Some(("contentLanguage", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "metageneration" => Some(("metageneration", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "kind" => Some(("kind", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), @@ -2958,9 +2967,9 @@ impl<'n, 'a> Engine<'n, 'a> { "bucket" => Some(("bucket", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "content-encoding" => Some(("contentEncoding", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "storage-class" => Some(("storageClass", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), - "content-disposition" => Some(("contentDisposition", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "self-link" => Some(("selfLink", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), _ => { - let suggestion = FieldCursor::did_you_mean(key, &vec!["bucket", "cache-control", "component-count", "content-disposition", "content-encoding", "content-language", "content-type", "crc32c", "entity", "entity-id", "etag", "generation", "id", "kind", "md5-hash", "media-link", "metadata", "metageneration", "name", "owner", "self-link", "size", "storage-class", "time-deleted", "updated"]); + let suggestion = FieldCursor::did_you_mean(key, &vec!["bucket", "cache-control", "component-count", "content-disposition", "content-encoding", "content-language", "content-type", "crc32c", "entity", "entity-id", "etag", "generation", "id", "kind", "md5-hash", "media-link", "metadata", "metageneration", "name", "owner", "self-link", "size", "storage-class", "time-created", "time-deleted", "updated"]); err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); None } @@ -3926,7 +3935,7 @@ fn main() { (Some(r##"object"##), None, - Some(r##"Name of the object."##), + Some(r##"Name of the object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts."##), Some(true), Some(false)), @@ -3954,7 +3963,7 @@ fn main() { (Some(r##"object"##), None, - Some(r##"Name of the object."##), + Some(r##"Name of the object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts."##), Some(true), Some(false)), @@ -3988,7 +3997,7 @@ fn main() { (Some(r##"object"##), None, - Some(r##"Name of the object."##), + Some(r##"Name of the object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts."##), Some(true), Some(false)), @@ -4022,7 +4031,7 @@ fn main() { (Some(r##"object"##), None, - Some(r##"Name of the object."##), + Some(r##"Name of the object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts."##), Some(true), Some(false)), @@ -4050,7 +4059,7 @@ fn main() { (Some(r##"object"##), None, - Some(r##"Name of the object."##), + Some(r##"Name of the object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts."##), Some(true), Some(false)), @@ -4090,7 +4099,7 @@ fn main() { (Some(r##"object"##), None, - Some(r##"Name of the object."##), + Some(r##"Name of the object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts."##), Some(true), Some(false)), @@ -4133,7 +4142,7 @@ fn main() { (Some(r##"destination-object"##), None, - Some(r##"Name of the new object."##), + Some(r##"Name of the new object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts."##), Some(true), Some(false)), @@ -4167,13 +4176,13 @@ fn main() { (Some(r##"source-object"##), None, - Some(r##"Name of the source object."##), + Some(r##"Name of the source object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts."##), Some(true), Some(false)), (Some(r##"destination-bucket"##), None, - Some(r##"Name of the bucket in which to store the new object. Overrides the provided object metadata's bucket value, if any."##), + Some(r##"Name of the bucket in which to store the new object. Overrides the provided object metadata's bucket value, if any.For information about how to URL encode object names to be path safe, see Encoding URI Path Parts."##), Some(true), Some(false)), @@ -4213,7 +4222,7 @@ fn main() { (Some(r##"object"##), None, - Some(r##"Name of the object."##), + Some(r##"Name of the object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts."##), Some(true), Some(false)), @@ -4235,7 +4244,7 @@ fn main() { (Some(r##"object"##), None, - Some(r##"Name of the object."##), + Some(r##"Name of the object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts."##), Some(true), Some(false)), @@ -4319,7 +4328,7 @@ fn main() { (Some(r##"object"##), None, - Some(r##"Name of the object."##), + Some(r##"Name of the object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts."##), Some(true), Some(false)), @@ -4353,7 +4362,7 @@ fn main() { (Some(r##"source-object"##), None, - Some(r##"Name of the source object."##), + Some(r##"Name of the source object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts."##), Some(true), Some(false)), @@ -4365,7 +4374,7 @@ fn main() { (Some(r##"destination-object"##), None, - Some(r##"Name of the new object. Required when the object metadata is not otherwise provided. Overrides the object metadata's name value, if any."##), + Some(r##"Name of the new object. Required when the object metadata is not otherwise provided. Overrides the object metadata's name value, if any. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts."##), Some(true), Some(false)), @@ -4399,7 +4408,7 @@ fn main() { (Some(r##"object"##), None, - Some(r##"Name of the object."##), + Some(r##"Name of the object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts."##), Some(true), Some(false)), @@ -4455,7 +4464,7 @@ fn main() { let mut app = App::new("storage1") .author("Sebastian Thiel ") - .version("0.3.2+20150710") + .version("0.3.2+20151007") .about("Lets you store and retrieve potentially-large, immutable data objects.") .after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_storage1_cli") .arg(Arg::with_name("url") diff --git a/gen/storage1/Cargo.toml b/gen/storage1/Cargo.toml index 28c9bdc6da..9757608d59 100644 --- a/gen/storage1/Cargo.toml +++ b/gen/storage1/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-storage1" -version = "0.1.9+20150710" +version = "0.1.9+20151007" authors = ["Sebastian Thiel "] description = "A complete library to interact with storage (protocol v1)" repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/storage1" diff --git a/gen/storage1/README.md b/gen/storage1/README.md index a1cf0e0501..baa8c8db15 100644 --- a/gen/storage1/README.md +++ b/gen/storage1/README.md @@ -5,7 +5,7 @@ DO NOT EDIT ! --> The `google-storage1` library allows access to all features of the *Google storage* service. -This documentation was generated from *storage* crate version *0.1.9+20150710*, where *20150710* is the exact revision of the *storage:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +This documentation was generated from *storage* crate version *0.1.9+20151007*, where *20151007* is the exact revision of the *storage:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. Everything else about the *storage* *v1* API can be found at the [official documentation site](https://developers.google.com/storage/docs/json_api/). diff --git a/gen/storage1/src/lib.rs b/gen/storage1/src/lib.rs index e7609588d2..30509566b4 100644 --- a/gen/storage1/src/lib.rs +++ b/gen/storage1/src/lib.rs @@ -2,7 +2,7 @@ // This file was generated automatically from 'src/mako/api/lib.rs.mako' // DO NOT EDIT ! -//! This documentation was generated from *storage* crate version *0.1.9+20150710*, where *20150710* is the exact revision of the *storage:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +//! This documentation was generated from *storage* crate version *0.1.9+20151007*, where *20151007* is the exact revision of the *storage:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. //! //! Everything else about the *storage* *v1* API can be found at the //! [official documentation site](https://developers.google.com/storage/docs/json_api/). diff --git a/gen/storage1/src/lib.rs.in b/gen/storage1/src/lib.rs.in index 271c7485b0..38635bfc08 100644 --- a/gen/storage1/src/lib.rs.in +++ b/gen/storage1/src/lib.rs.in @@ -46,6 +46,9 @@ pub enum Scope { /// Manage your data and permissions in Google Cloud Storage DevstorageFullControl, + + /// View your data across Google Cloud Platform services + CloudPlatformReadOnly, } impl AsRef for Scope { @@ -55,6 +58,7 @@ impl AsRef for Scope { Scope::DevstorageReadWrite => "https://www.googleapis.com/auth/devstorage.read_write", Scope::CloudPlatform => "https://www.googleapis.com/auth/cloud-platform", Scope::DevstorageFullControl => "https://www.googleapis.com/auth/devstorage.full_control", + Scope::CloudPlatformReadOnly => "https://www.googleapis.com/auth/cloud-platform.read-only", } } } @@ -400,14 +404,14 @@ pub struct Object { /// The link to this object. #[serde(rename="selfLink")] pub self_link: Option, - /// The creation or modification time of the object in RFC 3339 format. For buckets with versioning enabled, changing an object's metadata does not change this property. + /// The modification time of the object metadata in RFC 3339 format. pub updated: Option, /// Content-Type of the object data. #[serde(rename="contentType")] pub content_type: Option, - /// Content-Language of the object data. - #[serde(rename="contentLanguage")] - pub content_language: Option, + /// The creation time of the object in RFC 3339 format. + #[serde(rename="timeCreated")] + pub time_created: Option, /// The content generation of this object. Used for object versioning. pub generation: Option, /// Number of underlying components that make up this object. Components are accumulated by compose operations. @@ -435,6 +439,9 @@ pub struct Object { pub time_deleted: Option, /// The kind of item this is. For objects, this is always storage#object. pub kind: Option, + /// Content-Language of the object data. + #[serde(rename="contentLanguage")] + pub content_language: Option, /// The name of this object. Required if not specified by URL parameter. pub name: Option, /// MD5 hash of the data; encoded using base64. For more information about using the MD5 hash, see Hashes and ETags: Best Practices. @@ -600,7 +607,9 @@ impl Part for ComposeRequestSourceObjects {} pub struct Bucket { /// The bucket's website configuration. pub website: Option, - /// Creation time of the bucket in RFC 3339 format. + /// The modification time of the bucket in RFC 3339 format. + pub updated: Option, + /// The creation time of the bucket in RFC 3339 format. #[serde(rename="timeCreated")] pub time_created: Option, /// The bucket's versioning configuration. @@ -1323,9 +1332,9 @@ impl<'a, C, A> ObjectMethods<'a, C, A> { /// /// * `request` - No description provided. /// * `sourceBucket` - Name of the bucket in which to find the source object. - /// * `sourceObject` - Name of the source object. + /// * `sourceObject` - Name of the source object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts. /// * `destinationBucket` - Name of the bucket in which to store the new object. Overrides the provided object metadata's bucket value, if any. - /// * `destinationObject` - Name of the new object. Required when the object metadata is not otherwise provided. Overrides the object metadata's name value, if any. + /// * `destinationObject` - Name of the new object. Required when the object metadata is not otherwise provided. Overrides the object metadata's name value, if any. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts. pub fn rewrite(&self, request: Object, source_bucket: &str, source_object: &str, destination_bucket: &str, destination_object: &str) -> ObjectRewriteCall<'a, C, A> { ObjectRewriteCall { hub: self.hub, @@ -1360,7 +1369,7 @@ impl<'a, C, A> ObjectMethods<'a, C, A> { /// # Arguments /// /// * `bucket` - Name of the bucket in which the object resides. - /// * `object` - Name of the object. + /// * `object` - Name of the object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts. pub fn get(&self, bucket: &str, object: &str) -> ObjectGetCall<'a, C, A> { ObjectGetCall { hub: self.hub, @@ -1386,7 +1395,7 @@ impl<'a, C, A> ObjectMethods<'a, C, A> { /// /// * `request` - No description provided. /// * `bucket` - Name of the bucket in which the object resides. - /// * `object` - Name of the object. + /// * `object` - Name of the object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts. pub fn update(&self, request: Object, bucket: &str, object: &str) -> ObjectUpdateCall<'a, C, A> { ObjectUpdateCall { hub: self.hub, @@ -1466,7 +1475,7 @@ impl<'a, C, A> ObjectMethods<'a, C, A> { /// /// * `request` - No description provided. /// * `destinationBucket` - Name of the bucket in which to store the new object. - /// * `destinationObject` - Name of the new object. + /// * `destinationObject` - Name of the new object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts. pub fn compose(&self, request: ComposeRequest, destination_bucket: &str, destination_object: &str) -> ObjectComposeCall<'a, C, A> { ObjectComposeCall { hub: self.hub, @@ -1489,7 +1498,7 @@ impl<'a, C, A> ObjectMethods<'a, C, A> { /// # Arguments /// /// * `bucket` - Name of the bucket in which the object resides. - /// * `object` - Name of the object. + /// * `object` - Name of the object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts. pub fn delete(&self, bucket: &str, object: &str) -> ObjectDeleteCall<'a, C, A> { ObjectDeleteCall { hub: self.hub, @@ -1537,8 +1546,8 @@ impl<'a, C, A> ObjectMethods<'a, C, A> { /// /// * `request` - No description provided. /// * `sourceBucket` - Name of the bucket in which to find the source object. - /// * `sourceObject` - Name of the source object. - /// * `destinationBucket` - Name of the bucket in which to store the new object. Overrides the provided object metadata's bucket value, if any. + /// * `sourceObject` - Name of the source object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts. + /// * `destinationBucket` - Name of the bucket in which to store the new object. Overrides the provided object metadata's bucket value, if any.For information about how to URL encode object names to be path safe, see Encoding URI Path Parts. /// * `destinationObject` - Name of the new object. Required when the object metadata is not otherwise provided. Overrides the object metadata's name value, if any. pub fn copy(&self, request: Object, source_bucket: &str, source_object: &str, destination_bucket: &str, destination_object: &str) -> ObjectCopyCall<'a, C, A> { ObjectCopyCall { @@ -1573,7 +1582,7 @@ impl<'a, C, A> ObjectMethods<'a, C, A> { /// /// * `request` - No description provided. /// * `bucket` - Name of the bucket in which the object resides. - /// * `object` - Name of the object. + /// * `object` - Name of the object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts. pub fn patch(&self, request: Object, bucket: &str, object: &str) -> ObjectPatchCall<'a, C, A> { ObjectPatchCall { hub: self.hub, @@ -1642,7 +1651,7 @@ impl<'a, C, A> ObjectAccessControlMethods<'a, C, A> { /// /// * `request` - No description provided. /// * `bucket` - Name of a bucket. - /// * `object` - Name of the object. + /// * `object` - Name of the object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts. pub fn insert(&self, request: ObjectAccessControl, bucket: &str, object: &str) -> ObjectAccessControlInsertCall<'a, C, A> { ObjectAccessControlInsertCall { hub: self.hub, @@ -1664,7 +1673,7 @@ impl<'a, C, A> ObjectAccessControlMethods<'a, C, A> { /// /// * `request` - No description provided. /// * `bucket` - Name of a bucket. - /// * `object` - Name of the object. + /// * `object` - Name of the object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts. /// * `entity` - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers. pub fn patch(&self, request: ObjectAccessControl, bucket: &str, object: &str, entity: &str) -> ObjectAccessControlPatchCall<'a, C, A> { ObjectAccessControlPatchCall { @@ -1687,7 +1696,7 @@ impl<'a, C, A> ObjectAccessControlMethods<'a, C, A> { /// # Arguments /// /// * `bucket` - Name of a bucket. - /// * `object` - Name of the object. + /// * `object` - Name of the object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts. pub fn list(&self, bucket: &str, object: &str) -> ObjectAccessControlListCall<'a, C, A> { ObjectAccessControlListCall { hub: self.hub, @@ -1707,7 +1716,7 @@ impl<'a, C, A> ObjectAccessControlMethods<'a, C, A> { /// # Arguments /// /// * `bucket` - Name of a bucket. - /// * `object` - Name of the object. + /// * `object` - Name of the object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts. /// * `entity` - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers. pub fn delete(&self, bucket: &str, object: &str, entity: &str) -> ObjectAccessControlDeleteCall<'a, C, A> { ObjectAccessControlDeleteCall { @@ -1729,7 +1738,7 @@ impl<'a, C, A> ObjectAccessControlMethods<'a, C, A> { /// # Arguments /// /// * `bucket` - Name of a bucket. - /// * `object` - Name of the object. + /// * `object` - Name of the object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts. /// * `entity` - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers. pub fn get(&self, bucket: &str, object: &str, entity: &str) -> ObjectAccessControlGetCall<'a, C, A> { ObjectAccessControlGetCall { @@ -1752,7 +1761,7 @@ impl<'a, C, A> ObjectAccessControlMethods<'a, C, A> { /// /// * `request` - No description provided. /// * `bucket` - Name of a bucket. - /// * `object` - Name of the object. + /// * `object` - Name of the object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts. /// * `entity` - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers. pub fn update(&self, request: ObjectAccessControl, bucket: &str, object: &str, entity: &str) -> ObjectAccessControlUpdateCall<'a, C, A> { ObjectAccessControlUpdateCall { @@ -5573,7 +5582,7 @@ impl<'a, C, A> ObjectRewriteCall<'a, C, A> where C: BorrowMut, A: self._source_bucket = new_value.to_string(); self } - /// Name of the source object. + /// Name of the source object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts. /// /// Sets the *source object* path property to the given value. /// @@ -5593,7 +5602,7 @@ impl<'a, C, A> ObjectRewriteCall<'a, C, A> where C: BorrowMut, A: self._destination_bucket = new_value.to_string(); self } - /// Name of the new object. Required when the object metadata is not otherwise provided. Overrides the object metadata's name value, if any. + /// Name of the new object. Required when the object metadata is not otherwise provided. Overrides the object metadata's name value, if any. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts. /// /// Sets the *destination object* path property to the given value. /// @@ -5983,7 +5992,7 @@ impl<'a, C, A> ObjectGetCall<'a, C, A> where C: BorrowMut, A: oau self._bucket = new_value.to_string(); self } - /// Name of the object. + /// Name of the object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts. /// /// Sets the *object* path property to the given value. /// @@ -6360,7 +6369,7 @@ impl<'a, C, A> ObjectUpdateCall<'a, C, A> where C: BorrowMut, A: self._bucket = new_value.to_string(); self } - /// Name of the object. + /// Name of the object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts. /// /// Sets the *object* path property to the given value. /// @@ -7161,10 +7170,10 @@ impl<'a, C, A> ObjectInsertCall<'a, C, A> where C: BorrowMut, A: self.doit(stream, mime_type, "simple") } /// Upload media in a resumable fashion. - /// Even if the upload fails or is interrupted, it can be resumed for a + /// Even if the upload fails or is interrupted, it can be resumed for a /// certain amount of time as the server maintains state temporarily. /// - /// The delegate will be asked for an `upload_url()`, and if not provided, will be asked to store an upload URL + /// The delegate will be asked for an `upload_url()`, and if not provided, will be asked to store an upload URL /// that was provided by the server, using `store_upload_url(...)`. The upload will be done in chunks, the delegate /// may specify the `chunk_size()` and may cancel the operation before each chunk is uploaded, using /// `cancel_chunk_upload(...)`. @@ -7210,7 +7219,7 @@ impl<'a, C, A> ObjectInsertCall<'a, C, A> where C: BorrowMut, A: self._predefined_acl = Some(new_value.to_string()); self } - /// Name of the object. Required when the object metadata is not otherwise provided. Overrides the object metadata's name value, if any. + /// Name of the object. Required when the object metadata is not otherwise provided. Overrides the object metadata's name value, if any. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts. /// /// Sets the *name* query property to the given value. pub fn name(mut self, new_value: &str) -> ObjectInsertCall<'a, C, A> { @@ -7557,7 +7566,7 @@ impl<'a, C, A> ObjectComposeCall<'a, C, A> where C: BorrowMut, A: self._destination_bucket = new_value.to_string(); self } - /// Name of the new object. + /// Name of the new object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts. /// /// Sets the *destination object* path property to the given value. /// @@ -7840,7 +7849,7 @@ impl<'a, C, A> ObjectDeleteCall<'a, C, A> where C: BorrowMut, A: self._bucket = new_value.to_string(); self } - /// Name of the object. + /// Name of the object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts. /// /// Sets the *object* path property to the given value. /// @@ -8542,7 +8551,7 @@ impl<'a, C, A> ObjectCopyCall<'a, C, A> where C: BorrowMut, A: oa self._source_bucket = new_value.to_string(); self } - /// Name of the source object. + /// Name of the source object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts. /// /// Sets the *source object* path property to the given value. /// @@ -8552,7 +8561,7 @@ impl<'a, C, A> ObjectCopyCall<'a, C, A> where C: BorrowMut, A: oa self._source_object = new_value.to_string(); self } - /// Name of the bucket in which to store the new object. Overrides the provided object metadata's bucket value, if any. + /// Name of the bucket in which to store the new object. Overrides the provided object metadata's bucket value, if any.For information about how to URL encode object names to be path safe, see Encoding URI Path Parts. /// /// Sets the *destination bucket* path property to the given value. /// @@ -8953,7 +8962,7 @@ impl<'a, C, A> ObjectPatchCall<'a, C, A> where C: BorrowMut, A: o self._bucket = new_value.to_string(); self } - /// Name of the object. + /// Name of the object. For information about how to URL encode object names to be path safe, see Encoding URI Path Parts. /// /// Sets the *object* path property to the given value. /// @@ -9286,7 +9295,7 @@ impl<'a, C, A> ObjectAccessControlInsertCall<'a, C, A> where C: BorrowMut ObjectAccessControlPatchCall<'a, C, A> where C: BorrowMut ObjectAccessControlListCall<'a, C, A> where C: BorrowMut ObjectAccessControlDeleteCall<'a, C, A> where C: BorrowMut ObjectAccessControlGetCall<'a, C, A> where C: BorrowMut ObjectAccessControlUpdateCall<'a, C, A> where C: BorrowMut"] +description = "A complete library to interact with storagetransfer (protocol v1)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/storagetransfer1-cli" +homepage = "https://cloud.google.com/storage/transfer" +documentation = "http://byron.github.io/google-apis-rs/google_storagetransfer1_cli" +license = "MIT" +keywords = ["storagetransfer", "google", "cli"] + +[[bin]] +name = "storagetransfer1" + +[dependencies] +hyper = ">= 0.6.8" +mime = "0.1.0" +serde = ">= 0.6.0" +serde_json = ">= 0.6.0" +yup-oauth2 = "*" +strsim = "*" +yup-hyper-mock = ">=1.0.0" +clap = ">= 1.0.3" + +[build-dependencies] +syntex = { version = "*" } +serde_codegen = { version = "*" } + + +[dependencies.google-storagetransfer1] +path = "../storagetransfer1" diff --git a/gen/storagetransfer1-cli/LICENSE.md b/gen/storagetransfer1-cli/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/storagetransfer1-cli/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/storagetransfer1-cli/README.md b/gen/storagetransfer1-cli/README.md new file mode 100644 index 0000000000..42b7e51427 --- /dev/null +++ b/gen/storagetransfer1-cli/README.md @@ -0,0 +1,127 @@ + +The `storagetransfer1` command-line interface *(CLI)* allows to use most features of the *Google storagetransfer* service from the comfort of your terminal. + +By default all output is printed to standard out, but flags can be set to direct it into a file independent of your shell's +capabilities. Errors will be printed to standard error, and cause the program's exit code to be non-zero. + +If data-structures are requested, these will be returned as pretty-printed JSON, to be useful as input to other tools. + +Everything else about the *storagetransfer* API can be found at the +[official documentation site](https://cloud.google.com/storage/transfer). + +# Downloads + +You can download the pre-compiled 64bit binaries for the following platforms: + +* ![icon](http://megaicons.net/static/img/icons_sizes/6/140/16/ubuntu-icon.png) [ubuntu](http://dl.byronimo.de/google.rs/cli/0.3.2/ubuntu/storagetransfer1.tar.gz) +* ![icon](http://hydra-media.cursecdn.com/wow.gamepedia.com/a/a2/Apple-icon-16x16.png?version=25ddd67ac3dd3b634478e3978b76cb74) [osx](http://dl.byronimo.de/google.rs/cli/0.3.2/osx/storagetransfer1.tar.gz) + +Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/storagetransfer1-cli). + +# Usage + +This documentation was generated from the *storagetransfer* API at revision *20150811*. The CLI is at version *0.3.2*. + +```bash +storagetransfer1 [options] + google-service-accounts + get [-p ]... [-o ] + methods + get-google-service-account [-p ]... [-o ] + transfer-jobs + create (-r )... [-p ]... [-o ] + get [-p ]... [-o ] + list [-p ]... [-o ] + patch (-r )... [-p ]... [-o ] + transfer-operations + cancel [-p ]... [-o ] + delete [-p ]... [-o ] + get [-p ]... [-o ] + list [-p ]... [-o ] + pause (-r )... [-p ]... [-o ] + resume (-r )... [-p ]... [-o ] + storagetransfer1 --help + +Configuration: + [--scope ]... + Specify the authentication a method should be executed in. Each scope + requires the user to grant this application permission to use it. + If unset, it defaults to the shortest scope url for a particular method. + --config-dir + A directory into which we will store our persistent data. Defaults to + a user-writable directory that we will create during the first invocation. + [default: ~/.google-service-cli] + --debug + Output all server communication to standard error. `tx` and `rx` are placed + into the same stream. + --debug-auth + Output all communication related to authentication to standard error. `tx` + and `rx` are placed into the same stream. + +``` + +# Configuration + +The program will store all persistent data in the `~/.google-service-cli` directory in *JSON* files prefixed with `storagetransfer1-`. You can change the directory used to store configuration with the `--config-dir` flag on a per-invocation basis. + +More information about the various kinds of persistent data are given in the following paragraphs. + +# Authentication + +Most APIs require a user to authenticate any request. If this is the case, the [scope][scopes] determines the +set of permissions granted. The granularity of these is usually no more than *read-only* or *full-access*. + +If not set, the system will automatically select the smallest feasible scope, e.g. when invoking a +method that is read-only, it will ask only for a read-only scope. +You may use the `--scope` flag to specify a scope directly. +All applicable scopes are documented in the respective method's CLI documentation. + +The first time a scope is used, the user is asked for permission. Follow the instructions given +by the CLI to grant permissions, or to decline. + +If a scope was authenticated by the user, the respective information will be stored as *JSON* in the configuration +directory, e.g. `~/.google-service-cli/storagetransfer1-token-.json`. No manual management of these tokens +is necessary. + +To revoke granted authentication, please refer to the [official documentation][revoke-access]. + +# Application Secrets + +In order to allow any application to use Google services, it will need to be registered using the +[Google Developer Console][google-dev-console]. APIs the application may use are then enabled for it +one by one. Most APIs can be used for free and have a daily quota. + +To allow more comfortable usage of the CLI without forcing anyone to register an own application, the CLI +comes with a default application secret that is configured accordingly. This also means that heavy usage +all around the world may deplete the daily quota. + +You can workaround this limitation by putting your own secrets file at this location: +`~/.google-service-cli/storagetransfer1-secret.json`, assuming that the required *storagetransfer* API +was enabled for it. Such a secret file can be downloaded in the *Google Developer Console* at +*APIs & auth -> Credentials -> Download JSON* and used as is. + +Learn more about how to setup Google projects and enable APIs using the [official documentation][google-project-new]. + + +# Debugging + +Even though the CLI does its best to provide usable error messages, sometimes it might be desirable to know +what exactly led to a particular issue. This is done by allowing all client-server communication to be +output to standard error *as-is*. + +The `--debug` flag will print all client-server communication to standard error, whereas the `--debug-auth` flag +will cause all communication related to authentication to standard error. +If the `--debug` flag is set, error-results will be debug-printed, possibly yielding more information about the +issue at hand. + +You may consider redirecting standard error into a file for ease of use, e.g. `storagetransfer1 --debug [options] 2>debug.txt`. + + +[scopes]: https://developers.google.com/+/api/oauth#scopes +[revoke-access]: http://webapps.stackexchange.com/a/30849 +[google-dev-console]: https://console.developers.google.com/ +[google-project-new]: https://developers.google.com/console/help/new/ \ No newline at end of file diff --git a/gen/storagetransfer1-cli/mkdocs.yml b/gen/storagetransfer1-cli/mkdocs.yml new file mode 100644 index 0000000000..e111f9f51c --- /dev/null +++ b/gen/storagetransfer1-cli/mkdocs.yml @@ -0,0 +1,28 @@ +site_name: storagetransfer v0.3.2+20150811 +site_url: http://byron.github.io/google-apis-rs/google-storagetransfer1-cli +site_description: Write integrating applications with bcore + +repo_url: https://github.com/Byron/google-apis-rs/tree/master/gen/storagetransfer1-cli + +docs_dir: docs +site_dir: build_html + +pages: +- ['index.md', 'Home'] +- ['google-service-accounts_get.md', 'Google Service Accounts', 'Get'] +- ['methods_get-google-service-account.md', 'Methods', 'Get Google Service Account'] +- ['transfer-jobs_create.md', 'Transfer Jobs', 'Create'] +- ['transfer-jobs_get.md', 'Transfer Jobs', 'Get'] +- ['transfer-jobs_list.md', 'Transfer Jobs', 'List'] +- ['transfer-jobs_patch.md', 'Transfer Jobs', 'Patch'] +- ['transfer-operations_cancel.md', 'Transfer Operations', 'Cancel'] +- ['transfer-operations_delete.md', 'Transfer Operations', 'Delete'] +- ['transfer-operations_get.md', 'Transfer Operations', 'Get'] +- ['transfer-operations_list.md', 'Transfer Operations', 'List'] +- ['transfer-operations_pause.md', 'Transfer Operations', 'Pause'] +- ['transfer-operations_resume.md', 'Transfer Operations', 'Resume'] + +theme: readthedocs + +copyright: Copyright © 2015, `Sebastian Thiel` + diff --git a/gen/storagetransfer1-cli/src/cmn.rs b/gen/storagetransfer1-cli/src/cmn.rs new file mode 100644 index 0000000000..8358f156fa --- /dev/null +++ b/gen/storagetransfer1-cli/src/cmn.rs @@ -0,0 +1,721 @@ +// COPY OF 'src/rust/cli/cmn.rs' +// DO NOT EDIT +use oauth2::{ApplicationSecret, ConsoleApplicationSecret, TokenStorage, Token}; +use serde_json as json; +use serde_json::value::Value; +use mime::Mime; +use clap::{App, SubCommand}; +use strsim; + +use std::fs; +use std::env; +use std::io; +use std::fmt; +use std::path::{Path, PathBuf}; +use std::str::FromStr; +use std::string::ToString; +use std::io::{Write, Read, stdout}; + +use std::default::Default; + +const FIELD_SEP: char = '.'; + + +pub enum ComplexType { + Pod, + Vec, + Map, +} + + // Null, + // Bool(bool), + // I64(i64), + // U64(u64), + // F64(f64), + // String(String), + +pub enum JsonType { + Boolean, + Int, + Uint, + Float, + String, +} + +pub struct JsonTypeInfo { + pub jtype: JsonType, + pub ctype: ComplexType, +} + +// Based on @erickt user comment. Thanks for the idea ! +// Remove all keys whose values are null from given value (changed in place) +pub fn remove_json_null_values(value: &mut Value) { + match *value { + Value::Object(ref mut map) => { + let mut for_removal = Vec::new(); + + for (key, mut value) in map.iter_mut() { + if value.is_null() { + for_removal.push(key.clone()); + } else { + remove_json_null_values(&mut value); + } + } + + for key in &for_removal { + map.remove(key); + } + } + _ => {} + } +} + +fn did_you_mean<'a>(v: &str, possible_values: &[&'a str]) -> Option<&'a str> { + + let mut candidate: Option<(f64, &str)> = None; + for pv in possible_values { + let confidence = strsim::jaro_winkler(v, pv); + if confidence > 0.8 && (candidate.is_none() || (candidate.as_ref().unwrap().0 < confidence)) { + candidate = Some((confidence, pv)); + } + } + match candidate { + None => None, + Some((_, candidate)) => Some(candidate), + } +} + +pub enum CallType { + Upload(UploadProtocol), + Standard, +} + +arg_enum!{ + pub enum UploadProtocol { + Simple, + Resumable + } +} + +impl AsRef for UploadProtocol { + fn as_ref(&self) -> &str { + match *self { + UploadProtocol::Simple => "simple", + UploadProtocol::Resumable => "resumable" + } + } +} + +impl AsRef for CallType { + fn as_ref(&self) -> &str { + match *self { + CallType::Upload(ref proto) => proto.as_ref(), + CallType::Standard => "standard-request" + } + } +} + +#[derive(Clone, Default)] +pub struct FieldCursor(Vec); + +impl ToString for FieldCursor { + fn to_string(&self) -> String { + self.0.join(".") + } +} + +impl From<&'static str> for FieldCursor { + fn from(value: &'static str) -> FieldCursor { + let mut res = FieldCursor::default(); + res.set(value).unwrap(); + res + } +} + +impl FieldCursor { + pub fn set(&mut self, value: &str) -> Result<(), CLIError> { + if value.len() == 0 { + return Err(CLIError::Field(FieldError::Empty)) + } + + let mut first_is_field_sep = false; + let mut char_count: usize = 0; + let mut last_c = FIELD_SEP; + let mut num_conscutive_field_seps = 0; + + let mut field = String::new(); + let mut fields = self.0.clone(); + + let push_field = |fs: &mut Vec, f: &mut String| { + if f.len() > 0 { + fs.push(f.clone()); + f.truncate(0); + } + }; + + for (cid, c) in value.chars().enumerate() { + char_count += 1; + + if c == FIELD_SEP { + if cid == 0 { + first_is_field_sep = true; + } + num_conscutive_field_seps += 1; + if cid > 0 && last_c == FIELD_SEP { + if fields.pop().is_none() { + return Err(CLIError::Field(FieldError::PopOnEmpty(value.to_string()))) + } + } else { + push_field(&mut fields, &mut field); + } + } else { + num_conscutive_field_seps = 0; + if cid == 1 { + if first_is_field_sep { + fields.truncate(0); + } + } + field.push(c); + } + + last_c = c; + } + + push_field(&mut fields, &mut field); + + if char_count == 1 && first_is_field_sep { + fields.truncate(0); + } + if char_count > 1 && num_conscutive_field_seps == 1 { + return Err(CLIError::Field(FieldError::TrailingFieldSep(value.to_string()))) + } + + self.0 = fields; + Ok(()) + } + + pub fn did_you_mean(value: &str, possible_values: &[&str]) -> Option { + if value.len() == 0 { + return None + } + + let mut last_c = FIELD_SEP; + + let mut field = String::new(); + let mut output = String::new(); + + let push_field = |fs: &mut String, f: &mut String| { + if f.len() > 0 { + fs.push_str( + match did_you_mean(&f, possible_values) { + Some(candidate) => candidate, + None => &f, + }); + f.truncate(0); + } + }; + + for (cid, c) in value.chars().enumerate() { + if c == FIELD_SEP { + if last_c != FIELD_SEP { + push_field(&mut output, &mut field); + } + output.push(c); + } else { + field.push(c); + } + + last_c = c; + } + + push_field(&mut output, &mut field); + + if &output == value { + None + } else { + Some(output) + } + } + + pub fn set_json_value(&self, mut object: &mut Value, + value: &str, type_info: JsonTypeInfo, + err: &mut InvalidOptionsError, + orig_cursor: &FieldCursor) { + assert!(self.0.len() > 0); + + for field in &self.0[..self.0.len()-1] { + let tmp = object; + object = + match *tmp { + Value::Object(ref mut mapping) => { + mapping.entry(field.to_owned()).or_insert( + Value::Object(Default::default()) + ) + }, + _ => panic!("We don't expect non-object Values here ...") + }; + } + + match *object { + Value::Object(ref mut mapping) => { + let field = &self.0[self.0.len()-1]; + let to_jval = + |value: &str, jtype: JsonType, err: &mut InvalidOptionsError| + -> Value { + match jtype { + JsonType::Boolean => + Value::Bool(arg_from_str(value, err, &field, "boolean")), + JsonType::Int => + Value::I64(arg_from_str(value, err, &field, "int")), + JsonType::Uint => + Value::U64(arg_from_str(value, err, &field, "uint")), + JsonType::Float => + Value::F64(arg_from_str(value, err, &field, "float")), + JsonType::String => + Value::String(value.to_owned()), + } + }; + + match type_info.ctype { + ComplexType::Pod => { + if mapping.insert(field.to_owned(), to_jval(value, type_info.jtype, err)).is_some() { + err.issues.push(CLIError::Field(FieldError::Duplicate(orig_cursor.to_string()))); + } + }, + ComplexType::Vec => { + match *mapping.entry(field.to_owned()) + .or_insert(Value::Array(Default::default())) { + Value::Array(ref mut values) => values.push(to_jval(value, type_info.jtype, err)), + _ => unreachable!() + } + }, + ComplexType::Map => { + let (key, value) = parse_kv_arg(value, err, true); + let jval = to_jval(value.unwrap_or(""), type_info.jtype, err); + + match *mapping.entry(field.to_owned()) + .or_insert(Value::Object(Default::default())) { + Value::Object(ref mut value_map) => { + if value_map.insert(key.to_owned(), jval).is_some() { + err.issues.push(CLIError::Field(FieldError::Duplicate(orig_cursor.to_string()))); + } + } + _ => unreachable!() + } + } + } + }, + _ => unreachable!() + } + } + + pub fn num_fields(&self) -> usize { + self.0.len() + } +} + +pub fn parse_kv_arg<'a>(kv: &'a str, err: &mut InvalidOptionsError, for_hashmap: bool) + -> (&'a str, Option<&'a str>) { + let mut add_err = || err.issues.push(CLIError::InvalidKeyValueSyntax(kv.to_string(),for_hashmap)); + match kv.find('=') { + None => { + add_err(); + return (kv, None) + }, + Some(pos) => { + let key = &kv[..pos]; + if kv.len() <= pos + 1 { + add_err(); + return (key, Some("")) + } + (key, Some(&kv[pos+1..])) + } + } +} + +pub fn calltype_from_str(name: &str, valid_protocols: Vec, err: &mut InvalidOptionsError) -> CallType { + CallType::Upload( + match UploadProtocol::from_str(name) { + Ok(up) => up, + Err(msg) => { + err.issues.push(CLIError::InvalidUploadProtocol(name.to_string(), valid_protocols)); + UploadProtocol::Simple + } + }) +} + +pub fn input_file_from_opts(file_path: &str, err: &mut InvalidOptionsError) -> Option { + match fs::File::open(file_path) { + Ok(f) => Some(f), + Err(io_err) => { + err.issues.push(CLIError::Input(InputError::IOError((file_path.to_string(), io_err)))); + None + } + } +} + +pub fn input_mime_from_opts(mime: &str, err: &mut InvalidOptionsError) -> Option { + match mime.parse() { + Ok(m) => Some(m), + Err(_) => { + err.issues.push(CLIError::Input(InputError::Mime(mime.to_string()))); + None + } + } +} + +pub fn writer_from_opts(arg: Option<&str>) -> Result, io::Error> { + let f = arg.unwrap_or("-"); + match f { + "-" => Ok(Box::new(stdout())), + _ => match fs::OpenOptions::new().create(true).write(true).open(f) { + Ok(f) => Ok(Box::new(f)), + Err(io_err) => Err(io_err), + } + } +} + + +pub fn arg_from_str<'a, T>(arg: &str, err: &mut InvalidOptionsError, + arg_name: &'a str, + arg_type: &'a str) -> T + where T: FromStr + Default, + ::Err: fmt::Display { + match FromStr::from_str(arg) { + Err(perr) => { + err.issues.push( + CLIError::ParseError(arg_name.to_owned(), arg_type.to_owned(), arg.to_string(), format!("{}", perr)) + ); + Default::default() + }, + Ok(v) => v, + } +} + +pub struct JsonTokenStorage { + pub program_name: &'static str, + pub db_dir: String, +} + +impl JsonTokenStorage { + fn path(&self, scope_hash: u64) -> PathBuf { + Path::new(&self.db_dir).join(&format!("{}-token-{}.json", self.program_name, scope_hash)) + } +} + +impl TokenStorage for JsonTokenStorage { + type Error = json::Error; + + // NOTE: logging might be interesting, currently we swallow all errors + fn set(&mut self, scope_hash: u64, _: &Vec<&str>, token: Option) -> Result<(), json::Error> { + match token { + None => { + match fs::remove_file(self.path(scope_hash)) { + Err(err) => + match err.kind() { + io::ErrorKind::NotFound => Ok(()), + _ => Err(json::Error::IoError(err)) + }, + Ok(_) => Ok(()), + } + } + Some(token) => { + match fs::OpenOptions::new().create(true).write(true).open(&self.path(scope_hash)) { + Ok(mut f) => { + match json::to_writer_pretty(&mut f, &token) { + Ok(_) => Ok(()), + Err(serde_err) => Err(serde_err), + } + }, + Err(io_err) => Err(json::Error::IoError(io_err)) + } + } + } + } + + fn get(&self, scope_hash: u64, _: &Vec<&str>) -> Result, json::Error> { + match fs::File::open(&self.path(scope_hash)) { + Ok(mut f) => { + match json::de::from_reader(f) { + Ok(token) => Ok(Some(token)), + Err(err) => Err(err), + } + }, + Err(io_err) => { + match io_err.kind() { + io::ErrorKind::NotFound => Ok(None), + _ => Err(json::Error::IoError(io_err)) + } + } + } + } +} + + +#[derive(Debug)] +pub enum ApplicationSecretError { + DecoderError((String, json::Error)), + FormatError(String), +} + +impl fmt::Display for ApplicationSecretError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + ApplicationSecretError::DecoderError((ref path, ref err)) + => writeln!(f, "Could not decode file at '{}' with error: {}.", + path, err), + ApplicationSecretError::FormatError(ref path) + => writeln!(f, "'installed' field is unset in secret file at '{}'.", + path), + } + } +} + +#[derive(Debug)] +pub enum ConfigurationError { + DirectoryCreationFailed((String, io::Error)), + DirectoryUnset, + HomeExpansionFailed(String), + Secret(ApplicationSecretError), + IOError((String, io::Error)), +} + +impl fmt::Display for ConfigurationError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + ConfigurationError::DirectoryCreationFailed((ref dir, ref err)) + => writeln!(f, "Directory '{}' could not be created with error: {}.", dir, err), + ConfigurationError::DirectoryUnset + => writeln!(f, "--config-dir was unset or empty."), + ConfigurationError::HomeExpansionFailed(ref dir) + => writeln!(f, "Couldn't find HOME directory of current user, failed to expand '{}'.", dir), + ConfigurationError::Secret(ref err) + => writeln!(f, "Secret -> {}", err), + ConfigurationError::IOError((ref path, ref err)) + => writeln!(f, "IO operation failed on path '{}' with error: {}.", path, err), + } + } +} + +#[derive(Debug)] +pub enum InputError { + IOError((String, io::Error)), + Mime(String), +} + +impl fmt::Display for InputError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + InputError::IOError((ref file_path, ref io_err)) + => writeln!(f, "Failed to open '{}' for reading with error: {}.", file_path, io_err), + InputError::Mime(ref mime) + => writeln!(f, "'{}' is not a known mime-type.", mime), + } + } +} + +#[derive(Debug)] +pub enum FieldError { + PopOnEmpty(String), + TrailingFieldSep(String), + Unknown(String, Option, Option), + Duplicate(String), + Empty, +} + + +impl fmt::Display for FieldError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + FieldError::PopOnEmpty(ref field) + => writeln!(f, "'{}': Cannot move up on empty field cursor.", field), + FieldError::TrailingFieldSep(ref field) + => writeln!(f, "'{}': Single field separator may not be last character.", field), + FieldError::Unknown(ref field, ref suggestion, ref value) => { + let suffix = + match *suggestion { + Some(ref s) => { + let kv = + match *value { + Some(ref v) => format!("{}={}", s, v), + None => s.clone(), + }; + format!(" Did you mean '{}' ?", kv) + }, + None => String::new(), + }; + writeln!(f, "Field '{}' does not exist.{}", field, suffix) + }, + FieldError::Duplicate(ref cursor) + => writeln!(f, "Value at '{}' was already set", cursor), + FieldError::Empty + => writeln!(f, "Field names must not be empty."), + } + } +} + + +#[derive(Debug)] +pub enum CLIError { + Configuration(ConfigurationError), + ParseError(String, String, String, String), + UnknownParameter(String, Vec<&'static str>), + InvalidUploadProtocol(String, Vec), + InvalidKeyValueSyntax(String, bool), + Input(InputError), + Field(FieldError), + MissingCommandError, + MissingMethodError(String), +} + +impl fmt::Display for CLIError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + CLIError::Configuration(ref err) => write!(f, "Configuration -> {}", err), + CLIError::Input(ref err) => write!(f, "Input -> {}", err), + CLIError::Field(ref err) => write!(f, "Field -> {}", err), + CLIError::InvalidUploadProtocol(ref proto_name, ref valid_names) + => writeln!(f, "'{}' is not a valid upload protocol. Choose from one of {}.", proto_name, valid_names.join(", ")), + CLIError::ParseError(ref arg_name, ref type_name, ref value, ref err_desc) + => writeln!(f, "Failed to parse argument '{}' with value '{}' as {} with error: {}.", + arg_name, value, type_name, err_desc), + CLIError::UnknownParameter(ref param_name, ref possible_values) => { + let mut suffix = + match did_you_mean(param_name, &possible_values) { + Some(v) => format!(" Did you mean '{}' ?", v), + None => String::new(), + }; + write!(f, "Parameter '{}' is unknown.{}\n", param_name, suffix) + }, + CLIError::InvalidKeyValueSyntax(ref kv, is_hashmap) => { + let hashmap_info = if is_hashmap { "hashmap " } else { "" }; + writeln!(f, "'{}' does not match {}pattern =.", kv, hashmap_info) + }, + CLIError::MissingCommandError => writeln!(f, "Please specify the main sub-command."), + CLIError::MissingMethodError(ref cmd) => writeln!(f, "Please specify the method to call on the '{}' command.", cmd), + } + } +} + +#[derive(Debug)] +pub struct InvalidOptionsError { + pub issues: Vec, + pub exit_code: i32, +} + +impl fmt::Display for InvalidOptionsError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + for issue in &self.issues { + try!(issue.fmt(f)); + } + Ok(()) + } +} + +impl InvalidOptionsError { + pub fn single(err: CLIError, exit_code: i32) -> InvalidOptionsError { + InvalidOptionsError { + issues: vec![err], + exit_code: exit_code, + } + } + + pub fn new() -> InvalidOptionsError { + InvalidOptionsError { + issues: Vec::new(), + exit_code: 1, + } + } +} + +pub fn assure_config_dir_exists(dir: &str) -> Result { + let trdir = dir.trim(); + if trdir.len() == 0 { + return Err(CLIError::Configuration(ConfigurationError::DirectoryUnset)) + } + + let expanded_config_dir = + if trdir.as_bytes()[0] == b'~' { + match env::var("HOME").ok().or(env::var("UserProfile").ok()) { + None => return Err(CLIError::Configuration(ConfigurationError::HomeExpansionFailed(trdir.to_string()))), + Some(mut user) => { + user.push_str(&trdir[1..]); + user + } + } + } else { + trdir.to_string() + }; + + if let Err(err) = fs::create_dir(&expanded_config_dir) { + if err.kind() != io::ErrorKind::AlreadyExists { + return Err(CLIError::Configuration( + ConfigurationError::DirectoryCreationFailed((expanded_config_dir, err)))) + } + } + + Ok(expanded_config_dir) +} + +pub fn application_secret_from_directory(dir: &str, + secret_basename: &str, + json_console_secret: &str) + -> Result { + let secret_path = Path::new(dir).join(secret_basename); + let secret_str = || secret_path.as_path().to_str().unwrap().to_string(); + let secret_io_error = |io_err: io::Error| { + Err(CLIError::Configuration(ConfigurationError::IOError( + (secret_str(), io_err) + ))) + }; + + for _ in 0..2 { + match fs::File::open(&secret_path) { + Err(mut err) => { + if err.kind() == io::ErrorKind::NotFound { + // Write our built-in one - user may adjust the written file at will + + err = match fs::OpenOptions::new().create(true).write(true).open(&secret_path) { + Err(cfe) => cfe, + Ok(mut f) => { + // Assure we convert 'ugly' json string into pretty one + let console_secret: ConsoleApplicationSecret + = json::from_str(json_console_secret).unwrap(); + match json::to_writer_pretty(&mut f, &console_secret) { + Err(serde_err) => match serde_err { + json::Error::IoError(err) => err, + _ => panic!("Unexpected serde error: {:#?}", serde_err) + }, + Ok(_) => continue, + } + } + }; + // fall through to IO error handling + } + return secret_io_error(err) + }, + Ok(mut f) => { + match json::de::from_reader::<_, ConsoleApplicationSecret>(f) { + Err(json::Error::IoError(err)) => + return secret_io_error(err), + Err(json_err) => + return Err(CLIError::Configuration( + ConfigurationError::Secret( + ApplicationSecretError::DecoderError( + (secret_str(), json_err) + )))), + Ok(console_secret) => + match console_secret.installed { + Some(secret) => return Ok(secret), + None => return Err( + CLIError::Configuration( + ConfigurationError::Secret( + ApplicationSecretError::FormatError(secret_str()) + ))) + }, + } + } + } + } + unreachable!(); +} diff --git a/gen/storagetransfer1-cli/src/main.rs b/gen/storagetransfer1-cli/src/main.rs new file mode 100644 index 0000000000..5397c03d6f --- /dev/null +++ b/gen/storagetransfer1-cli/src/main.rs @@ -0,0 +1,1428 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/cli/main.rs.mako' +// DO NOT EDIT ! +#![allow(unused_variables, unused_imports, dead_code, unused_mut)] + +#[macro_use] +extern crate clap; +extern crate yup_oauth2 as oauth2; +extern crate yup_hyper_mock as mock; +extern crate serde; +extern crate serde_json; +extern crate hyper; +extern crate mime; +extern crate strsim; +extern crate google_storagetransfer1 as api; + +use std::env; +use std::io::{self, Write}; +use clap::{App, SubCommand, Arg}; + +mod cmn; + +use cmn::{InvalidOptionsError, CLIError, JsonTokenStorage, arg_from_str, writer_from_opts, parse_kv_arg, + input_file_from_opts, input_mime_from_opts, FieldCursor, FieldError, CallType, UploadProtocol, + calltype_from_str, remove_json_null_values, ComplexType, JsonType, JsonTypeInfo}; + +use std::default::Default; +use std::str::FromStr; + +use oauth2::{Authenticator, DefaultAuthenticatorDelegate}; +use serde_json as json; +use clap::ArgMatches; + +enum DoitError { + IoError(String, io::Error), + ApiError(api::Error), +} + +struct Engine<'n, 'a> { + opt: ArgMatches<'n, 'a>, + hub: api::Storagetransfer>, + gp: Vec<&'static str>, + gpm: Vec<(&'static str, &'static str)>, +} + + +impl<'n, 'a> Engine<'n, 'a> { + fn _google_service_accounts_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.google_service_accounts().get(opt.value_of("project-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _methods_get_google_service_account(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.methods().get_google_service_account(); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "project-id" => { + call = call.project_id(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["project-id"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _transfer_jobs_create(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "transfer-spec.object-conditions.max-time-elapsed-since-last-modification" => Some(("transferSpec.objectConditions.maxTimeElapsedSinceLastModification", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "transfer-spec.object-conditions.include-prefixes" => Some(("transferSpec.objectConditions.includePrefixes", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "transfer-spec.object-conditions.exclude-prefixes" => Some(("transferSpec.objectConditions.excludePrefixes", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "transfer-spec.object-conditions.min-time-elapsed-since-last-modification" => Some(("transferSpec.objectConditions.minTimeElapsedSinceLastModification", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "transfer-spec.gcs-data-source.bucket-name" => Some(("transferSpec.gcsDataSource.bucketName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "transfer-spec.http-data-source.list-url" => Some(("transferSpec.httpDataSource.listUrl", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "transfer-spec.transfer-options.overwrite-objects-already-existing-in-sink" => Some(("transferSpec.transferOptions.overwriteObjectsAlreadyExistingInSink", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "transfer-spec.transfer-options.delete-objects-from-source-after-transfer" => Some(("transferSpec.transferOptions.deleteObjectsFromSourceAfterTransfer", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "transfer-spec.transfer-options.delete-objects-unique-in-sink" => Some(("transferSpec.transferOptions.deleteObjectsUniqueInSink", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "transfer-spec.gcs-data-sink.bucket-name" => Some(("transferSpec.gcsDataSink.bucketName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "transfer-spec.aws-s3-data-source.aws-access-key.secret-access-key" => Some(("transferSpec.awsS3DataSource.awsAccessKey.secretAccessKey", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "transfer-spec.aws-s3-data-source.aws-access-key.access-key-id" => Some(("transferSpec.awsS3DataSource.awsAccessKey.accessKeyId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "transfer-spec.aws-s3-data-source.bucket-name" => Some(("transferSpec.awsS3DataSource.bucketName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "status" => Some(("status", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "deletion-time" => Some(("deletionTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "schedule.schedule-start-date.month" => Some(("schedule.scheduleStartDate.month", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "schedule.schedule-start-date.day" => Some(("schedule.scheduleStartDate.day", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "schedule.schedule-start-date.year" => Some(("schedule.scheduleStartDate.year", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "schedule.start-time-of-day.hours" => Some(("schedule.startTimeOfDay.hours", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "schedule.start-time-of-day.seconds" => Some(("schedule.startTimeOfDay.seconds", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "schedule.start-time-of-day.minutes" => Some(("schedule.startTimeOfDay.minutes", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "schedule.start-time-of-day.nanos" => Some(("schedule.startTimeOfDay.nanos", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "schedule.schedule-end-date.month" => Some(("schedule.scheduleEndDate.month", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "schedule.schedule-end-date.day" => Some(("schedule.scheduleEndDate.day", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "schedule.schedule-end-date.year" => Some(("schedule.scheduleEndDate.year", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "project-id" => Some(("projectId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "last-modification-time" => Some(("lastModificationTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "creation-time" => Some(("creationTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "description" => Some(("description", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["access-key-id", "aws-access-key", "aws-s3-data-source", "bucket-name", "creation-time", "day", "delete-objects-from-source-after-transfer", "delete-objects-unique-in-sink", "deletion-time", "description", "exclude-prefixes", "gcs-data-sink", "gcs-data-source", "hours", "http-data-source", "include-prefixes", "last-modification-time", "list-url", "max-time-elapsed-since-last-modification", "min-time-elapsed-since-last-modification", "minutes", "month", "name", "nanos", "object-conditions", "overwrite-objects-already-existing-in-sink", "project-id", "schedule", "schedule-end-date", "schedule-start-date", "seconds", "secret-access-key", "start-time-of-day", "status", "transfer-options", "transfer-spec", "year"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::TransferJob = json::value::from_value(object).unwrap(); + let mut call = self.hub.transfer_jobs().create(request); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _transfer_jobs_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.transfer_jobs().get(opt.value_of("job-name").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "project-id" => { + call = call.project_id(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["project-id"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _transfer_jobs_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.transfer_jobs().list(); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "page-size" => { + call = call.page_size(arg_from_str(value.unwrap_or("-0"), err, "page-size", "integer")); + }, + "filter" => { + call = call.filter(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["filter", "page-token", "page-size"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _transfer_jobs_patch(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "project-id" => Some(("projectId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "update-transfer-job-field-mask" => Some(("updateTransferJobFieldMask", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "transfer-job.transfer-spec.object-conditions.max-time-elapsed-since-last-modification" => Some(("transferJob.transferSpec.objectConditions.maxTimeElapsedSinceLastModification", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "transfer-job.transfer-spec.object-conditions.include-prefixes" => Some(("transferJob.transferSpec.objectConditions.includePrefixes", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "transfer-job.transfer-spec.object-conditions.exclude-prefixes" => Some(("transferJob.transferSpec.objectConditions.excludePrefixes", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "transfer-job.transfer-spec.object-conditions.min-time-elapsed-since-last-modification" => Some(("transferJob.transferSpec.objectConditions.minTimeElapsedSinceLastModification", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "transfer-job.transfer-spec.gcs-data-source.bucket-name" => Some(("transferJob.transferSpec.gcsDataSource.bucketName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "transfer-job.transfer-spec.http-data-source.list-url" => Some(("transferJob.transferSpec.httpDataSource.listUrl", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "transfer-job.transfer-spec.transfer-options.overwrite-objects-already-existing-in-sink" => Some(("transferJob.transferSpec.transferOptions.overwriteObjectsAlreadyExistingInSink", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "transfer-job.transfer-spec.transfer-options.delete-objects-from-source-after-transfer" => Some(("transferJob.transferSpec.transferOptions.deleteObjectsFromSourceAfterTransfer", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "transfer-job.transfer-spec.transfer-options.delete-objects-unique-in-sink" => Some(("transferJob.transferSpec.transferOptions.deleteObjectsUniqueInSink", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })), + "transfer-job.transfer-spec.gcs-data-sink.bucket-name" => Some(("transferJob.transferSpec.gcsDataSink.bucketName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "transfer-job.transfer-spec.aws-s3-data-source.aws-access-key.secret-access-key" => Some(("transferJob.transferSpec.awsS3DataSource.awsAccessKey.secretAccessKey", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "transfer-job.transfer-spec.aws-s3-data-source.aws-access-key.access-key-id" => Some(("transferJob.transferSpec.awsS3DataSource.awsAccessKey.accessKeyId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "transfer-job.transfer-spec.aws-s3-data-source.bucket-name" => Some(("transferJob.transferSpec.awsS3DataSource.bucketName", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "transfer-job.status" => Some(("transferJob.status", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "transfer-job.deletion-time" => Some(("transferJob.deletionTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "transfer-job.schedule.schedule-start-date.month" => Some(("transferJob.schedule.scheduleStartDate.month", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "transfer-job.schedule.schedule-start-date.day" => Some(("transferJob.schedule.scheduleStartDate.day", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "transfer-job.schedule.schedule-start-date.year" => Some(("transferJob.schedule.scheduleStartDate.year", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "transfer-job.schedule.start-time-of-day.hours" => Some(("transferJob.schedule.startTimeOfDay.hours", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "transfer-job.schedule.start-time-of-day.seconds" => Some(("transferJob.schedule.startTimeOfDay.seconds", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "transfer-job.schedule.start-time-of-day.minutes" => Some(("transferJob.schedule.startTimeOfDay.minutes", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "transfer-job.schedule.start-time-of-day.nanos" => Some(("transferJob.schedule.startTimeOfDay.nanos", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "transfer-job.schedule.schedule-end-date.month" => Some(("transferJob.schedule.scheduleEndDate.month", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "transfer-job.schedule.schedule-end-date.day" => Some(("transferJob.schedule.scheduleEndDate.day", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "transfer-job.schedule.schedule-end-date.year" => Some(("transferJob.schedule.scheduleEndDate.year", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })), + "transfer-job.project-id" => Some(("transferJob.projectId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "transfer-job.last-modification-time" => Some(("transferJob.lastModificationTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "transfer-job.creation-time" => Some(("transferJob.creationTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "transfer-job.name" => Some(("transferJob.name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "transfer-job.description" => Some(("transferJob.description", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["access-key-id", "aws-access-key", "aws-s3-data-source", "bucket-name", "creation-time", "day", "delete-objects-from-source-after-transfer", "delete-objects-unique-in-sink", "deletion-time", "description", "exclude-prefixes", "gcs-data-sink", "gcs-data-source", "hours", "http-data-source", "include-prefixes", "last-modification-time", "list-url", "max-time-elapsed-since-last-modification", "min-time-elapsed-since-last-modification", "minutes", "month", "name", "nanos", "object-conditions", "overwrite-objects-already-existing-in-sink", "project-id", "schedule", "schedule-end-date", "schedule-start-date", "seconds", "secret-access-key", "start-time-of-day", "status", "transfer-job", "transfer-options", "transfer-spec", "update-transfer-job-field-mask", "year"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::UpdateTransferJobRequest = json::value::from_value(object).unwrap(); + let mut call = self.hub.transfer_jobs().patch(request, opt.value_of("job-name").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _transfer_operations_cancel(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.transfer_operations().cancel(opt.value_of("name").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _transfer_operations_delete(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.transfer_operations().delete(opt.value_of("name").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _transfer_operations_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.transfer_operations().get(opt.value_of("name").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _transfer_operations_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.transfer_operations().list(opt.value_of("name").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "page-size" => { + call = call.page_size(arg_from_str(value.unwrap_or("-0"), err, "page-size", "integer")); + }, + "filter" => { + call = call.filter(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["filter", "page-token", "page-size"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _transfer_operations_pause(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec![]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::PauseTransferOperationRequest = json::value::from_value(object).unwrap(); + let mut call = self.hub.transfer_operations().pause(request, opt.value_of("name").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _transfer_operations_resume(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec![]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::ResumeTransferOperationRequest = json::value::from_value(object).unwrap(); + let mut call = self.hub.transfer_operations().resume(request, opt.value_of("name").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _doit(&self, dry_run: bool) -> Result, Option> { + let mut err = InvalidOptionsError::new(); + let mut call_result: Result<(), DoitError> = Ok(()); + let mut err_opt: Option = None; + match self.opt.subcommand() { + ("google-service-accounts", Some(opt)) => { + match opt.subcommand() { + ("get", Some(opt)) => { + call_result = self._google_service_accounts_get(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("google-service-accounts".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("methods", Some(opt)) => { + match opt.subcommand() { + ("get-google-service-account", Some(opt)) => { + call_result = self._methods_get_google_service_account(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("methods".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("transfer-jobs", Some(opt)) => { + match opt.subcommand() { + ("create", Some(opt)) => { + call_result = self._transfer_jobs_create(opt, dry_run, &mut err); + }, + ("get", Some(opt)) => { + call_result = self._transfer_jobs_get(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._transfer_jobs_list(opt, dry_run, &mut err); + }, + ("patch", Some(opt)) => { + call_result = self._transfer_jobs_patch(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("transfer-jobs".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("transfer-operations", Some(opt)) => { + match opt.subcommand() { + ("cancel", Some(opt)) => { + call_result = self._transfer_operations_cancel(opt, dry_run, &mut err); + }, + ("delete", Some(opt)) => { + call_result = self._transfer_operations_delete(opt, dry_run, &mut err); + }, + ("get", Some(opt)) => { + call_result = self._transfer_operations_get(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._transfer_operations_list(opt, dry_run, &mut err); + }, + ("pause", Some(opt)) => { + call_result = self._transfer_operations_pause(opt, dry_run, &mut err); + }, + ("resume", Some(opt)) => { + call_result = self._transfer_operations_resume(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("transfer-operations".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + _ => { + err.issues.push(CLIError::MissingCommandError); + writeln!(io::stderr(), "{}\n", self.opt.usage()).ok(); + } + } + + if dry_run { + if err.issues.len() > 0 { + err_opt = Some(err); + } + Err(err_opt) + } else { + Ok(call_result) + } + } + + // Please note that this call will fail if any part of the opt can't be handled + fn new(opt: ArgMatches<'a, 'n>) -> Result, InvalidOptionsError> { + let (config_dir, secret) = { + let config_dir = match cmn::assure_config_dir_exists(opt.value_of("folder").unwrap_or("~/.google-service-cli")) { + Err(e) => return Err(InvalidOptionsError::single(e, 3)), + Ok(p) => p, + }; + + match cmn::application_secret_from_directory(&config_dir, "storagetransfer1-secret.json", + "{\"installed\":{\"auth_uri\":\"https://accounts.google.com/o/oauth2/auth\",\"client_secret\":\"hCsslbCUyfehWMmbkG8vTYxG\",\"token_uri\":\"https://accounts.google.com/o/oauth2/token\",\"client_email\":\"\",\"redirect_uris\":[\"urn:ietf:wg:oauth:2.0:oob\",\"oob\"],\"client_x509_cert_url\":\"\",\"client_id\":\"620010449518-9ngf7o4dhs0dka470npqvor6dc5lqb9b.apps.googleusercontent.com\",\"auth_provider_x509_cert_url\":\"https://www.googleapis.com/oauth2/v1/certs\"}}") { + Ok(secret) => (config_dir, secret), + Err(e) => return Err(InvalidOptionsError::single(e, 4)) + } + }; + + let auth = Authenticator::new( &secret, DefaultAuthenticatorDelegate, + if opt.is_present("debug-auth") { + hyper::Client::with_connector(mock::TeeConnector { + connector: hyper::net::HttpsConnector::::default() + }) + } else { + hyper::Client::new() + }, + JsonTokenStorage { + program_name: "storagetransfer1", + db_dir: config_dir.clone(), + }, None); + + let client = + if opt.is_present("debug") { + hyper::Client::with_connector(mock::TeeConnector { + connector: hyper::net::HttpsConnector::::default() + }) + } else { + hyper::Client::new() + }; + let engine = Engine { + opt: opt, + hub: api::Storagetransfer::new(client, auth), + gp: vec!["$-xgafv", "access-token", "alt", "bearer-token", "callback", "fields", "key", "oauth-token", "pp", "pretty-print", "quota-user", "upload-type", "upload-protocol"], + gpm: vec![ + ("$-xgafv", "$.xgafv"), + ("access-token", "access_token"), + ("bearer-token", "bearer_token"), + ("oauth-token", "oauth_token"), + ("pretty-print", "prettyPrint"), + ("quota-user", "quotaUser"), + ("upload-type", "uploadType"), + ("upload-protocol", "upload_protocol"), + ] + }; + + match engine._doit(true) { + Err(Some(err)) => Err(err), + Err(None) => Ok(engine), + Ok(_) => unreachable!(), + } + } + + fn doit(&self) -> Result<(), DoitError> { + match self._doit(false) { + Ok(res) => res, + Err(_) => unreachable!(), + } + } +} + +fn main() { + let mut exit_status = 0i32; + let arg_data = [ + ("google-service-accounts", "methods: 'get'", vec![ + ("get", + Some(r##"Returns the Google service account that is used by Storage Transfer Service to access buckets in the project where transfers run or in other projects. Each Google service account is associated with one Google Developers Console project. Users should add this service account to the Google Cloud Storage bucket ACLs to grant access to Storage Transfer Service. This service account is created and owned by Storage Transfer Service and can only be used by Storage Transfer Service."##), + "Details at http://byron.github.io/google-apis-rs/google_storagetransfer1_cli/google-service-accounts_get", + vec![ + (Some(r##"project-id"##), + None, + Some(r##"The ID of the Google Developers Console project that the Google service account is associated with. Required."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("methods", "methods: 'get-google-service-account'", vec![ + ("get-google-service-account", + Some(r##"Returns the Google service account that is used by Storage Transfer Service to access buckets in the project where transfers run or in other projects. Each Google service account is associated with one Google Developers Console project. Users should add this service account to the Google Cloud Storage bucket ACLs to grant access to Storage Transfer Service. This service account is created and owned by Storage Transfer Service and can only be used by Storage Transfer Service."##), + "Details at http://byron.github.io/google-apis-rs/google_storagetransfer1_cli/methods_get-google-service-account", + vec![ + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("transfer-jobs", "methods: 'create', 'get', 'list' and 'patch'", vec![ + ("create", + Some(r##"Creates a transfer job that runs periodically."##), + "Details at http://byron.github.io/google-apis-rs/google_storagetransfer1_cli/transfer-jobs_create", + vec![ + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("get", + Some(r##"Gets a transfer job."##), + "Details at http://byron.github.io/google-apis-rs/google_storagetransfer1_cli/transfer-jobs_get", + vec![ + (Some(r##"job-name"##), + None, + Some(r##"The job to get. Required."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Lists transfer jobs."##), + "Details at http://byron.github.io/google-apis-rs/google_storagetransfer1_cli/transfer-jobs_list", + vec![ + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("patch", + Some(r##"Updates a transfer job. Updating a job's transfer spec does not affect transfer operations that are running already. Updating the scheduling of a job is not allowed."##), + "Details at http://byron.github.io/google-apis-rs/google_storagetransfer1_cli/transfer-jobs_patch", + vec![ + (Some(r##"job-name"##), + None, + Some(r##"The name of job to update. Required."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("transfer-operations", "methods: 'cancel', 'delete', 'get', 'list', 'pause' and 'resume'", vec![ + ("cancel", + Some(r##"Cancels a transfer. Use the get method to check whether the cancellation succeeded or whether the operation completed despite cancellation."##), + "Details at http://byron.github.io/google-apis-rs/google_storagetransfer1_cli/transfer-operations_cancel", + vec![ + (Some(r##"name"##), + None, + Some(r##"The name of the operation resource to be cancelled."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("delete", + Some(r##"This method is not supported and the server returns `UNIMPLEMENTED`."##), + "Details at http://byron.github.io/google-apis-rs/google_storagetransfer1_cli/transfer-operations_delete", + vec![ + (Some(r##"name"##), + None, + Some(r##"The name of the operation resource to be deleted."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("get", + Some(r##"Gets the latest state of a long-running operation. Clients can use this method to poll the operation result at intervals as recommended by the API service."##), + "Details at http://byron.github.io/google-apis-rs/google_storagetransfer1_cli/transfer-operations_get", + vec![ + (Some(r##"name"##), + None, + Some(r##"The name of the operation resource."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Lists operations that match the specified filter in the request. If the server doesn't support this method, it returns `UNIMPLEMENTED`. NOTE: the `name` binding below allows API services to override the binding to use different resource name schemes, such as `users/*/operations`."##), + "Details at http://byron.github.io/google-apis-rs/google_storagetransfer1_cli/transfer-operations_list", + vec![ + (Some(r##"name"##), + None, + Some(r##"The value `transferOperations`."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("pause", + Some(r##"Pauses a transfer operation."##), + "Details at http://byron.github.io/google-apis-rs/google_storagetransfer1_cli/transfer-operations_pause", + vec![ + (Some(r##"name"##), + None, + Some(r##"The name of the transfer operation. Required."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("resume", + Some(r##"Resumes a transfer operation that is paused."##), + "Details at http://byron.github.io/google-apis-rs/google_storagetransfer1_cli/transfer-operations_resume", + vec![ + (Some(r##"name"##), + None, + Some(r##"The name of the transfer operation. Required."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ]; + + let mut app = App::new("storagetransfer1") + .author("Sebastian Thiel ") + .version("0.3.2+20150811") + .about("Transfers data from external data sources to a Google Cloud Storage bucket or between Google Cloud Storage buckets.") + .after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_storagetransfer1_cli") + .arg(Arg::with_name("url") + .long("scope") + .help("Specify the authentication a method should be executed in. Each scope requires the user to grant this application permission to use it.If unset, it defaults to the shortest scope url for a particular method.") + .multiple(true) + .takes_value(true)) + .arg(Arg::with_name("folder") + .long("config-dir") + .help("A directory into which we will store our persistent data. Defaults to a user-writable directory that we will create during the first invocation.[default: ~/.google-service-cli") + .multiple(false) + .takes_value(true)) + .arg(Arg::with_name("debug") + .long("debug") + .help("Output all server communication to standard error. `tx` and `rx` are placed into the same stream.") + .multiple(false) + .takes_value(false)) + .arg(Arg::with_name("debug-auth") + .long("debug-auth") + .help("Output all communication related to authentication to standard error. `tx` and `rx` are placed into the same stream.") + .multiple(false) + .takes_value(false)); + + for &(main_command_name, ref about, ref subcommands) in arg_data.iter() { + let mut mcmd = SubCommand::with_name(main_command_name).about(about); + + for &(sub_command_name, ref desc, url_info, ref args) in subcommands { + let mut scmd = SubCommand::with_name(sub_command_name); + if let &Some(desc) = desc { + scmd = scmd.about(desc); + } + scmd = scmd.after_help(url_info); + + for &(ref arg_name, ref flag, ref desc, ref required, ref multi) in args { + let arg_name_str = + match (arg_name, flag) { + (&Some(an), _ ) => an, + (_ , &Some(f)) => f, + _ => unreachable!(), + }; + let mut arg = Arg::with_name(arg_name_str) + .empty_values(false); + if let &Some(short_flag) = flag { + arg = arg.short(short_flag); + } + if let &Some(desc) = desc { + arg = arg.help(desc); + } + if arg_name.is_some() && flag.is_some() { + arg = arg.takes_value(true); + } + if let &Some(required) = required { + arg = arg.required(required); + } + if let &Some(multi) = multi { + arg = arg.multiple(multi); + } + scmd = scmd.arg(arg); + } + mcmd = mcmd.subcommand(scmd); + } + app = app.subcommand(mcmd); + } + + let matches = app.get_matches(); + + let debug = matches.is_present("debug"); + match Engine::new(matches) { + Err(err) => { + exit_status = err.exit_code; + writeln!(io::stderr(), "{}", err).ok(); + }, + Ok(engine) => { + if let Err(doit_err) = engine.doit() { + exit_status = 1; + match doit_err { + DoitError::IoError(path, err) => { + writeln!(io::stderr(), "Failed to open output file '{}': {}", path, err).ok(); + }, + DoitError::ApiError(err) => { + if debug { + writeln!(io::stderr(), "{:#?}", err).ok(); + } else { + writeln!(io::stderr(), "{}", err).ok(); + } + } + } + } + } + } + + std::process::exit(exit_status); +} \ No newline at end of file diff --git a/gen/storagetransfer1/Cargo.toml b/gen/storagetransfer1/Cargo.toml new file mode 100644 index 0000000000..f67f1b1956 --- /dev/null +++ b/gen/storagetransfer1/Cargo.toml @@ -0,0 +1,29 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-storagetransfer1" +version = "0.1.9+20150811" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with storagetransfer (protocol v1)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/storagetransfer1" +homepage = "https://cloud.google.com/storage/transfer" +documentation = "http://byron.github.io/google-apis-rs/google_storagetransfer1" +license = "MIT" +keywords = ["storagetransfer", "google", "protocol", "web", "api"] +build = "src/build.rs" + + +[dependencies] +hyper = ">= 0.6.8" +mime = "0.1.0" +serde = ">= 0.6.0" +serde_json = ">= 0.6.0" +yup-oauth2 = "*" +url = "*" + +[build-dependencies] +syntex = { version = "*" } +serde_codegen = { version = "*" } + diff --git a/gen/storagetransfer1/LICENSE.md b/gen/storagetransfer1/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/storagetransfer1/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/storagetransfer1/README.md b/gen/storagetransfer1/README.md new file mode 100644 index 0000000000..a0c95971c4 --- /dev/null +++ b/gen/storagetransfer1/README.md @@ -0,0 +1,188 @@ + +The `google-storagetransfer1` library allows access to all features of the *Google storagetransfer* service. + +This documentation was generated from *storagetransfer* crate version *0.1.9+20150811*, where *20150811* is the exact revision of the *storagetransfer:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. + +Everything else about the *storagetransfer* *v1* API can be found at the +[official documentation site](https://cloud.google.com/storage/transfer). +# Features + +Handle the following *Resources* with ease from the central [hub](http://byron.github.io/google-apis-rs/google_storagetransfer1/struct.Storagetransfer.html) ... + +* [google service accounts](http://byron.github.io/google-apis-rs/google_storagetransfer1/struct.GoogleServiceAccount.html) + * [*get*](http://byron.github.io/google-apis-rs/google_storagetransfer1/struct.GoogleServiceAccountGetCall.html) +* [transfer jobs](http://byron.github.io/google-apis-rs/google_storagetransfer1/struct.TransferJob.html) + * [*create*](http://byron.github.io/google-apis-rs/google_storagetransfer1/struct.TransferJobCreateCall.html), [*get*](http://byron.github.io/google-apis-rs/google_storagetransfer1/struct.TransferJobGetCall.html), [*list*](http://byron.github.io/google-apis-rs/google_storagetransfer1/struct.TransferJobListCall.html) and [*patch*](http://byron.github.io/google-apis-rs/google_storagetransfer1/struct.TransferJobPatchCall.html) +* [transfer operations](http://byron.github.io/google-apis-rs/google_storagetransfer1/struct.TransferOperation.html) + * [*cancel*](http://byron.github.io/google-apis-rs/google_storagetransfer1/struct.TransferOperationCancelCall.html), [*delete*](http://byron.github.io/google-apis-rs/google_storagetransfer1/struct.TransferOperationDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google_storagetransfer1/struct.TransferOperationGetCall.html), [*list*](http://byron.github.io/google-apis-rs/google_storagetransfer1/struct.TransferOperationListCall.html), [*pause*](http://byron.github.io/google-apis-rs/google_storagetransfer1/struct.TransferOperationPauseCall.html) and [*resume*](http://byron.github.io/google-apis-rs/google_storagetransfer1/struct.TransferOperationResumeCall.html) + +Other activities are ... + +* [get google service account](http://byron.github.io/google-apis-rs/google_storagetransfer1/struct.MethodGetGoogleServiceAccountCall.html) + + + +# Structure of this Library + +The API is structured into the following primary items: + +* **[Hub](http://byron.github.io/google-apis-rs/google_storagetransfer1/struct.Storagetransfer.html)** + * a central object to maintain state and allow accessing all *Activities* + * creates [*Method Builders*](http://byron.github.io/google-apis-rs/google_storagetransfer1/trait.MethodsBuilder.html) which in turn + allow access to individual [*Call Builders*](http://byron.github.io/google-apis-rs/google_storagetransfer1/trait.CallBuilder.html) +* **[Resources](http://byron.github.io/google-apis-rs/google_storagetransfer1/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_storagetransfer1/trait.Part.html)** + * a collection of properties + * never directly used in *Activities* +* **[Activities](http://byron.github.io/google-apis-rs/google_storagetransfer1/trait.CallBuilder.html)** + * operations to apply to *Resources* + +All *structures* are marked with applicable traits to further categorize them and ease browsing. + +Generally speaking, you can invoke *Activities* like this: + +```Rust,ignore +let r = hub.resource().activity(...).doit() +``` + +Or specifically ... + +```ignore +let r = hub.transfer_operations().pause(...).doit() +let r = hub.transfer_operations().resume(...).doit() +let r = hub.transfer_operations().delete(...).doit() +let r = hub.transfer_operations().get(...).doit() +let r = hub.transfer_operations().list(...).doit() +let r = hub.transfer_operations().cancel(...).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-storagetransfer1 = "*" +``` + +## A complete example + +```Rust +extern crate hyper; +extern crate yup_oauth2 as oauth2; +extern crate google_storagetransfer1 as storagetransfer1; +use storagetransfer1::{Result, Error}; +use std::default::Default; +use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +use storagetransfer1::Storagetransfer; + +// 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 = Storagetransfer::new(hyper::Client::new(), auth); +// You can configure optional parameters by calling the respective setters at will, and +// execute the final call using `doit()`. +// Values shown here are possibly random and not representative ! +let result = hub.transfer_operations().list("name") + .page_token("sit") + .page_size(-65) + .filter("sed") + .doit(); + +match result { + Err(e) => match e { + // The Error enum provides details about what exactly happened. + // You can also just use its `Debug`, `Display` or `Error` traits + Error::HttpError(_) + |Error::MissingAPIKey + |Error::MissingToken(_) + |Error::Cancelled + |Error::UploadSizeLimitExceeded(_, _) + |Error::Failure(_) + |Error::BadRequest(_) + |Error::FieldClash(_) + |Error::JsonDecodeError(_, _) => println!("{}", e), + }, + Ok(res) => println!("Success: {:?}", res), +} + +``` +## Handling Errors + +All errors produced by the system are provided either as [Result](http://byron.github.io/google-apis-rs/google_storagetransfer1/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_storagetransfer1/trait.Delegate.html), or the [Authenticator Delegate](http://byron.github.io/google-apis-rs/google_storagetransfer1/../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 Downloads +If a method supports downloads, the response body, which is part of the [Result](http://byron.github.io/google-apis-rs/google_storagetransfer1/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_storagetransfer1/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_storagetransfer1/trait.Delegate.html) to the +[Method Builder](http://byron.github.io/google-apis-rs/google_storagetransfer1/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_storagetransfer1/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_storagetransfer1/trait.RequestValue.html) and +[decodable](http://byron.github.io/google-apis-rs/google_storagetransfer1/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_storagetransfer1/trait.Part.html) which are identifiable 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_storagetransfer1/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_storagetransfer1/trait.RequestValue.html) are moved + +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 **storagetransfer1** 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/storagetransfer1/src/build.rs b/gen/storagetransfer1/src/build.rs new file mode 100644 index 0000000000..6f04d187e1 --- /dev/null +++ b/gen/storagetransfer1/src/build.rs @@ -0,0 +1,16 @@ +extern crate syntex; +extern crate serde_codegen; + +use std::env; +use std::path::Path; + +pub fn main() { + let out_dir = env::var_os("OUT_DIR").unwrap(); + + let src = Path::new("src/lib.rs.in"); + let dst = Path::new(&out_dir).join("lib.rs"); + + let mut registry = syntex::Registry::new(); + serde_codegen::register(&mut registry); + registry.expand("google-storagetransfer1", &src, &dst).unwrap(); +} diff --git a/gen/storagetransfer1/src/cmn.rs b/gen/storagetransfer1/src/cmn.rs new file mode 100644 index 0000000000..0e31353ba3 --- /dev/null +++ b/gen/storagetransfer1/src/cmn.rs @@ -0,0 +1,762 @@ +// COPY OF 'src/rust/api/cmn.rs' +// DO NOT EDIT +use std::io::{self, Read, Seek, Cursor, Write, SeekFrom}; +use std; +use std::fmt::{self, Display}; +use std::str::FromStr; +use std::error; +use std::thread::sleep_ms; + +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::h1::LINE_ENDING; +use hyper::method::Method; +use hyper::status::StatusCode; + +use serde_json as json; + +/// 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 {} + +/// Identifies types for building methods of a particular resource type +pub trait MethodsBuilder {} + +/// Identifies types which represent builders for a particular resource method +pub trait CallBuilder {} + +/// Identifies types which can be inserted and deleted. +/// Types with this trait are most commonly used by clients of this API. +pub trait Resource {} + +/// Identifies types which are used in API responses. +pub trait ResponseResult {} + +/// Identifies types which are used in API requests. +pub trait RequestValue {} + +/// Identifies types which are not actually used by the API +/// This might be a bug within the google API schema. +pub trait UnusedType {} + +/// Identifies types which are only used as part of other types, which +/// usually are carrying the `Resource` trait. +pub trait Part {} + +/// 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 {} + +/// 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 +} + +/// A utility to represent detailed errors we might see in case there are BadRequests. +/// The latter happen if the sent parameters or request structures are unsound +#[derive(Deserialize, Serialize, Debug)] +pub struct ErrorResponse { + error: ServerError, +} + +#[derive(Deserialize, Serialize, Debug)] +pub struct ServerError { + errors: Vec, + code: u16, + message: String, +} + +#[derive(Deserialize, Serialize, Debug)] +pub struct ServerMessage { + domain: String, + reason: String, + message: String, + #[serde(rename="locationType")] + location_type: Option, + location: 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 successful. That way, the delegate 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. + /// + /// If you choose to retry after a duration, the duration should be chosen using the + /// [exponential backoff algorithm](http://en.wikipedia.org/wiki/Exponential_backoff). + /// + /// Return retry information. + fn http_error(&mut self, &hyper::Error) -> 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 it as a general information about the + /// impending failure. + /// The given Error provides information about why the token couldn't be acquired in the + /// first place + fn token(&mut self, err: &error::Error) -> Option { + let _ = err; + 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/canceled, 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()`. + /// It will also be called with None after a successful upload, which allows the delegate + /// to forget the URL. That way, we will not attempt to resume an upload that has already + /// finished. + fn store_upload_url(&mut self, url: Option<&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: &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. + /// + /// If you choose to retry after a duration, the duration should be chosen using the + /// [exponential backoff algorithm](http://en.wikipedia.org/wiki/Exponential_backoff). + fn http_failure(&mut self, _: &hyper::client::Response, Option, _: 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 {} + + +#[derive(Debug)] +pub enum Error { + /// The http connection failed + HttpError(hyper::Error), + + /// 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), + + /// Represents information about a request that was not understood by the server. + /// Details are included. + BadRequest(ErrorResponse), + + /// 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(Box), + + /// 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(String, json::Error), + + /// Indicates an HTTP repsonse with a non-success status code + Failure(hyper::client::Response), +} + + +impl Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + Error::HttpError(ref err) => err.fmt(f), + Error::UploadSizeLimitExceeded(ref resource_size, ref max_size) => + writeln!(f, "The media size {} exceeds the maximum allowed upload size of {}" + , resource_size, max_size), + Error::MissingAPIKey => { + (writeln!(f, "The application's API key was not found in the configuration")).ok(); + writeln!(f, "It is used as there are no Scopes defined for this method.") + }, + Error::BadRequest(ref err) => { + try!(writeln!(f, "Bad Requst ({}): {}", err.error.code, err.error.message)); + for err in err.error.errors.iter() { + try!(writeln!(f, " {}: {}, {}{}", + err.domain, + err.message, + err.reason, + match &err.location { + &Some(ref loc) => format!("@{}", loc), + &None => String::new(), + })); + } + Ok(()) + }, + Error::MissingToken(ref err) => + writeln!(f, "Token retrieval failed with error: {}", err), + Error::Cancelled => + writeln!(f, "Operation cancelled by delegate"), + Error::FieldClash(field) => + writeln!(f, "The custom parameter '{}' is already provided natively by the CallBuilder.", field), + Error::JsonDecodeError(ref json_str, ref err) + => writeln!(f, "{}: {}", err, json_str), + Error::Failure(ref response) => + writeln!(f, "Http status indicates failure: {:?}", response), + } + } +} + +impl error::Error for Error { + fn description(&self) -> &str { + match *self { + Error::HttpError(ref err) => err.description(), + Error::JsonDecodeError(_, ref err) => err.description(), + _ => "NO DESCRIPTION POSSIBLE - use `Display.fmt()` instead" + } + } + + fn cause(&self) -> Option<&error::Error> { + match *self { + Error::HttpError(ref err) => err.cause(), + Error::JsonDecodeError(_, ref err) => err.cause(), + _ => None + } + } +} + +/// A universal result type used as return for all calls. +pub type Result = std::result::Result; + +/// 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 + 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 following macro invocation needs to be expanded, as `include!` +// doens't support external macros +// header!{ +// #[doc="The `X-Upload-Content-Type` header."] +// (XUploadContentType, "X-Upload-Content-Type") => [Mime] + +// xupload_content_type { +// test_header!( +// test1, +// vec![b"text/plain"], +// Some(HeaderField( +// vec![Mime(TopLevel::Text, SubLevel::Plain, Vec::new())] +// ))); + +// } +// } + +/// The `X-Upload-Content-Type` header. +/// +/// Generated via rustc --pretty expanded -Z unstable-options, and manually +/// processed to be more readable. +#[derive(PartialEq, Debug, Clone)] +pub struct XUploadContentType(pub Mime); + +impl ::std::ops::Deref for XUploadContentType { + type Target = Mime; + fn deref<'a>(&'a self) -> &'a Mime { &self.0 } +} +impl ::std::ops::DerefMut for XUploadContentType { + fn deref_mut<'a>(&'a mut self) -> &'a mut Mime { &mut self.0 } +} +impl Header for XUploadContentType { + fn header_name() -> &'static str { "X-Upload-Content-Type" } + fn parse_header(raw: &[Vec]) -> hyper::error::Result { + hyper::header::parsing::from_one_raw_str(raw).map(XUploadContentType) + } +} +impl HeaderFormat for XUploadContentType { + fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { + Display::fmt(&**self, f) + } +} +impl Display for XUploadContentType { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Display::fmt(&**self, f) + } +} + +#[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]) -> hyper::error::Result { + Err(hyper::error::Error::Method) + } +} + + +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]) -> hyper::error::Result { + if raw.len() > 0 { + let v = &raw[0]; + if let Ok(s) = std::str::from_utf8(v) { + const PREFIX: &'static str = "bytes "; + if s.starts_with(PREFIX) { + if let Ok(c) = ::from_str(&s[PREFIX.len()..]) { + return Ok(RangeResponseHeader(c)) + } + } + } + } + Err(hyper::error::Error::Method) + } +} + +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, 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, A> ResumableUploadHelper<'a, A> + where A: oauth2::GetToken { + + fn query_transfer_status(&mut self) -> std::result::Result> { + 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, None) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + return Err(Ok(r)) + } + }; + return Ok(h.0.last) + } + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + return Err(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() { + Ok(s) => s, + Err(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 + }; + + self.reader.seek(SeekFrom::Start(start)).unwrap(); + loop { + let request_size = match self.content_length - start { + rs if rs > chunk_size => chunk_size, + rs => rs + }; + + 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 + } + // workaround https://github.com/rust-lang/rust/issues/22252 + let res = 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(); + match res { + 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, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + } + return Some(Ok(res)) + }, + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + return Some(Err(err)) + } + } + } + } +} + +// Copy of src/rust/cli/cmn.rs +// TODO(ST): Allow sharing common code between program types +pub fn remove_json_null_values(value: &mut json::value::Value) { + match *value { + json::value::Value::Object(ref mut map) => { + let mut for_removal = Vec::new(); + + for (key, mut value) in map.iter_mut() { + if value.is_null() { + for_removal.push(key.clone()); + } else { + remove_json_null_values(&mut value); + } + } + + for key in &for_removal { + map.remove(key); + } + } + _ => {} + } +} diff --git a/gen/storagetransfer1/src/lib.rs b/gen/storagetransfer1/src/lib.rs new file mode 100644 index 0000000000..4a845eecf0 --- /dev/null +++ b/gen/storagetransfer1/src/lib.rs @@ -0,0 +1,192 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/api/lib.rs.mako' +// DO NOT EDIT ! + +//! This documentation was generated from *storagetransfer* crate version *0.1.9+20150811*, where *20150811* is the exact revision of the *storagetransfer:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +//! +//! Everything else about the *storagetransfer* *v1* API can be found at the +//! [official documentation site](https://cloud.google.com/storage/transfer). +//! The original source code is [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/storagetransfer1). +//! # Features +//! +//! Handle the following *Resources* with ease from the central [hub](struct.Storagetransfer.html) ... +//! +//! * [google service accounts](struct.GoogleServiceAccount.html) +//! * [*get*](struct.GoogleServiceAccountGetCall.html) +//! * [transfer jobs](struct.TransferJob.html) +//! * [*create*](struct.TransferJobCreateCall.html), [*get*](struct.TransferJobGetCall.html), [*list*](struct.TransferJobListCall.html) and [*patch*](struct.TransferJobPatchCall.html) +//! * [transfer operations](struct.TransferOperation.html) +//! * [*cancel*](struct.TransferOperationCancelCall.html), [*delete*](struct.TransferOperationDeleteCall.html), [*get*](struct.TransferOperationGetCall.html), [*list*](struct.TransferOperationListCall.html), [*pause*](struct.TransferOperationPauseCall.html) and [*resume*](struct.TransferOperationResumeCall.html) +//! +//! Other activities are ... +//! +//! * [get google service account](struct.MethodGetGoogleServiceAccountCall.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.Storagetransfer.html)** +//! * a central object to maintain state and allow accessing all *Activities* +//! * creates [*Method Builders*](trait.MethodsBuilder.html) which in turn +//! allow access to individual [*Call Builders*](trait.CallBuilder.html) +//! * **[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* +//! +//! All *structures* are marked with applicable traits to further categorize them and ease browsing. +//! +//! Generally speaking, you can invoke *Activities* like this: +//! +//! ```Rust,ignore +//! let r = hub.resource().activity(...).doit() +//! ``` +//! +//! Or specifically ... +//! +//! ```ignore +//! let r = hub.transfer_operations().pause(...).doit() +//! let r = hub.transfer_operations().resume(...).doit() +//! let r = hub.transfer_operations().delete(...).doit() +//! let r = hub.transfer_operations().get(...).doit() +//! let r = hub.transfer_operations().list(...).doit() +//! let r = hub.transfer_operations().cancel(...).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-storagetransfer1 = "*" +//! ``` +//! +//! ## A complete example +//! +//! ```test_harness,no_run +//! extern crate hyper; +//! extern crate yup_oauth2 as oauth2; +//! extern crate google_storagetransfer1 as storagetransfer1; +//! use storagetransfer1::{Result, Error}; +//! # #[test] fn egal() { +//! use std::default::Default; +//! use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +//! use storagetransfer1::Storagetransfer; +//! +//! // 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 = Storagetransfer::new(hyper::Client::new(), auth); +//! // You can configure optional parameters by calling the respective setters at will, and +//! // execute the final call using `doit()`. +//! // Values shown here are possibly random and not representative ! +//! let result = hub.transfer_operations().list("name") +//! .page_token("ipsum") +//! .page_size(-5) +//! .filter("et") +//! .doit(); +//! +//! match result { +//! Err(e) => match e { +//! // The Error enum provides details about what exactly happened. +//! // You can also just use its `Debug`, `Display` or `Error` traits +//! Error::HttpError(_) +//! |Error::MissingAPIKey +//! |Error::MissingToken(_) +//! |Error::Cancelled +//! |Error::UploadSizeLimitExceeded(_, _) +//! |Error::Failure(_) +//! |Error::BadRequest(_) +//! |Error::FieldClash(_) +//! |Error::JsonDecodeError(_, _) => println!("{}", e), +//! }, +//! Ok(res) => println!("Success: {:?}", res), +//! } +//! # } +//! ``` +//! ## 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 Downloads +//! 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 identifiable 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 moved +//! +//! 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 +//! +//! + +// 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)] + +include!(concat!(env!("OUT_DIR"), "/lib.rs")); \ No newline at end of file diff --git a/gen/storagetransfer1/src/lib.rs.in b/gen/storagetransfer1/src/lib.rs.in new file mode 100644 index 0000000000..2b5fe695f6 --- /dev/null +++ b/gen/storagetransfer1/src/lib.rs.in @@ -0,0 +1,4157 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/api/lib.rs.in.mako' +// DO NOT EDIT ! + +extern crate hyper; +extern crate serde; +extern crate serde_json; +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 serde_json as json; +use std::io; +use std::fs; +use std::thread::sleep_ms; + +pub use cmn::{MultiPartReader, ToParts, MethodInfo, Result, Error, CallBuilder, Hub, ReadSeek, Part, + ResponseResult, RequestValue, NestedType, Delegate, DefaultDelegate, MethodsBuilder, + Resource, ErrorResponse, remove_json_null_values}; + + +// ############## +// 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 AsRef for Scope { + fn as_ref(&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 Storagetransfer related resource activities +/// +/// # Examples +/// +/// Instantiate a new hub +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate yup_oauth2 as oauth2; +/// extern crate google_storagetransfer1 as storagetransfer1; +/// use storagetransfer1::{Result, Error}; +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use storagetransfer1::Storagetransfer; +/// +/// // 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 = Storagetransfer::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.transfer_operations().list("name") +/// .page_token("dolores") +/// .page_size(-63) +/// .filter("accusam") +/// .doit(); +/// +/// match result { +/// Err(e) => match e { +/// // The Error enum provides details about what exactly happened. +/// // You can also just use its `Debug`, `Display` or `Error` traits +/// Error::HttpError(_) +/// |Error::MissingAPIKey +/// |Error::MissingToken(_) +/// |Error::Cancelled +/// |Error::UploadSizeLimitExceeded(_, _) +/// |Error::Failure(_) +/// |Error::BadRequest(_) +/// |Error::FieldClash(_) +/// |Error::JsonDecodeError(_, _) => println!("{}", e), +/// }, +/// Ok(res) => println!("Success: {:?}", res), +/// } +/// # } +/// ``` +pub struct Storagetransfer { + client: RefCell, + auth: RefCell, + _user_agent: String, +} + +impl<'a, C, A> Hub for Storagetransfer {} + +impl<'a, C, A> Storagetransfer + where C: BorrowMut, A: oauth2::GetToken { + + pub fn new(client: C, authenticator: A) -> Storagetransfer { + Storagetransfer { + client: RefCell::new(client), + auth: RefCell::new(authenticator), + _user_agent: "google-api-rust-client/0.1.9".to_string(), + } + } + + pub fn google_service_accounts(&'a self) -> GoogleServiceAccountMethods<'a, C, A> { + GoogleServiceAccountMethods { hub: &self } + } + pub fn methods(&'a self) -> MethodMethods<'a, C, A> { + MethodMethods { hub: &self } + } + pub fn transfer_jobs(&'a self) -> TransferJobMethods<'a, C, A> { + TransferJobMethods { hub: &self } + } + pub fn transfer_operations(&'a self) -> TransferOperationMethods<'a, C, A> { + TransferOperationMethods { 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.9`. + /// + /// 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 ### +// ########## +/// Configuration for running a transfer. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct TransferSpec { + /// An HTTP URL data source. + #[serde(rename="httpDataSource")] + pub http_data_source: Option, + /// If the option `deleteObjectsUniqueInSink` is `true`, object conditions based on objects' `lastModificationTime` are ignored and do not exclude objects in a data source or a data sink. + #[serde(rename="transferOptions")] + pub transfer_options: Option, + /// Only objects that satisfy these object conditions are included in the set of data source and data sink objects. Object conditions based on objects' `lastModificationTime` do not exclude objects in a data sink. + #[serde(rename="objectConditions")] + pub object_conditions: Option, + /// A Google Cloud Storage data source. + #[serde(rename="gcsDataSource")] + pub gcs_data_source: Option, + /// A Google Cloud Storage data sink. + #[serde(rename="gcsDataSink")] + pub gcs_data_sink: Option, + /// An AWS S3 data source. + #[serde(rename="awsS3DataSource")] + pub aws_s3_data_source: Option, +} + +impl Part for TransferSpec {} + + +/// Request passed to PauseTransferOperation. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [pause transfer operations](struct.TransferOperationPauseCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct PauseTransferOperationRequest; + +impl RequestValue for PauseTransferOperationRequest {} + + +/// AWS access key (see [AWS Security Credentials](http://docs.aws.amazon.com/general/latest/gr/aws-security-credentials.html)). +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct AwsAccessKey { + /// AWS secret access key. This field is not returned in RPC responses. Required. + #[serde(rename="secretAccessKey")] + pub secret_access_key: Option, + /// AWS access key ID. Required. + #[serde(rename="accessKeyId")] + pub access_key_id: Option, +} + +impl Part for AwsAccessKey {} + + +/// Conditions that determine which objects will be transferred. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ObjectConditions { + /// `maxTimeElapsedSinceLastModification` is the complement to `minTimeElapsedSinceLastModification`. + #[serde(rename="maxTimeElapsedSinceLastModification")] + pub max_time_elapsed_since_last_modification: Option, + /// If `includePrefixes` is specified, objects that satisfy the object conditions must have names that start with one of the `includePrefixes` and that do not start with any of the `excludePrefixes`. If `includePrefixes` is not specified, all objects except those that have names starting with one of the `excludePrefixes` must satisfy the object conditions. Requirements: * Each include-prefix and exclude-prefix can contain any sequence of Unicode characters, of max length 1024 bytes when UTF8-encoded, and must not contain Carriage Return or Line Feed characters. Wildcard matching and regular expression matching are not supported. * None of the include-prefix or the exclude-prefix values can be empty, if specified. * Each include-prefix must include a distinct portion of the object namespace, i.e., no include-prefix may be a prefix of another include-prefix. * Each exclude-prefix must exclude a distinct portion of the object namespace, i.e., no exclude-prefix may be a prefix of another exclude-prefix. * If `includePrefixes` is specified, then each exclude-prefix must start with the value of a path explicitly included by `includePrefixes`. The max size of `includePrefixes` is 20. + #[serde(rename="includePrefixes")] + pub include_prefixes: Option>, + /// `excludePrefixes` must follow the requirements described for `includePrefixes`. The max size of `excludePrefixes` is 20. + #[serde(rename="excludePrefixes")] + pub exclude_prefixes: Option>, + /// If unspecified, `minTimeElapsedSinceLastModification` takes a zero value and `maxTimeElapsedSinceLastModification` takes the maximum possible value of Duration. Objects that satisfy the object conditions must either have a `lastModificationTime` greater or equal to `NOW` - `maxTimeElapsedSinceLastModification` and less than `NOW` - `minTimeElapsedSinceLastModification`, or not have a `lastModificationTime`. + #[serde(rename="minTimeElapsedSinceLastModification")] + pub min_time_elapsed_since_last_modification: Option, +} + +impl Part for ObjectConditions {} + + +/// A collection of counters that report the progress of a transfer operation. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct TransferCounters { + /// Bytes in the data source that are not transferred because they already exist in the data sink. + #[serde(rename="bytesFromSourceSkippedBySync")] + pub bytes_from_source_skipped_by_sync: Option, + /// Objects found in the data source that are scheduled to be transferred, which will be copied, excluded based on conditions, or skipped due to failures. + #[serde(rename="objectsFoundFromSource")] + pub objects_found_from_source: Option, + /// Bytes that failed to be deleted from the data sink. + #[serde(rename="bytesFailedToDeleteFromSink")] + pub bytes_failed_to_delete_from_sink: Option, + /// Objects that failed to be deleted from the data sink. + #[serde(rename="objectsFailedToDeleteFromSink")] + pub objects_failed_to_delete_from_sink: Option, + /// Objects found only in the data sink that are scheduled to be deleted. + #[serde(rename="objectsFoundOnlyFromSink")] + pub objects_found_only_from_sink: Option, + /// Objects in the data source that are not transferred because they already exist in the data sink. + #[serde(rename="objectsFromSourceSkippedBySync")] + pub objects_from_source_skipped_by_sync: Option, + /// Bytes that are copied to the data sink. + #[serde(rename="bytesCopiedToSink")] + pub bytes_copied_to_sink: Option, + /// Bytes found in the data source that are scheduled to be transferred, which will be copied, excluded based on conditions, or skipped due to failures. + #[serde(rename="bytesFoundFromSource")] + pub bytes_found_from_source: Option, + /// Objects that are deleted from the data source. + #[serde(rename="objectsDeletedFromSource")] + pub objects_deleted_from_source: Option, + /// Bytes found only in the data sink that are scheduled to be deleted. + #[serde(rename="bytesFoundOnlyFromSink")] + pub bytes_found_only_from_sink: Option, + /// Bytes in the data source that failed during the transfer. + #[serde(rename="bytesFromSourceFailed")] + pub bytes_from_source_failed: Option, + /// Bytes that are deleted from the data source. + #[serde(rename="bytesDeletedFromSource")] + pub bytes_deleted_from_source: Option, + /// Bytes that are deleted from the data sink. + #[serde(rename="bytesDeletedFromSink")] + pub bytes_deleted_from_sink: Option, + /// Objects that are copied to the data sink. + #[serde(rename="objectsCopiedToSink")] + pub objects_copied_to_sink: Option, + /// Objects that are deleted from the data sink. + #[serde(rename="objectsDeletedFromSink")] + pub objects_deleted_from_sink: Option, + /// Objects in the data source that failed during the transfer. + #[serde(rename="objectsFromSourceFailed")] + pub objects_from_source_failed: Option, +} + +impl Part for TransferCounters {} + + +/// A description of the execution of a transfer. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [pause transfer operations](struct.TransferOperationPauseCall.html) (none) +/// * [resume transfer operations](struct.TransferOperationResumeCall.html) (none) +/// * [delete transfer operations](struct.TransferOperationDeleteCall.html) (none) +/// * [get transfer operations](struct.TransferOperationGetCall.html) (none) +/// * [list transfer operations](struct.TransferOperationListCall.html) (none) +/// * [cancel transfer operations](struct.TransferOperationCancelCall.html) (none) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct TransferOperation { + /// Transfer specification. Required. + #[serde(rename="transferSpec")] + pub transfer_spec: Option, + /// Status of the transfer operation. + pub status: Option, + /// The name of the transfer job that triggers this transfer operation. + #[serde(rename="transferJobName")] + pub transfer_job_name: Option, + /// A globally unique ID assigned by the system. + pub name: Option, + /// The ID of the Google Developers Console project that owns the operation. Required. + #[serde(rename="projectId")] + pub project_id: Option, + /// Summarizes errors encountered with sample error log entries. + #[serde(rename="errorBreakdowns")] + pub error_breakdowns: Option>, + /// Start time of this transfer execution. + #[serde(rename="startTime")] + pub start_time: Option, + /// End time of this transfer execution. + #[serde(rename="endTime")] + pub end_time: Option, + /// Information about the progress of the transfer operation. + pub counters: Option, +} + +impl Resource for TransferOperation {} + + +/// An AwsS3Data can be a data source, but not a data sink. In an AwsS3Data, an object's name is the S3 object's key name. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct AwsS3Data { + /// AWS access key used to sign the API requests to the AWS S3 bucket. Permissions on the bucket must be granted to the access ID of the AWS access key. Required. + #[serde(rename="awsAccessKey")] + pub aws_access_key: Option, + /// S3 Bucket name (see [Creating a bucket](http://docs.aws.amazon.com/AmazonS3/latest/dev/create-bucket-get-location-example.html)). Required. + #[serde(rename="bucketName")] + pub bucket_name: Option, +} + +impl Part for AwsS3Data {} + + +/// An entry describing an error that has occurred. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ErrorLogEntry { + /// A URL that refers to the target (a data source, a data sink, or an object) with which the error is associated. Required. + pub url: Option, + /// A list of messages that carry the error details. + #[serde(rename="errorDetails")] + pub error_details: Option>, +} + +impl Part for ErrorLogEntry {} + + +/// In a GcsData, an object's name is the Google Cloud Storage object's name and its `lastModificationTime` refers to the object's updated time, which changes when the content or the metadata of the object is updated. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct GcsData { + /// Google Cloud Storage bucket name (see [Bucket Name Requirements](https://cloud.google.com/storage/docs/bucket-naming#requirements)). Required. + #[serde(rename="bucketName")] + pub bucket_name: Option, +} + +impl Part for GcsData {} + + +/// An HttpData specifies a list of objects on the web to be transferred over HTTP. The information of the objects to be transferred is contained in a file referenced by a URL. The first line in the file must be "TsvHttpData-1.0", which specifies the format of the file. Subsequent lines specify the information of the list of objects, one object per list entry. Each entry has the following tab-delimited fields: * HTTP URL * Length * MD5 - This field is a base64-encoded MD5 hash of the object An HTTP URL that points to the object to be transferred. It must be a valid URL with URL scheme HTTP or HTTPS. When an object with URL `http(s)://hostname:port/` is transferred to the data sink, the name of the object at the data sink is `/`. Length and MD5 provide the size and the base64-encoded MD5 hash of the object. If Length does not match the actual length of the object fetched, the object will not be transferred. If MD5 does not match the MD5 computed from the transferred bytes, the object transfer will fail. `lastModificationTime` is not available in HttpData objects. The objects that the URL list points to must allow public access. Storage Transfer Service obeys `robots.txt` rules and requires the HTTP server to support Range requests and to return a Content-Length header in each response. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct HttpData { + /// The URL that points to the file that stores the object list entries. This file must allow public access. Currently, only URLs with HTTP and HTTPS schemes are supported. Required. + #[serde(rename="listUrl")] + pub list_url: Option, +} + +impl Part for HttpData {} + + +/// Represents a time of day. The date and time zone are either not significant or are specified elsewhere. An API may chose to allow leap seconds. Related types are [google.type.Date][google.type.Date] and `google.protobuf.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 TimeOfDay { + /// Hours of day in 24 hour format. Should be from 0 to 23. An API may choose to allow the value "24:00:00" for scenarios like business closing time. + pub hours: Option, + /// Seconds of minutes of the time. Must normally be from 0 to 59. An API may allow the value 60 if it allows leap-seconds. + pub seconds: Option, + /// Minutes of hour of day. Must be from 0 to 59. + pub minutes: Option, + /// Fractions of seconds in nanoseconds. Must be from 0 to 999,999,999. + pub nanos: Option, +} + +impl Part for TimeOfDay {} + + +/// A generic empty message that you can re-use to avoid defining duplicated empty messages in your APIs. A typical example is to use it as the request or the response type of an API method. For instance: service Foo { rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); } The JSON representation for `Empty` is empty JSON object `{}`. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [pause transfer operations](struct.TransferOperationPauseCall.html) (response) +/// * [cancel transfer operations](struct.TransferOperationCancelCall.html) (response) +/// * [delete transfer operations](struct.TransferOperationDeleteCall.html) (response) +/// * [resume transfer operations](struct.TransferOperationResumeCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Empty; + +impl ResponseResult for Empty {} + + +/// The `Status` type defines a logical error model that is suitable for different programming environments, including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). The error model is designed to be: - Simple to use and understand for most users - Flexible enough to meet unexpected needs # Overview The `Status` message contains three pieces of data: error code, error message, and error details. The error code should be an enum value of [google.rpc.Code][google.rpc.Code], but it may accept additional error codes if needed. The error message should be a developer-facing English message that helps developers *understand* and *resolve* the error. If a localized user-facing error message is needed, put the localized message in the error details or localize it in the client. The optional error details may contain arbitrary information about the error. There is a predefined set of error detail types in the package `google.rpc` which can be used for common error conditions. # Language mapping The `Status` message is the logical representation of the error model, but it is not necessarily the actual wire format. When the `Status` message is exposed in different client libraries and different wire protocols, it can be mapped differently. For example, it will likely be mapped to some exceptions in Java, but more likely mapped to some error codes in C. # Other uses The error model and the `Status` message can be used in a variety of environments, either with or without APIs, to provide a consistent developer experience across different environments. Example uses of this error model include: - Partial errors. If a service needs to return partial errors to the client, it may embed the `Status` in the normal response to indicate the partial errors. - Workflow errors. A typical workflow has multiple steps. Each step may have a `Status` message for error reporting purpose. - Batch operations. If a client uses batch request and batch response, the `Status` message should be used directly inside batch response, one for each error sub-response. - Asynchronous operations. If an API call embeds asynchronous operation results in its response, the status of those operations should be represented directly using the `Status` message. - Logging. If some API errors are stored in logs, the message `Status` could be used directly after any stripping needed for security/privacy 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 Status { + /// A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the [google.rpc.Status.details][google.rpc.Status.details] field, or localized by the client. + pub message: Option, + /// The status code, which should be an enum value of [google.rpc.Code][google.rpc.Code]. + pub code: Option, + /// A list of messages that carry the error details. There will be a common set of message types for APIs to use. + pub details: Option>>, +} + +impl Part for Status {} + + +/// Google service 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 google service account](struct.MethodGetGoogleServiceAccountCall.html) (response) +/// * [get google service accounts](struct.GoogleServiceAccountGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct GoogleServiceAccount { + /// Required. + #[serde(rename="accountEmail")] + pub account_email: Option, +} + +impl Resource for GoogleServiceAccount {} +impl ResponseResult for GoogleServiceAccount {} + + +/// The response message for [Operations.ListOperations][google.longrunning.Operations.ListOperations]. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where 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 transfer operations](struct.TransferOperationListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ListOperationsResponse { + /// A list of operations that matches the specified filter in the request. + pub operations: Option>, + /// The standard List next-page token. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, +} + +impl ResponseResult for ListOperationsResponse {} + + +/// Transfers can be scheduled to recur or to run just once. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Schedule { + /// The first day the recurring transfer is scheduled to run. Required. + #[serde(rename="scheduleStartDate")] + pub schedule_start_date: Option, + /// The time in UTC at which the transfer will be scheduled to start in a day. Transfers may start later than this time. If not specified, transfers are scheduled to start at midnight UTC. + #[serde(rename="startTimeOfDay")] + pub start_time_of_day: Option, + /// The last day the recurring transfer will be run. If `scheduleEndDate` is the same as `scheduleStartDate`, the transfer will be executed only once. + #[serde(rename="scheduleEndDate")] + pub schedule_end_date: Option, +} + +impl Part for Schedule {} + + +/// A summary of errors by error code, plus a count and sample error log entries. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ErrorSummary { + /// Required. + #[serde(rename="errorCode")] + pub error_code: Option, + /// Error samples. + #[serde(rename="errorLogEntries")] + pub error_log_entries: Option>, + /// Count of this type of error. Required. + #[serde(rename="errorCount")] + pub error_count: Option, +} + +impl Part for ErrorSummary {} + + +/// Request passed to ResumeTransferOperation. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [resume transfer operations](struct.TransferOperationResumeCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ResumeTransferOperationRequest; + +impl RequestValue for ResumeTransferOperationRequest {} + + +/// Request passed to UpdateTransferJob. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where 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 transfer jobs](struct.TransferJobPatchCall.html) (request) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct UpdateTransferJobRequest { + /// The ID of the Google Developers Console project that owns the job. Required. + #[serde(rename="projectId")] + pub project_id: Option, + /// The field mask of the fields in `transferJob` that are to be updated in this request. Fields in `transferJob` that can be updated are: `description`, `transferSpec`, and `status`. To update the `transferSpec` of the job, a complete transfer specification has to be provided. An incomplete specification which misses any required fields will be rejected with the error `INVALID_ARGUMENT`. + #[serde(rename="updateTransferJobFieldMask")] + pub update_transfer_job_field_mask: Option, + /// The job to update. Required. + #[serde(rename="transferJob")] + pub transfer_job: Option, +} + +impl RequestValue for UpdateTransferJobRequest {} + + +/// Response from ListTransferJobs. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where 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 transfer jobs](struct.TransferJobListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ListTransferJobsResponse { + /// The list next page token. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// A list of transfer jobs. + #[serde(rename="transferJobs")] + pub transfer_jobs: Option>, +} + +impl ResponseResult for ListTransferJobsResponse {} + + +/// TransferOptions uses three boolean parameters to define the actions to be performed on objects in a transfer. +/// +/// This type is not used in any activity, and only used as *part* of another schema. +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct TransferOptions { + /// Whether overwriting objects that already exist in the sink is allowed. + #[serde(rename="overwriteObjectsAlreadyExistingInSink")] + pub overwrite_objects_already_existing_in_sink: Option, + /// Whether objects should be deleted from the source after they are transferred to the sink. + #[serde(rename="deleteObjectsFromSourceAfterTransfer")] + pub delete_objects_from_source_after_transfer: Option, + /// Whether objects that exist only in the sink should be deleted. + #[serde(rename="deleteObjectsUniqueInSink")] + pub delete_objects_unique_in_sink: Option, +} + +impl Part for TransferOptions {} + + +/// This resource represents the configuration of a transfer job that runs periodically. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where 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 transfer jobs](struct.TransferJobListCall.html) (none) +/// * [create transfer jobs](struct.TransferJobCreateCall.html) (request|response) +/// * [get transfer jobs](struct.TransferJobGetCall.html) (response) +/// * [patch transfer jobs](struct.TransferJobPatchCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct TransferJob { + /// Transfer specification. Required. + #[serde(rename="transferSpec")] + pub transfer_spec: Option, + /// Status of the job. This value MUST be specified for `CreateTransferJobRequests`. NOTE: The effect of the new job status takes place during a subsequent job run. For example, if you change the job status from `ENABLED` to `DISABLED`, and an operation spawned by the transfer is running, the status change would not affect the current operation. + pub status: Option, + /// This field cannot be changed by user requests. + #[serde(rename="deletionTime")] + pub deletion_time: Option, + /// A description provided by the user for the job. Its max length is 1024 bytes when Unicode-encoded. + pub description: Option, + /// Schedule specification. Required. + pub schedule: Option, + /// The ID of the Google Developers Console project that owns the job. Required. + #[serde(rename="projectId")] + pub project_id: Option, + /// This field cannot be changed by user requests. + #[serde(rename="lastModificationTime")] + pub last_modification_time: Option, + /// This field cannot be changed by user requests. + #[serde(rename="creationTime")] + pub creation_time: Option, + /// A globally unique name assigned by Storage Transfer Service when the job is created. This field should be left empty in requests to create a new transfer job; otherwise, the requests result in an `INVALID_ARGUMENT` error. + pub name: Option, +} + +impl RequestValue for TransferJob {} +impl Resource for TransferJob {} +impl ResponseResult for TransferJob {} + + +/// Represents a whole calendar date, e.g. date of birth. The time of day and time zone are either specified elsewhere or are not significant. The date is relative to the Proleptic Gregorian Calendar. The day may be 0 to represent a year and month where the day is not significant, e.g. credit card expiration date. The year may be 0 to represent a month and day independent of year, e.g. anniversary date. Related types are [google.type.TimeOfDay][google.type.TimeOfDay] and `google.protobuf.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 Date { + /// Year of date. Must be from 1 to 9,999, or 0 if specifying a date without a year. + pub year: Option, + /// Day of month. Must be from 1 to 31 and valid for the year and month, or 0 if specifying a year/month where the day is not sigificant. + pub day: Option, + /// Month of year of date. Must be from 1 to 12. + pub month: Option, +} + +impl Part for Date {} + + +/// This resource represents a long-running operation that is the result of a network API call. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where 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 transfer operations](struct.TransferOperationGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Operation { + /// Represents the transfer operation object. + pub metadata: Option>, + /// If the value is `false`, it means the operation is still in progress. If true, the operation is completed and the `result` is available. + pub done: Option, + /// The normal response of the operation in case of success. If the original method returns no data on success, such as `Delete`, the response is `google.protobuf.Empty`. If the original method is standard `Get`/`Create`/`Update`, the response should be the resource. For other methods, the response should have the type `XxxResponse`, where `Xxx` is the original method name. For example, if the original method name is `TakeSnapshot()`, the inferred response type is `TakeSnapshotResponse`. + pub response: Option>, + /// The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping above, the `name` should have the format of `operations/some/unique/name`. + pub name: Option, + /// The error result of the operation in case of failure. + pub error: Option, +} + +impl ResponseResult for Operation {} + + + +// ################### +// MethodBuilders ### +// ################# + +/// A builder providing access to all methods supported on *transferOperation* resources. +/// It is not used directly, but through the `Storagetransfer` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate yup_oauth2 as oauth2; +/// extern crate google_storagetransfer1 as storagetransfer1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use storagetransfer1::Storagetransfer; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Storagetransfer::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `cancel(...)`, `delete(...)`, `get(...)`, `list(...)`, `pause(...)` and `resume(...)` +/// // to build up your call. +/// let rb = hub.transfer_operations(); +/// # } +/// ``` +pub struct TransferOperationMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Storagetransfer, +} + +impl<'a, C, A> MethodsBuilder for TransferOperationMethods<'a, C, A> {} + +impl<'a, C, A> TransferOperationMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Pauses a transfer operation. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `name` - The name of the transfer operation. Required. + pub fn pause(&self, request: PauseTransferOperationRequest, name: &str) -> TransferOperationPauseCall<'a, C, A> { + TransferOperationPauseCall { + hub: self.hub, + _request: request, + _name: name.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Resumes a transfer operation that is paused. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `name` - The name of the transfer operation. Required. + pub fn resume(&self, request: ResumeTransferOperationRequest, name: &str) -> TransferOperationResumeCall<'a, C, A> { + TransferOperationResumeCall { + hub: self.hub, + _request: request, + _name: name.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets the latest state of a long-running operation. Clients can use this method to poll the operation result at intervals as recommended by the API service. + /// + /// # Arguments + /// + /// * `name` - The name of the operation resource. + pub fn get(&self, name: &str) -> TransferOperationGetCall<'a, C, A> { + TransferOperationGetCall { + hub: self.hub, + _name: 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 is not supported and the server returns `UNIMPLEMENTED`. + /// + /// # Arguments + /// + /// * `name` - The name of the operation resource to be deleted. + pub fn delete(&self, name: &str) -> TransferOperationDeleteCall<'a, C, A> { + TransferOperationDeleteCall { + hub: self.hub, + _name: name.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Lists operations that match the specified filter in the request. If the server doesn't support this method, it returns `UNIMPLEMENTED`. NOTE: the `name` binding below allows API services to override the binding to use different resource name schemes, such as `users/*/operations`. + /// + /// # Arguments + /// + /// * `name` - The value `transferOperations`. + pub fn list(&self, name: &str) -> TransferOperationListCall<'a, C, A> { + TransferOperationListCall { + hub: self.hub, + _name: name.to_string(), + _page_token: Default::default(), + _page_size: 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: + /// + /// Cancels a transfer. Use the get method to check whether the cancellation succeeded or whether the operation completed despite cancellation. + /// + /// # Arguments + /// + /// * `name` - The name of the operation resource to be cancelled. + pub fn cancel(&self, name: &str) -> TransferOperationCancelCall<'a, C, A> { + TransferOperationCancelCall { + hub: self.hub, + _name: name.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *googleServiceAccount* resources. +/// It is not used directly, but through the `Storagetransfer` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate yup_oauth2 as oauth2; +/// extern crate google_storagetransfer1 as storagetransfer1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use storagetransfer1::Storagetransfer; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Storagetransfer::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.google_service_accounts(); +/// # } +/// ``` +pub struct GoogleServiceAccountMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Storagetransfer, +} + +impl<'a, C, A> MethodsBuilder for GoogleServiceAccountMethods<'a, C, A> {} + +impl<'a, C, A> GoogleServiceAccountMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Returns the Google service account that is used by Storage Transfer Service to access buckets in the project where transfers run or in other projects. Each Google service account is associated with one Google Developers Console project. Users should add this service account to the Google Cloud Storage bucket ACLs to grant access to Storage Transfer Service. This service account is created and owned by Storage Transfer Service and can only be used by Storage Transfer Service. + /// + /// # Arguments + /// + /// * `projectId` - The ID of the Google Developers Console project that the Google service account is associated with. Required. + pub fn get(&self, project_id: &str) -> GoogleServiceAccountGetCall<'a, C, A> { + GoogleServiceAccountGetCall { + hub: self.hub, + _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 *transferJob* resources. +/// It is not used directly, but through the `Storagetransfer` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate yup_oauth2 as oauth2; +/// extern crate google_storagetransfer1 as storagetransfer1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use storagetransfer1::Storagetransfer; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Storagetransfer::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `create(...)`, `get(...)`, `list(...)` and `patch(...)` +/// // to build up your call. +/// let rb = hub.transfer_jobs(); +/// # } +/// ``` +pub struct TransferJobMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Storagetransfer, +} + +impl<'a, C, A> MethodsBuilder for TransferJobMethods<'a, C, A> {} + +impl<'a, C, A> TransferJobMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Lists transfer jobs. + pub fn list(&self) -> TransferJobListCall<'a, C, A> { + TransferJobListCall { + hub: self.hub, + _page_token: Default::default(), + _page_size: 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: + /// + /// Updates a transfer job. Updating a job's transfer spec does not affect transfer operations that are running already. Updating the scheduling of a job is not allowed. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `jobName` - The name of job to update. Required. + pub fn patch(&self, request: UpdateTransferJobRequest, job_name: &str) -> TransferJobPatchCall<'a, C, A> { + TransferJobPatchCall { + hub: self.hub, + _request: request, + _job_name: job_name.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Creates a transfer job that runs periodically. + /// + /// # Arguments + /// + /// * `request` - No description provided. + pub fn create(&self, request: TransferJob) -> TransferJobCreateCall<'a, C, A> { + TransferJobCreateCall { + hub: self.hub, + _request: request, + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets a transfer job. + /// + /// # Arguments + /// + /// * `jobName` - The job to get. Required. + pub fn get(&self, job_name: &str) -> TransferJobGetCall<'a, C, A> { + TransferJobGetCall { + hub: self.hub, + _job_name: job_name.to_string(), + _project_id: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all free methods, which are not associated with a particular resource. +/// It is not used directly, but through the `Storagetransfer` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate yup_oauth2 as oauth2; +/// extern crate google_storagetransfer1 as storagetransfer1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use storagetransfer1::Storagetransfer; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = Storagetransfer::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `get_google_service_account(...)` +/// // to build up your call. +/// let rb = hub.methods(); +/// # } +/// ``` +pub struct MethodMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Storagetransfer, +} + +impl<'a, C, A> MethodsBuilder for MethodMethods<'a, C, A> {} + +impl<'a, C, A> MethodMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Returns the Google service account that is used by Storage Transfer Service to access buckets in the project where transfers run or in other projects. Each Google service account is associated with one Google Developers Console project. Users should add this service account to the Google Cloud Storage bucket ACLs to grant access to Storage Transfer Service. This service account is created and owned by Storage Transfer Service and can only be used by Storage Transfer Service. + pub fn get_google_service_account(&self) -> MethodGetGoogleServiceAccountCall<'a, C, A> { + MethodGetGoogleServiceAccountCall { + hub: self.hub, + _project_id: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + + + +// ################### +// CallBuilders ### +// ################# + +/// Pauses a transfer operation. +/// +/// A builder for the *pause* method supported by a *transferOperation* resource. +/// It is not used directly, but through a `TransferOperationMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_storagetransfer1 as storagetransfer1; +/// use storagetransfer1::PauseTransferOperationRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use storagetransfer1::Storagetransfer; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Storagetransfer::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req = PauseTransferOperationRequest::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.transfer_operations().pause(req, "name") +/// .doit(); +/// # } +/// ``` +pub struct TransferOperationPauseCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Storagetransfer, + _request: PauseTransferOperationRequest, + _name: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for TransferOperationPauseCall<'a, C, A> {} + +impl<'a, C, A> TransferOperationPauseCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Empty)> { + use url::percent_encoding::{percent_encode, FORM_URLENCODED_ENCODE_SET}; + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "storagetransfer.transferOperations.pause", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("name", self._name.to_string())); + for &field in ["alt", "name"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://storagetransfer.googleapis.com/v1/{+name}:pause".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{+name}", "name")].iter() { + let mut replace_with = String::new(); + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = value.to_string(); + break; + } + } + if find_this.as_bytes()[1] == '+' as u8 { + replace_with = percent_encode(replace_with.as_bytes(), FORM_URLENCODED_ENCODE_SET); + } + url = url.replace(find_this, &replace_with); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["name"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: PauseTransferOperationRequest) -> TransferOperationPauseCall<'a, C, A> { + self._request = new_value; + self + } + /// The name of the transfer operation. Required. + /// + /// Sets the *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 name(mut self, new_value: &str) -> TransferOperationPauseCall<'a, C, A> { + self._name = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> TransferOperationPauseCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> TransferOperationPauseCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> TransferOperationPauseCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Resumes a transfer operation that is paused. +/// +/// A builder for the *resume* method supported by a *transferOperation* resource. +/// It is not used directly, but through a `TransferOperationMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_storagetransfer1 as storagetransfer1; +/// use storagetransfer1::ResumeTransferOperationRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use storagetransfer1::Storagetransfer; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Storagetransfer::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req = ResumeTransferOperationRequest::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.transfer_operations().resume(req, "name") +/// .doit(); +/// # } +/// ``` +pub struct TransferOperationResumeCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Storagetransfer, + _request: ResumeTransferOperationRequest, + _name: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for TransferOperationResumeCall<'a, C, A> {} + +impl<'a, C, A> TransferOperationResumeCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Empty)> { + use url::percent_encoding::{percent_encode, FORM_URLENCODED_ENCODE_SET}; + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "storagetransfer.transferOperations.resume", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("name", self._name.to_string())); + for &field in ["alt", "name"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://storagetransfer.googleapis.com/v1/{+name}:resume".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{+name}", "name")].iter() { + let mut replace_with = String::new(); + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = value.to_string(); + break; + } + } + if find_this.as_bytes()[1] == '+' as u8 { + replace_with = percent_encode(replace_with.as_bytes(), FORM_URLENCODED_ENCODE_SET); + } + url = url.replace(find_this, &replace_with); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["name"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: ResumeTransferOperationRequest) -> TransferOperationResumeCall<'a, C, A> { + self._request = new_value; + self + } + /// The name of the transfer operation. Required. + /// + /// Sets the *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 name(mut self, new_value: &str) -> TransferOperationResumeCall<'a, C, A> { + self._name = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> TransferOperationResumeCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> TransferOperationResumeCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> TransferOperationResumeCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Gets the latest state of a long-running operation. Clients can use this method to poll the operation result at intervals as recommended by the API service. +/// +/// A builder for the *get* method supported by a *transferOperation* resource. +/// It is not used directly, but through a `TransferOperationMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_storagetransfer1 as storagetransfer1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use storagetransfer1::Storagetransfer; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Storagetransfer::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.transfer_operations().get("name") +/// .doit(); +/// # } +/// ``` +pub struct TransferOperationGetCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Storagetransfer, + _name: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for TransferOperationGetCall<'a, C, A> {} + +impl<'a, C, A> TransferOperationGetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> { + use url::percent_encoding::{percent_encode, FORM_URLENCODED_ENCODE_SET}; + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "storagetransfer.transferOperations.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("name", self._name.to_string())); + for &field in ["alt", "name"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://storagetransfer.googleapis.com/v1/{+name}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{+name}", "name")].iter() { + let mut replace_with = String::new(); + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = value.to_string(); + break; + } + } + if find_this.as_bytes()[1] == '+' as u8 { + replace_with = percent_encode(replace_with.as_bytes(), FORM_URLENCODED_ENCODE_SET); + } + url = url.replace(find_this, &replace_with); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["name"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The name of the operation resource. + /// + /// Sets the *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 name(mut self, new_value: &str) -> TransferOperationGetCall<'a, C, A> { + self._name = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> TransferOperationGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> TransferOperationGetCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> TransferOperationGetCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// This method is not supported and the server returns `UNIMPLEMENTED`. +/// +/// A builder for the *delete* method supported by a *transferOperation* resource. +/// It is not used directly, but through a `TransferOperationMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_storagetransfer1 as storagetransfer1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use storagetransfer1::Storagetransfer; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Storagetransfer::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.transfer_operations().delete("name") +/// .doit(); +/// # } +/// ``` +pub struct TransferOperationDeleteCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Storagetransfer, + _name: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for TransferOperationDeleteCall<'a, C, A> {} + +impl<'a, C, A> TransferOperationDeleteCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Empty)> { + use url::percent_encoding::{percent_encode, FORM_URLENCODED_ENCODE_SET}; + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "storagetransfer.transferOperations.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("name", self._name.to_string())); + for &field in ["alt", "name"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://storagetransfer.googleapis.com/v1/{+name}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{+name}", "name")].iter() { + let mut replace_with = String::new(); + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = value.to_string(); + break; + } + } + if find_this.as_bytes()[1] == '+' as u8 { + replace_with = percent_encode(replace_with.as_bytes(), FORM_URLENCODED_ENCODE_SET); + } + url = url.replace(find_this, &replace_with); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["name"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The name of the operation resource to be deleted. + /// + /// Sets the *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 name(mut self, new_value: &str) -> TransferOperationDeleteCall<'a, C, A> { + self._name = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> TransferOperationDeleteCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> TransferOperationDeleteCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> TransferOperationDeleteCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Lists operations that match the specified filter in the request. If the server doesn't support this method, it returns `UNIMPLEMENTED`. NOTE: the `name` binding below allows API services to override the binding to use different resource name schemes, such as `users/*/operations`. +/// +/// A builder for the *list* method supported by a *transferOperation* resource. +/// It is not used directly, but through a `TransferOperationMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_storagetransfer1 as storagetransfer1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use storagetransfer1::Storagetransfer; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Storagetransfer::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.transfer_operations().list("name") +/// .page_token("sea") +/// .page_size(-90) +/// .filter("dolores") +/// .doit(); +/// # } +/// ``` +pub struct TransferOperationListCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Storagetransfer, + _name: String, + _page_token: Option, + _page_size: Option, + _filter: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for TransferOperationListCall<'a, C, A> {} + +impl<'a, C, A> TransferOperationListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ListOperationsResponse)> { + use url::percent_encoding::{percent_encode, FORM_URLENCODED_ENCODE_SET}; + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "storagetransfer.transferOperations.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("name", self._name.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._filter { + params.push(("filter", value.to_string())); + } + for &field in ["alt", "name", "pageToken", "pageSize", "filter"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://storagetransfer.googleapis.com/v1/{+name}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{+name}", "name")].iter() { + let mut replace_with = String::new(); + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = value.to_string(); + break; + } + } + if find_this.as_bytes()[1] == '+' as u8 { + replace_with = percent_encode(replace_with.as_bytes(), FORM_URLENCODED_ENCODE_SET); + } + url = url.replace(find_this, &replace_with); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["name"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The value `transferOperations`. + /// + /// Sets the *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 name(mut self, new_value: &str) -> TransferOperationListCall<'a, C, A> { + self._name = new_value.to_string(); + self + } + /// The standard list page token. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> TransferOperationListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// The standard list page size. + /// + /// Sets the *page size* query property to the given value. + pub fn page_size(mut self, new_value: i32) -> TransferOperationListCall<'a, C, A> { + self._page_size = Some(new_value); + self + } + /// The standard list filter. + /// + /// Sets the *filter* query property to the given value. + pub fn filter(mut self, new_value: &str) -> TransferOperationListCall<'a, C, A> { + self._filter = Some(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> TransferOperationListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> TransferOperationListCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> TransferOperationListCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Cancels a transfer. Use the get method to check whether the cancellation succeeded or whether the operation completed despite cancellation. +/// +/// A builder for the *cancel* method supported by a *transferOperation* resource. +/// It is not used directly, but through a `TransferOperationMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_storagetransfer1 as storagetransfer1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use storagetransfer1::Storagetransfer; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Storagetransfer::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.transfer_operations().cancel("name") +/// .doit(); +/// # } +/// ``` +pub struct TransferOperationCancelCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Storagetransfer, + _name: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for TransferOperationCancelCall<'a, C, A> {} + +impl<'a, C, A> TransferOperationCancelCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Empty)> { + use url::percent_encoding::{percent_encode, FORM_URLENCODED_ENCODE_SET}; + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "storagetransfer.transferOperations.cancel", + http_method: hyper::method::Method::Post }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len())); + params.push(("name", self._name.to_string())); + for &field in ["alt", "name"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://storagetransfer.googleapis.com/v1/{+name}:cancel".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{+name}", "name")].iter() { + let mut replace_with = String::new(); + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = value.to_string(); + break; + } + } + if find_this.as_bytes()[1] == '+' as u8 { + replace_with = percent_encode(replace_with.as_bytes(), FORM_URLENCODED_ENCODE_SET); + } + url = url.replace(find_this, &replace_with); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["name"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The name of the operation resource to be cancelled. + /// + /// Sets the *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 name(mut self, new_value: &str) -> TransferOperationCancelCall<'a, C, A> { + self._name = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> TransferOperationCancelCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> TransferOperationCancelCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> TransferOperationCancelCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Returns the Google service account that is used by Storage Transfer Service to access buckets in the project where transfers run or in other projects. Each Google service account is associated with one Google Developers Console project. Users should add this service account to the Google Cloud Storage bucket ACLs to grant access to Storage Transfer Service. This service account is created and owned by Storage Transfer Service and can only be used by Storage Transfer Service. +/// +/// A builder for the *get* method supported by a *googleServiceAccount* resource. +/// It is not used directly, but through a `GoogleServiceAccountMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_storagetransfer1 as storagetransfer1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use storagetransfer1::Storagetransfer; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Storagetransfer::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.google_service_accounts().get("projectId") +/// .doit(); +/// # } +/// ``` +pub struct GoogleServiceAccountGetCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Storagetransfer, + _project_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for GoogleServiceAccountGetCall<'a, C, A> {} + +impl<'a, C, A> GoogleServiceAccountGetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, GoogleServiceAccount)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "storagetransfer.googleServiceAccounts.get", + 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 Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://storagetransfer.googleapis.com/v1/googleServiceAccounts/{projectId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().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() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The ID of the Google Developers Console project that the Google service account is associated with. Required. + /// + /// 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. + pub fn project_id(mut self, new_value: &str) -> GoogleServiceAccountGetCall<'a, C, A> { + self._project_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> GoogleServiceAccountGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> GoogleServiceAccountGetCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> GoogleServiceAccountGetCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Lists transfer jobs. +/// +/// A builder for the *list* method supported by a *transferJob* resource. +/// It is not used directly, but through a `TransferJobMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_storagetransfer1 as storagetransfer1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use storagetransfer1::Storagetransfer; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Storagetransfer::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.transfer_jobs().list() +/// .page_token("aliquyam") +/// .page_size(-66) +/// .filter("no") +/// .doit(); +/// # } +/// ``` +pub struct TransferJobListCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Storagetransfer, + _page_token: Option, + _page_size: Option, + _filter: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for TransferJobListCall<'a, C, A> {} + +impl<'a, C, A> TransferJobListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ListTransferJobsResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "storagetransfer.transferJobs.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._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._filter { + params.push(("filter", value.to_string())); + } + for &field in ["alt", "pageToken", "pageSize", "filter"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://storagetransfer.googleapis.com/v1/transferJobs".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The list page token. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> TransferJobListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// The list page size. The max allowed value is 256. + /// + /// Sets the *page size* query property to the given value. + pub fn page_size(mut self, new_value: i32) -> TransferJobListCall<'a, C, A> { + self._page_size = Some(new_value); + self + } + /// A list of query parameters specified as JSON text in the form of {"`project_id`":"my_project_id", "`job_names`":["jobid1","jobid2",...], "`job_statuses`":["status1","status2",...]}. Since `job_names` and `job_statuses` support multiple values, their values must be specified with array notation. `project_id` is required. `job_names` and `job_statuses` are optional. The valid values for `job_statuses` are case-insensitive: `ENABLED`, `DISABLED`, and `DELETED`. + /// + /// Sets the *filter* query property to the given value. + pub fn filter(mut self, new_value: &str) -> TransferJobListCall<'a, C, A> { + self._filter = Some(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> TransferJobListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> TransferJobListCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> TransferJobListCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Updates a transfer job. Updating a job's transfer spec does not affect transfer operations that are running already. Updating the scheduling of a job is not allowed. +/// +/// A builder for the *patch* method supported by a *transferJob* resource. +/// It is not used directly, but through a `TransferJobMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_storagetransfer1 as storagetransfer1; +/// use storagetransfer1::UpdateTransferJobRequest; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use storagetransfer1::Storagetransfer; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Storagetransfer::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req = UpdateTransferJobRequest::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.transfer_jobs().patch(req, "jobName") +/// .doit(); +/// # } +/// ``` +pub struct TransferJobPatchCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Storagetransfer, + _request: UpdateTransferJobRequest, + _job_name: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for TransferJobPatchCall<'a, C, A> {} + +impl<'a, C, A> TransferJobPatchCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, TransferJob)> { + use url::percent_encoding::{percent_encode, FORM_URLENCODED_ENCODE_SET}; + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "storagetransfer.transferJobs.patch", + http_method: hyper::method::Method::Patch }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("jobName", self._job_name.to_string())); + for &field in ["alt", "jobName"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://storagetransfer.googleapis.com/v1/{+jobName}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{+jobName}", "jobName")].iter() { + let mut replace_with = String::new(); + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = value.to_string(); + break; + } + } + if find_this.as_bytes()[1] == '+' as u8 { + replace_with = percent_encode(replace_with.as_bytes(), FORM_URLENCODED_ENCODE_SET); + } + url = url.replace(find_this, &replace_with); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["jobName"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: UpdateTransferJobRequest) -> TransferJobPatchCall<'a, C, A> { + self._request = new_value; + self + } + /// The name of job to update. Required. + /// + /// Sets the *job 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 job_name(mut self, new_value: &str) -> TransferJobPatchCall<'a, C, A> { + self._job_name = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> TransferJobPatchCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> TransferJobPatchCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> TransferJobPatchCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Creates a transfer job that runs periodically. +/// +/// A builder for the *create* method supported by a *transferJob* resource. +/// It is not used directly, but through a `TransferJobMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_storagetransfer1 as storagetransfer1; +/// use storagetransfer1::TransferJob; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use storagetransfer1::Storagetransfer; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Storagetransfer::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req = TransferJob::default(); +/// +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.transfer_jobs().create(req) +/// .doit(); +/// # } +/// ``` +pub struct TransferJobCreateCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Storagetransfer, + _request: TransferJob, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for TransferJobCreateCall<'a, C, A> {} + +impl<'a, C, A> TransferJobCreateCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, TransferJob)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "storagetransfer.transferJobs.create", + 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 Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://storagetransfer.googleapis.com/v1/transferJobs".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: TransferJob) -> TransferJobCreateCall<'a, C, A> { + self._request = new_value; + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> TransferJobCreateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> TransferJobCreateCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> TransferJobCreateCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Gets a transfer job. +/// +/// A builder for the *get* method supported by a *transferJob* resource. +/// It is not used directly, but through a `TransferJobMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_storagetransfer1 as storagetransfer1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use storagetransfer1::Storagetransfer; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Storagetransfer::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.transfer_jobs().get("jobName") +/// .project_id("et") +/// .doit(); +/// # } +/// ``` +pub struct TransferJobGetCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Storagetransfer, + _job_name: String, + _project_id: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for TransferJobGetCall<'a, C, A> {} + +impl<'a, C, A> TransferJobGetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, TransferJob)> { + use url::percent_encoding::{percent_encode, FORM_URLENCODED_ENCODE_SET}; + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "storagetransfer.transferJobs.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("jobName", self._job_name.to_string())); + if let Some(value) = self._project_id { + params.push(("projectId", value.to_string())); + } + for &field in ["alt", "jobName", "projectId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://storagetransfer.googleapis.com/v1/{+jobName}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{+jobName}", "jobName")].iter() { + let mut replace_with = String::new(); + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = value.to_string(); + break; + } + } + if find_this.as_bytes()[1] == '+' as u8 { + replace_with = percent_encode(replace_with.as_bytes(), FORM_URLENCODED_ENCODE_SET); + } + url = url.replace(find_this, &replace_with); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["jobName"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The job to get. Required. + /// + /// Sets the *job 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 job_name(mut self, new_value: &str) -> TransferJobGetCall<'a, C, A> { + self._job_name = new_value.to_string(); + self + } + /// The ID of the Google Developers Console project that owns the job. Required. + /// + /// Sets the *project id* query property to the given value. + pub fn project_id(mut self, new_value: &str) -> TransferJobGetCall<'a, C, A> { + self._project_id = Some(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> TransferJobGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> TransferJobGetCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> TransferJobGetCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Returns the Google service account that is used by Storage Transfer Service to access buckets in the project where transfers run or in other projects. Each Google service account is associated with one Google Developers Console project. Users should add this service account to the Google Cloud Storage bucket ACLs to grant access to Storage Transfer Service. This service account is created and owned by Storage Transfer Service and can only be used by Storage Transfer Service. +/// +/// A builder for the *getGoogleServiceAccount* method. +/// It is not used directly, but through a `MethodMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_storagetransfer1 as storagetransfer1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use storagetransfer1::Storagetransfer; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = Storagetransfer::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling 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().get_google_service_account() +/// .project_id("et") +/// .doit(); +/// # } +/// ``` +pub struct MethodGetGoogleServiceAccountCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a Storagetransfer, + _project_id: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for MethodGetGoogleServiceAccountCall<'a, C, A> {} + +impl<'a, C, A> MethodGetGoogleServiceAccountCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, GoogleServiceAccount)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "storagetransfer.getGoogleServiceAccount", + 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._project_id { + params.push(("projectId", value.to_string())); + } + for &field in ["alt", "projectId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://storagetransfer.googleapis.com/v1:getGoogleServiceAccount".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The ID of the Google Developers Console project that the Google service account is associated with. Required. + /// + /// Sets the *project id* query property to the given value. + pub fn project_id(mut self, new_value: &str) -> MethodGetGoogleServiceAccountCall<'a, C, A> { + self._project_id = Some(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> MethodGetGoogleServiceAccountCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> MethodGetGoogleServiceAccountCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::CloudPlatform`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> MethodGetGoogleServiceAccountCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + diff --git a/gen/tagmanager1-cli/Cargo.toml b/gen/tagmanager1-cli/Cargo.toml index 9615c85421..9b8d5d92cc 100644 --- a/gen/tagmanager1-cli/Cargo.toml +++ b/gen/tagmanager1-cli/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-tagmanager1-cli" -version = "0.3.2+20150526" +version = "0.3.2+20151008" authors = ["Sebastian Thiel "] description = "A complete library to interact with Tag Manager (protocol v1)" repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/tagmanager1-cli" diff --git a/gen/tagmanager1-cli/README.md b/gen/tagmanager1-cli/README.md index 8948f47f48..6bdd555f37 100644 --- a/gen/tagmanager1-cli/README.md +++ b/gen/tagmanager1-cli/README.md @@ -24,25 +24,22 @@ Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/ma # Usage -This documentation was generated from the *Tag Manager* API at revision *20150526*. The CLI is at version *0.3.2*. +This documentation was generated from the *Tag Manager* API at revision *20151008*. The CLI is at version *0.3.2*. ```bash tagmanager1 [options] accounts containers-create (-r )... [-p ]... [-o ] containers-delete [-p ]... + containers-folders-create (-r )... [-p ]... [-o ] + containers-folders-delete [-p ]... + containers-folders-entities-list [-p ]... [-o ] + containers-folders-get [-p ]... [-o ] + containers-folders-list [-p ]... [-o ] + containers-folders-update (-r )... [-p ]... [-o ] containers-get [-p ]... [-o ] containers-list [-p ]... [-o ] - containers-macros-create (-r )... [-p ]... [-o ] - containers-macros-delete [-p ]... - containers-macros-get [-p ]... [-o ] - containers-macros-list [-p ]... [-o ] - containers-macros-update (-r )... [-p ]... [-o ] - containers-rules-create (-r )... [-p ]... [-o ] - containers-rules-delete [-p ]... - containers-rules-get [-p ]... [-o ] - containers-rules-list [-p ]... [-o ] - containers-rules-update (-r )... [-p ]... [-o ] + containers-move-folders-update [-p ]... containers-tags-create (-r )... [-p ]... [-o ] containers-tags-delete [-p ]... containers-tags-get [-p ]... [-o ] diff --git a/gen/tagmanager1-cli/mkdocs.yml b/gen/tagmanager1-cli/mkdocs.yml index f265b21d67..bef26d606e 100644 --- a/gen/tagmanager1-cli/mkdocs.yml +++ b/gen/tagmanager1-cli/mkdocs.yml @@ -1,4 +1,4 @@ -site_name: Tag Manager v0.3.2+20150526 +site_name: Tag Manager v0.3.2+20151008 site_url: http://byron.github.io/google-apis-rs/google-tagmanager1-cli site_description: Write integrating applications with bcore @@ -11,18 +11,15 @@ pages: - ['index.md', 'Home'] - ['accounts_containers-create.md', 'Accounts', 'Containers Create'] - ['accounts_containers-delete.md', 'Accounts', 'Containers Delete'] +- ['accounts_containers-folders-create.md', 'Accounts', 'Containers Folders Create'] +- ['accounts_containers-folders-delete.md', 'Accounts', 'Containers Folders Delete'] +- ['accounts_containers-folders-entities-list.md', 'Accounts', 'Containers Folders Entities List'] +- ['accounts_containers-folders-get.md', 'Accounts', 'Containers Folders Get'] +- ['accounts_containers-folders-list.md', 'Accounts', 'Containers Folders List'] +- ['accounts_containers-folders-update.md', 'Accounts', 'Containers Folders Update'] - ['accounts_containers-get.md', 'Accounts', 'Containers Get'] - ['accounts_containers-list.md', 'Accounts', 'Containers List'] -- ['accounts_containers-macros-create.md', 'Accounts', 'Containers Macros Create'] -- ['accounts_containers-macros-delete.md', 'Accounts', 'Containers Macros Delete'] -- ['accounts_containers-macros-get.md', 'Accounts', 'Containers Macros Get'] -- ['accounts_containers-macros-list.md', 'Accounts', 'Containers Macros List'] -- ['accounts_containers-macros-update.md', 'Accounts', 'Containers Macros Update'] -- ['accounts_containers-rules-create.md', 'Accounts', 'Containers Rules Create'] -- ['accounts_containers-rules-delete.md', 'Accounts', 'Containers Rules Delete'] -- ['accounts_containers-rules-get.md', 'Accounts', 'Containers Rules Get'] -- ['accounts_containers-rules-list.md', 'Accounts', 'Containers Rules List'] -- ['accounts_containers-rules-update.md', 'Accounts', 'Containers Rules Update'] +- ['accounts_containers-move-folders-update.md', 'Accounts', 'Containers Move Folders Update'] - ['accounts_containers-tags-create.md', 'Accounts', 'Containers Tags Create'] - ['accounts_containers-tags-delete.md', 'Accounts', 'Containers Tags Delete'] - ['accounts_containers-tags-get.md', 'Accounts', 'Containers Tags Get'] diff --git a/gen/tagmanager1-cli/src/main.rs b/gen/tagmanager1-cli/src/main.rs index f428c10bf2..5304660e40 100644 --- a/gen/tagmanager1-cli/src/main.rs +++ b/gen/tagmanager1-cli/src/main.rs @@ -184,6 +184,388 @@ impl<'n, 'a> Engine<'n, 'a> { } } + fn _accounts_containers_folders_create(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "fingerprint" => Some(("fingerprint", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "folder-id" => Some(("folderId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "container-id" => Some(("containerId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "container-id", "fingerprint", "folder-id", "name"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::Folder = json::value::from_value(object).unwrap(); + let mut call = self.hub.accounts().containers_folders_create(request, opt.value_of("account-id").unwrap_or(""), opt.value_of("container-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _accounts_containers_folders_delete(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.accounts().containers_folders_delete(opt.value_of("account-id").unwrap_or(""), opt.value_of("container-id").unwrap_or(""), opt.value_of("folder-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok(mut response) => { + Ok(()) + } + } + } + } + + fn _accounts_containers_folders_entities_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.accounts().containers_folders_entities_list(opt.value_of("account-id").unwrap_or(""), opt.value_of("container-id").unwrap_or(""), opt.value_of("folder-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _accounts_containers_folders_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.accounts().containers_folders_get(opt.value_of("account-id").unwrap_or(""), opt.value_of("container-id").unwrap_or(""), opt.value_of("folder-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _accounts_containers_folders_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.accounts().containers_folders_list(opt.value_of("account-id").unwrap_or(""), opt.value_of("container-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _accounts_containers_folders_update(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "fingerprint" => Some(("fingerprint", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "folder-id" => Some(("folderId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "container-id" => Some(("containerId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "container-id", "fingerprint", "folder-id", "name"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::Folder = json::value::from_value(object).unwrap(); + let mut call = self.hub.accounts().containers_folders_update(request, opt.value_of("account-id").unwrap_or(""), opt.value_of("container-id").unwrap_or(""), opt.value_of("folder-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "fingerprint" => { + call = call.fingerprint(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["fingerprint"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + fn _accounts_containers_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) -> Result<(), DoitError> { let mut call = self.hub.accounts().containers_get(opt.value_of("account-id").unwrap_or(""), opt.value_of("container-id").unwrap_or("")); @@ -288,300 +670,20 @@ impl<'n, 'a> Engine<'n, 'a> { } } - fn _accounts_containers_macros_create(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + fn _accounts_containers_move_folders_update(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) -> Result<(), DoitError> { - - let mut field_cursor = FieldCursor::default(); - let mut object = json::value::Value::Object(Default::default()); - - for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { - let last_errc = err.issues.len(); - let (key, value) = parse_kv_arg(&*kvarg, err, false); - let mut temp_cursor = field_cursor.clone(); - if let Err(field_err) = temp_cursor.set(&*key) { - err.issues.push(field_err); - } - if value.is_none() { - field_cursor = temp_cursor.clone(); - if err.issues.len() > last_errc { - err.issues.remove(last_errc); - } - continue; - } - - let type_info: Option<(&'static str, JsonTypeInfo)> = - match &temp_cursor.to_string()[..] { - "schedule-start-ms" => Some(("scheduleStartMs", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), - "schedule-end-ms" => Some(("scheduleEndMs", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), - "macro-id" => Some(("macroId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), - "container-id" => Some(("containerId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), - "notes" => Some(("notes", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), - "enabling-rule-id" => Some(("enablingRuleId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), - "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), - "disabling-rule-id" => Some(("disablingRuleId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), - "fingerprint" => Some(("fingerprint", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), - "type" => Some(("type", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), - "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), - _ => { - let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "container-id", "disabling-rule-id", "enabling-rule-id", "fingerprint", "macro-id", "name", "notes", "schedule-end-ms", "schedule-start-ms", "type"]); - err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); - None - } - }; - if let Some((field_cursor_str, type_info)) = type_info { - FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); - } - } - let mut request: api::Macro = json::value::from_value(object).unwrap(); - let mut call = self.hub.accounts().containers_macros_create(request, opt.value_of("account-id").unwrap_or(""), opt.value_of("container-id").unwrap_or("")); + let mut call = self.hub.accounts().containers_move_folders_update(opt.value_of("account-id").unwrap_or(""), opt.value_of("container-id").unwrap_or(""), opt.value_of("folder-id").unwrap_or("")); for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { let (key, value) = parse_kv_arg(&*parg, err, false); match key { - _ => { - let mut found = false; - for param in &self.gp { - if key == *param { - found = true; - call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); - break; - } - } - if !found { - err.issues.push(CLIError::UnknownParameter(key.to_string(), - {let mut v = Vec::new(); - v.extend(self.gp.iter().map(|v|*v)); - v } )); - } - } - } - } - let protocol = CallType::Standard; - if dry_run { - Ok(()) - } else { - assert!(err.issues.len() == 0); - for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { - call = call.add_scope(scope); - } - let mut ostream = match writer_from_opts(opt.value_of("out")) { - Ok(mut f) => f, - Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), - }; - match match protocol { - CallType::Standard => call.doit(), - _ => unreachable!() - } { - Err(api_err) => Err(DoitError::ApiError(api_err)), - Ok((mut response, output_schema)) => { - let mut value = json::value::to_value(&output_schema); - remove_json_null_values(&mut value); - json::to_writer_pretty(&mut ostream, &value).unwrap(); - ostream.flush().unwrap(); - Ok(()) - } - } - } - } - - fn _accounts_containers_macros_delete(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) - -> Result<(), DoitError> { - let mut call = self.hub.accounts().containers_macros_delete(opt.value_of("account-id").unwrap_or(""), opt.value_of("container-id").unwrap_or(""), opt.value_of("macro-id").unwrap_or("")); - for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { - let (key, value) = parse_kv_arg(&*parg, err, false); - match key { - _ => { - let mut found = false; - for param in &self.gp { - if key == *param { - found = true; - call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); - break; - } - } - if !found { - err.issues.push(CLIError::UnknownParameter(key.to_string(), - {let mut v = Vec::new(); - v.extend(self.gp.iter().map(|v|*v)); - v } )); - } - } - } - } - let protocol = CallType::Standard; - if dry_run { - Ok(()) - } else { - assert!(err.issues.len() == 0); - for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { - call = call.add_scope(scope); - } - match match protocol { - CallType::Standard => call.doit(), - _ => unreachable!() - } { - Err(api_err) => Err(DoitError::ApiError(api_err)), - Ok(mut response) => { - Ok(()) - } - } - } - } - - fn _accounts_containers_macros_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) - -> Result<(), DoitError> { - let mut call = self.hub.accounts().containers_macros_get(opt.value_of("account-id").unwrap_or(""), opt.value_of("container-id").unwrap_or(""), opt.value_of("macro-id").unwrap_or("")); - for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { - let (key, value) = parse_kv_arg(&*parg, err, false); - match key { - _ => { - let mut found = false; - for param in &self.gp { - if key == *param { - found = true; - call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); - break; - } - } - if !found { - err.issues.push(CLIError::UnknownParameter(key.to_string(), - {let mut v = Vec::new(); - v.extend(self.gp.iter().map(|v|*v)); - v } )); - } - } - } - } - let protocol = CallType::Standard; - if dry_run { - Ok(()) - } else { - assert!(err.issues.len() == 0); - for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { - call = call.add_scope(scope); - } - let mut ostream = match writer_from_opts(opt.value_of("out")) { - Ok(mut f) => f, - Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), - }; - match match protocol { - CallType::Standard => call.doit(), - _ => unreachable!() - } { - Err(api_err) => Err(DoitError::ApiError(api_err)), - Ok((mut response, output_schema)) => { - let mut value = json::value::to_value(&output_schema); - remove_json_null_values(&mut value); - json::to_writer_pretty(&mut ostream, &value).unwrap(); - ostream.flush().unwrap(); - Ok(()) - } - } - } - } - - fn _accounts_containers_macros_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) - -> Result<(), DoitError> { - let mut call = self.hub.accounts().containers_macros_list(opt.value_of("account-id").unwrap_or(""), opt.value_of("container-id").unwrap_or("")); - for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { - let (key, value) = parse_kv_arg(&*parg, err, false); - match key { - _ => { - let mut found = false; - for param in &self.gp { - if key == *param { - found = true; - call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); - break; - } - } - if !found { - err.issues.push(CLIError::UnknownParameter(key.to_string(), - {let mut v = Vec::new(); - v.extend(self.gp.iter().map(|v|*v)); - v } )); - } - } - } - } - let protocol = CallType::Standard; - if dry_run { - Ok(()) - } else { - assert!(err.issues.len() == 0); - for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { - call = call.add_scope(scope); - } - let mut ostream = match writer_from_opts(opt.value_of("out")) { - Ok(mut f) => f, - Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), - }; - match match protocol { - CallType::Standard => call.doit(), - _ => unreachable!() - } { - Err(api_err) => Err(DoitError::ApiError(api_err)), - Ok((mut response, output_schema)) => { - let mut value = json::value::to_value(&output_schema); - remove_json_null_values(&mut value); - json::to_writer_pretty(&mut ostream, &value).unwrap(); - ostream.flush().unwrap(); - Ok(()) - } - } - } - } - - fn _accounts_containers_macros_update(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) - -> Result<(), DoitError> { - - let mut field_cursor = FieldCursor::default(); - let mut object = json::value::Value::Object(Default::default()); - - for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { - let last_errc = err.issues.len(); - let (key, value) = parse_kv_arg(&*kvarg, err, false); - let mut temp_cursor = field_cursor.clone(); - if let Err(field_err) = temp_cursor.set(&*key) { - err.issues.push(field_err); - } - if value.is_none() { - field_cursor = temp_cursor.clone(); - if err.issues.len() > last_errc { - err.issues.remove(last_errc); - } - continue; - } - - let type_info: Option<(&'static str, JsonTypeInfo)> = - match &temp_cursor.to_string()[..] { - "schedule-start-ms" => Some(("scheduleStartMs", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), - "schedule-end-ms" => Some(("scheduleEndMs", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), - "macro-id" => Some(("macroId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), - "container-id" => Some(("containerId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), - "notes" => Some(("notes", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), - "enabling-rule-id" => Some(("enablingRuleId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), - "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), - "disabling-rule-id" => Some(("disablingRuleId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), - "fingerprint" => Some(("fingerprint", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), - "type" => Some(("type", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), - "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), - _ => { - let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "container-id", "disabling-rule-id", "enabling-rule-id", "fingerprint", "macro-id", "name", "notes", "schedule-end-ms", "schedule-start-ms", "type"]); - err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); - None - } - }; - if let Some((field_cursor_str, type_info)) = type_info { - FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); - } - } - let mut request: api::Macro = json::value::from_value(object).unwrap(); - let mut call = self.hub.accounts().containers_macros_update(request, opt.value_of("account-id").unwrap_or(""), opt.value_of("container-id").unwrap_or(""), opt.value_of("macro-id").unwrap_or("")); - for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { - let (key, value) = parse_kv_arg(&*parg, err, false); - match key { - "fingerprint" => { - call = call.fingerprint(value.unwrap_or("")); + "variable-id" => { + call = call.add_variable_id(value.unwrap_or("")); + }, + "trigger-id" => { + call = call.add_trigger_id(value.unwrap_or("")); + }, + "tag-id" => { + call = call.add_tag_id(value.unwrap_or("")); }, _ => { let mut found = false; @@ -596,7 +698,7 @@ impl<'n, 'a> Engine<'n, 'a> { err.issues.push(CLIError::UnknownParameter(key.to_string(), {let mut v = Vec::new(); v.extend(self.gp.iter().map(|v|*v)); - v.extend(["fingerprint"].iter().map(|v|*v)); + v.extend(["trigger-id", "tag-id", "variable-id"].iter().map(|v|*v)); v } )); } } @@ -607,151 +709,6 @@ impl<'n, 'a> Engine<'n, 'a> { Ok(()) } else { assert!(err.issues.len() == 0); - for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { - call = call.add_scope(scope); - } - let mut ostream = match writer_from_opts(opt.value_of("out")) { - Ok(mut f) => f, - Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), - }; - match match protocol { - CallType::Standard => call.doit(), - _ => unreachable!() - } { - Err(api_err) => Err(DoitError::ApiError(api_err)), - Ok((mut response, output_schema)) => { - let mut value = json::value::to_value(&output_schema); - remove_json_null_values(&mut value); - json::to_writer_pretty(&mut ostream, &value).unwrap(); - ostream.flush().unwrap(); - Ok(()) - } - } - } - } - - fn _accounts_containers_rules_create(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) - -> Result<(), DoitError> { - - let mut field_cursor = FieldCursor::default(); - let mut object = json::value::Value::Object(Default::default()); - - for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { - let last_errc = err.issues.len(); - let (key, value) = parse_kv_arg(&*kvarg, err, false); - let mut temp_cursor = field_cursor.clone(); - if let Err(field_err) = temp_cursor.set(&*key) { - err.issues.push(field_err); - } - if value.is_none() { - field_cursor = temp_cursor.clone(); - if err.issues.len() > last_errc { - err.issues.remove(last_errc); - } - continue; - } - - let type_info: Option<(&'static str, JsonTypeInfo)> = - match &temp_cursor.to_string()[..] { - "container-id" => Some(("containerId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), - "rule-id" => Some(("ruleId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), - "notes" => Some(("notes", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), - "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), - "fingerprint" => Some(("fingerprint", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), - "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), - _ => { - let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "container-id", "fingerprint", "name", "notes", "rule-id"]); - err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); - None - } - }; - if let Some((field_cursor_str, type_info)) = type_info { - FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); - } - } - let mut request: api::Rule = json::value::from_value(object).unwrap(); - let mut call = self.hub.accounts().containers_rules_create(request, opt.value_of("account-id").unwrap_or(""), opt.value_of("container-id").unwrap_or("")); - for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { - let (key, value) = parse_kv_arg(&*parg, err, false); - match key { - _ => { - let mut found = false; - for param in &self.gp { - if key == *param { - found = true; - call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); - break; - } - } - if !found { - err.issues.push(CLIError::UnknownParameter(key.to_string(), - {let mut v = Vec::new(); - v.extend(self.gp.iter().map(|v|*v)); - v } )); - } - } - } - } - let protocol = CallType::Standard; - if dry_run { - Ok(()) - } else { - assert!(err.issues.len() == 0); - for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { - call = call.add_scope(scope); - } - let mut ostream = match writer_from_opts(opt.value_of("out")) { - Ok(mut f) => f, - Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), - }; - match match protocol { - CallType::Standard => call.doit(), - _ => unreachable!() - } { - Err(api_err) => Err(DoitError::ApiError(api_err)), - Ok((mut response, output_schema)) => { - let mut value = json::value::to_value(&output_schema); - remove_json_null_values(&mut value); - json::to_writer_pretty(&mut ostream, &value).unwrap(); - ostream.flush().unwrap(); - Ok(()) - } - } - } - } - - fn _accounts_containers_rules_delete(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) - -> Result<(), DoitError> { - let mut call = self.hub.accounts().containers_rules_delete(opt.value_of("account-id").unwrap_or(""), opt.value_of("container-id").unwrap_or(""), opt.value_of("rule-id").unwrap_or("")); - for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { - let (key, value) = parse_kv_arg(&*parg, err, false); - match key { - _ => { - let mut found = false; - for param in &self.gp { - if key == *param { - found = true; - call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); - break; - } - } - if !found { - err.issues.push(CLIError::UnknownParameter(key.to_string(), - {let mut v = Vec::new(); - v.extend(self.gp.iter().map(|v|*v)); - v } )); - } - } - } - } - let protocol = CallType::Standard; - if dry_run { - Ok(()) - } else { - assert!(err.issues.len() == 0); - for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { - call = call.add_scope(scope); - } match match protocol { CallType::Standard => call.doit(), _ => unreachable!() @@ -764,204 +721,6 @@ impl<'n, 'a> Engine<'n, 'a> { } } - fn _accounts_containers_rules_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) - -> Result<(), DoitError> { - let mut call = self.hub.accounts().containers_rules_get(opt.value_of("account-id").unwrap_or(""), opt.value_of("container-id").unwrap_or(""), opt.value_of("rule-id").unwrap_or("")); - for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { - let (key, value) = parse_kv_arg(&*parg, err, false); - match key { - _ => { - let mut found = false; - for param in &self.gp { - if key == *param { - found = true; - call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); - break; - } - } - if !found { - err.issues.push(CLIError::UnknownParameter(key.to_string(), - {let mut v = Vec::new(); - v.extend(self.gp.iter().map(|v|*v)); - v } )); - } - } - } - } - let protocol = CallType::Standard; - if dry_run { - Ok(()) - } else { - assert!(err.issues.len() == 0); - for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { - call = call.add_scope(scope); - } - let mut ostream = match writer_from_opts(opt.value_of("out")) { - Ok(mut f) => f, - Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), - }; - match match protocol { - CallType::Standard => call.doit(), - _ => unreachable!() - } { - Err(api_err) => Err(DoitError::ApiError(api_err)), - Ok((mut response, output_schema)) => { - let mut value = json::value::to_value(&output_schema); - remove_json_null_values(&mut value); - json::to_writer_pretty(&mut ostream, &value).unwrap(); - ostream.flush().unwrap(); - Ok(()) - } - } - } - } - - fn _accounts_containers_rules_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) - -> Result<(), DoitError> { - let mut call = self.hub.accounts().containers_rules_list(opt.value_of("account-id").unwrap_or(""), opt.value_of("container-id").unwrap_or("")); - for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { - let (key, value) = parse_kv_arg(&*parg, err, false); - match key { - _ => { - let mut found = false; - for param in &self.gp { - if key == *param { - found = true; - call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); - break; - } - } - if !found { - err.issues.push(CLIError::UnknownParameter(key.to_string(), - {let mut v = Vec::new(); - v.extend(self.gp.iter().map(|v|*v)); - v } )); - } - } - } - } - let protocol = CallType::Standard; - if dry_run { - Ok(()) - } else { - assert!(err.issues.len() == 0); - for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { - call = call.add_scope(scope); - } - let mut ostream = match writer_from_opts(opt.value_of("out")) { - Ok(mut f) => f, - Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), - }; - match match protocol { - CallType::Standard => call.doit(), - _ => unreachable!() - } { - Err(api_err) => Err(DoitError::ApiError(api_err)), - Ok((mut response, output_schema)) => { - let mut value = json::value::to_value(&output_schema); - remove_json_null_values(&mut value); - json::to_writer_pretty(&mut ostream, &value).unwrap(); - ostream.flush().unwrap(); - Ok(()) - } - } - } - } - - fn _accounts_containers_rules_update(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) - -> Result<(), DoitError> { - - let mut field_cursor = FieldCursor::default(); - let mut object = json::value::Value::Object(Default::default()); - - for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { - let last_errc = err.issues.len(); - let (key, value) = parse_kv_arg(&*kvarg, err, false); - let mut temp_cursor = field_cursor.clone(); - if let Err(field_err) = temp_cursor.set(&*key) { - err.issues.push(field_err); - } - if value.is_none() { - field_cursor = temp_cursor.clone(); - if err.issues.len() > last_errc { - err.issues.remove(last_errc); - } - continue; - } - - let type_info: Option<(&'static str, JsonTypeInfo)> = - match &temp_cursor.to_string()[..] { - "container-id" => Some(("containerId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), - "rule-id" => Some(("ruleId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), - "notes" => Some(("notes", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), - "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), - "fingerprint" => Some(("fingerprint", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), - "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), - _ => { - let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "container-id", "fingerprint", "name", "notes", "rule-id"]); - err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); - None - } - }; - if let Some((field_cursor_str, type_info)) = type_info { - FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); - } - } - let mut request: api::Rule = json::value::from_value(object).unwrap(); - let mut call = self.hub.accounts().containers_rules_update(request, opt.value_of("account-id").unwrap_or(""), opt.value_of("container-id").unwrap_or(""), opt.value_of("rule-id").unwrap_or("")); - for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { - let (key, value) = parse_kv_arg(&*parg, err, false); - match key { - "fingerprint" => { - call = call.fingerprint(value.unwrap_or("")); - }, - _ => { - let mut found = false; - for param in &self.gp { - if key == *param { - found = true; - call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); - break; - } - } - if !found { - err.issues.push(CLIError::UnknownParameter(key.to_string(), - {let mut v = Vec::new(); - v.extend(self.gp.iter().map(|v|*v)); - v.extend(["fingerprint"].iter().map(|v|*v)); - v } )); - } - } - } - } - let protocol = CallType::Standard; - if dry_run { - Ok(()) - } else { - assert!(err.issues.len() == 0); - for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { - call = call.add_scope(scope); - } - let mut ostream = match writer_from_opts(opt.value_of("out")) { - Ok(mut f) => f, - Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), - }; - match match protocol { - CallType::Standard => call.doit(), - _ => unreachable!() - } { - Err(api_err) => Err(DoitError::ApiError(api_err)), - Ok((mut response, output_schema)) => { - let mut value = json::value::to_value(&output_schema); - remove_json_null_values(&mut value); - json::to_writer_pretty(&mut ostream, &value).unwrap(); - ostream.flush().unwrap(); - Ok(()) - } - } - } - } - fn _accounts_containers_tags_create(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) -> Result<(), DoitError> { @@ -989,7 +748,9 @@ impl<'n, 'a> Engine<'n, 'a> { "schedule-end-ms" => Some(("scheduleEndMs", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "container-id" => Some(("containerId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "blocking-trigger-id" => Some(("blockingTriggerId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "tag-firing-option" => Some(("tagFiringOption", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "tag-id" => Some(("tagId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "parent-folder-id" => Some(("parentFolderId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "priority.type" => Some(("priority.type", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "priority.value" => Some(("priority.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), @@ -1003,7 +764,7 @@ impl<'n, 'a> Engine<'n, 'a> { "notes" => Some(("notes", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), _ => { - let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "blocking-rule-id", "blocking-trigger-id", "container-id", "fingerprint", "firing-rule-id", "firing-trigger-id", "key", "live-only", "name", "notes", "priority", "schedule-end-ms", "schedule-start-ms", "tag-id", "type", "value"]); + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "blocking-rule-id", "blocking-trigger-id", "container-id", "fingerprint", "firing-rule-id", "firing-trigger-id", "key", "live-only", "name", "notes", "parent-folder-id", "priority", "schedule-end-ms", "schedule-start-ms", "tag-firing-option", "tag-id", "type", "value"]); err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); None } @@ -1238,7 +999,9 @@ impl<'n, 'a> Engine<'n, 'a> { "schedule-end-ms" => Some(("scheduleEndMs", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "container-id" => Some(("containerId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "blocking-trigger-id" => Some(("blockingTriggerId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), + "tag-firing-option" => Some(("tagFiringOption", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "tag-id" => Some(("tagId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "parent-folder-id" => Some(("parentFolderId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "priority.type" => Some(("priority.type", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "priority.value" => Some(("priority.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), @@ -1252,7 +1015,7 @@ impl<'n, 'a> Engine<'n, 'a> { "notes" => Some(("notes", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), _ => { - let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "blocking-rule-id", "blocking-trigger-id", "container-id", "fingerprint", "firing-rule-id", "firing-trigger-id", "key", "live-only", "name", "notes", "priority", "schedule-end-ms", "schedule-start-ms", "tag-id", "type", "value"]); + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "blocking-rule-id", "blocking-trigger-id", "container-id", "fingerprint", "firing-rule-id", "firing-trigger-id", "key", "live-only", "name", "notes", "parent-folder-id", "priority", "schedule-end-ms", "schedule-start-ms", "tag-firing-option", "tag-id", "type", "value"]); err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); None } @@ -1371,9 +1134,10 @@ impl<'n, 'a> Engine<'n, 'a> { "enable-all-videos.type" => Some(("enableAllVideos.type", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "enable-all-videos.value" => Some(("enableAllVideos.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "enable-all-videos.key" => Some(("enableAllVideos.key", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "parent-folder-id" => Some(("parentFolderId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), _ => { - let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "check-validation", "container-id", "enable-all-videos", "event-name", "fingerprint", "interval", "key", "limit", "name", "trigger-id", "type", "unique-trigger-id", "value", "video-percentage-list", "wait-for-tags", "wait-for-tags-timeout"]); + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "check-validation", "container-id", "enable-all-videos", "event-name", "fingerprint", "interval", "key", "limit", "name", "parent-folder-id", "trigger-id", "type", "unique-trigger-id", "value", "video-percentage-list", "wait-for-tags", "wait-for-tags-timeout"]); err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); None } @@ -1636,9 +1400,10 @@ impl<'n, 'a> Engine<'n, 'a> { "enable-all-videos.type" => Some(("enableAllVideos.type", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "enable-all-videos.value" => Some(("enableAllVideos.value", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "enable-all-videos.key" => Some(("enableAllVideos.key", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "parent-folder-id" => Some(("parentFolderId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), _ => { - let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "check-validation", "container-id", "enable-all-videos", "event-name", "fingerprint", "interval", "key", "limit", "name", "trigger-id", "type", "unique-trigger-id", "value", "video-percentage-list", "wait-for-tags", "wait-for-tags-timeout"]); + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "check-validation", "container-id", "enable-all-videos", "event-name", "fingerprint", "interval", "key", "limit", "name", "parent-folder-id", "trigger-id", "type", "unique-trigger-id", "value", "video-percentage-list", "wait-for-tags", "wait-for-tags-timeout"]); err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); None } @@ -1833,10 +1598,11 @@ impl<'n, 'a> Engine<'n, 'a> { "fingerprint" => Some(("fingerprint", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "type" => Some(("type", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "parent-folder-id" => Some(("parentFolderId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "disabling-trigger-id" => Some(("disablingTriggerId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), "container-id" => Some(("containerId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), _ => { - let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "container-id", "disabling-trigger-id", "enabling-trigger-id", "fingerprint", "name", "notes", "schedule-end-ms", "schedule-start-ms", "type", "variable-id"]); + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "container-id", "disabling-trigger-id", "enabling-trigger-id", "fingerprint", "name", "notes", "parent-folder-id", "schedule-end-ms", "schedule-start-ms", "type", "variable-id"]); err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); None } @@ -2076,10 +1842,11 @@ impl<'n, 'a> Engine<'n, 'a> { "fingerprint" => Some(("fingerprint", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "account-id" => Some(("accountId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "type" => Some(("type", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "parent-folder-id" => Some(("parentFolderId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "disabling-trigger-id" => Some(("disablingTriggerId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), "container-id" => Some(("containerId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), _ => { - let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "container-id", "disabling-trigger-id", "enabling-trigger-id", "fingerprint", "name", "notes", "schedule-end-ms", "schedule-start-ms", "type", "variable-id"]); + let suggestion = FieldCursor::did_you_mean(key, &vec!["account-id", "container-id", "disabling-trigger-id", "enabling-trigger-id", "fingerprint", "name", "notes", "parent-folder-id", "schedule-end-ms", "schedule-start-ms", "type", "variable-id"]); err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); None } @@ -3181,41 +2948,32 @@ impl<'n, 'a> Engine<'n, 'a> { ("containers-delete", Some(opt)) => { call_result = self._accounts_containers_delete(opt, dry_run, &mut err); }, + ("containers-folders-create", Some(opt)) => { + call_result = self._accounts_containers_folders_create(opt, dry_run, &mut err); + }, + ("containers-folders-delete", Some(opt)) => { + call_result = self._accounts_containers_folders_delete(opt, dry_run, &mut err); + }, + ("containers-folders-entities-list", Some(opt)) => { + call_result = self._accounts_containers_folders_entities_list(opt, dry_run, &mut err); + }, + ("containers-folders-get", Some(opt)) => { + call_result = self._accounts_containers_folders_get(opt, dry_run, &mut err); + }, + ("containers-folders-list", Some(opt)) => { + call_result = self._accounts_containers_folders_list(opt, dry_run, &mut err); + }, + ("containers-folders-update", Some(opt)) => { + call_result = self._accounts_containers_folders_update(opt, dry_run, &mut err); + }, ("containers-get", Some(opt)) => { call_result = self._accounts_containers_get(opt, dry_run, &mut err); }, ("containers-list", Some(opt)) => { call_result = self._accounts_containers_list(opt, dry_run, &mut err); }, - ("containers-macros-create", Some(opt)) => { - call_result = self._accounts_containers_macros_create(opt, dry_run, &mut err); - }, - ("containers-macros-delete", Some(opt)) => { - call_result = self._accounts_containers_macros_delete(opt, dry_run, &mut err); - }, - ("containers-macros-get", Some(opt)) => { - call_result = self._accounts_containers_macros_get(opt, dry_run, &mut err); - }, - ("containers-macros-list", Some(opt)) => { - call_result = self._accounts_containers_macros_list(opt, dry_run, &mut err); - }, - ("containers-macros-update", Some(opt)) => { - call_result = self._accounts_containers_macros_update(opt, dry_run, &mut err); - }, - ("containers-rules-create", Some(opt)) => { - call_result = self._accounts_containers_rules_create(opt, dry_run, &mut err); - }, - ("containers-rules-delete", Some(opt)) => { - call_result = self._accounts_containers_rules_delete(opt, dry_run, &mut err); - }, - ("containers-rules-get", Some(opt)) => { - call_result = self._accounts_containers_rules_get(opt, dry_run, &mut err); - }, - ("containers-rules-list", Some(opt)) => { - call_result = self._accounts_containers_rules_list(opt, dry_run, &mut err); - }, - ("containers-rules-update", Some(opt)) => { - call_result = self._accounts_containers_rules_update(opt, dry_run, &mut err); + ("containers-move-folders-update", Some(opt)) => { + call_result = self._accounts_containers_move_folders_update(opt, dry_run, &mut err); }, ("containers-tags-create", Some(opt)) => { call_result = self._accounts_containers_tags_create(opt, dry_run, &mut err); @@ -3401,7 +3159,7 @@ impl<'n, 'a> Engine<'n, 'a> { fn main() { let mut exit_status = 0i32; let arg_data = [ - ("accounts", "methods: 'containers-create', 'containers-delete', 'containers-get', 'containers-list', 'containers-macros-create', 'containers-macros-delete', 'containers-macros-get', 'containers-macros-list', 'containers-macros-update', 'containers-rules-create', 'containers-rules-delete', 'containers-rules-get', 'containers-rules-list', 'containers-rules-update', 'containers-tags-create', 'containers-tags-delete', 'containers-tags-get', 'containers-tags-list', 'containers-tags-update', 'containers-triggers-create', 'containers-triggers-delete', 'containers-triggers-get', 'containers-triggers-list', 'containers-triggers-update', 'containers-update', 'containers-variables-create', 'containers-variables-delete', 'containers-variables-get', 'containers-variables-list', 'containers-variables-update', 'containers-versions-create', 'containers-versions-delete', 'containers-versions-get', 'containers-versions-list', 'containers-versions-publish', 'containers-versions-restore', 'containers-versions-undelete', 'containers-versions-update', 'get', 'list', 'permissions-create', 'permissions-delete', 'permissions-get', 'permissions-list', 'permissions-update' and 'update'", vec![ + ("accounts", "methods: 'containers-create', 'containers-delete', 'containers-folders-create', 'containers-folders-delete', 'containers-folders-entities-list', 'containers-folders-get', 'containers-folders-list', 'containers-folders-update', 'containers-get', 'containers-list', 'containers-move-folders-update', 'containers-tags-create', 'containers-tags-delete', 'containers-tags-get', 'containers-tags-list', 'containers-tags-update', 'containers-triggers-create', 'containers-triggers-delete', 'containers-triggers-get', 'containers-triggers-list', 'containers-triggers-update', 'containers-update', 'containers-variables-create', 'containers-variables-delete', 'containers-variables-get', 'containers-variables-list', 'containers-variables-update', 'containers-versions-create', 'containers-versions-delete', 'containers-versions-get', 'containers-versions-list', 'containers-versions-publish', 'containers-versions-restore', 'containers-versions-undelete', 'containers-versions-update', 'get', 'list', 'permissions-create', 'permissions-delete', 'permissions-get', 'permissions-list', 'permissions-update' and 'update'", vec![ ("containers-create", Some(r##"Creates a Container."##), "Details at http://byron.github.io/google-apis-rs/google_tagmanager1_cli/accounts_containers-create", @@ -3452,6 +3210,204 @@ fn main() { Some(false), Some(true)), ]), + ("containers-folders-create", + Some(r##"Creates a GTM Folder."##), + "Details at http://byron.github.io/google-apis-rs/google_tagmanager1_cli/accounts_containers-folders-create", + vec![ + (Some(r##"account-id"##), + None, + Some(r##"The GTM Account ID."##), + Some(true), + Some(false)), + + (Some(r##"container-id"##), + None, + Some(r##"The GTM Container ID."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("containers-folders-delete", + Some(r##"Deletes a GTM Folder."##), + "Details at http://byron.github.io/google-apis-rs/google_tagmanager1_cli/accounts_containers-folders-delete", + vec![ + (Some(r##"account-id"##), + None, + Some(r##"The GTM Account ID."##), + Some(true), + Some(false)), + + (Some(r##"container-id"##), + None, + Some(r##"The GTM Container ID."##), + Some(true), + Some(false)), + + (Some(r##"folder-id"##), + None, + Some(r##"The GTM Folder ID."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + ]), + ("containers-folders-entities-list", + Some(r##"List all entities in a GTM Folder."##), + "Details at http://byron.github.io/google-apis-rs/google_tagmanager1_cli/accounts_containers-folders-entities-list", + vec![ + (Some(r##"account-id"##), + None, + Some(r##"The GTM Account ID."##), + Some(true), + Some(false)), + + (Some(r##"container-id"##), + None, + Some(r##"The GTM Container ID."##), + Some(true), + Some(false)), + + (Some(r##"folder-id"##), + None, + Some(r##"The GTM Folder ID."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("containers-folders-get", + Some(r##"Gets a GTM Folder."##), + "Details at http://byron.github.io/google-apis-rs/google_tagmanager1_cli/accounts_containers-folders-get", + vec![ + (Some(r##"account-id"##), + None, + Some(r##"The GTM Account ID."##), + Some(true), + Some(false)), + + (Some(r##"container-id"##), + None, + Some(r##"The GTM Container ID."##), + Some(true), + Some(false)), + + (Some(r##"folder-id"##), + None, + Some(r##"The GTM Folder ID."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("containers-folders-list", + Some(r##"Lists all GTM Folders of a Container."##), + "Details at http://byron.github.io/google-apis-rs/google_tagmanager1_cli/accounts_containers-folders-list", + vec![ + (Some(r##"account-id"##), + None, + Some(r##"The GTM Account ID."##), + Some(true), + Some(false)), + + (Some(r##"container-id"##), + None, + Some(r##"The GTM Container ID."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("containers-folders-update", + Some(r##"Updates a GTM Folder."##), + "Details at http://byron.github.io/google-apis-rs/google_tagmanager1_cli/accounts_containers-folders-update", + vec![ + (Some(r##"account-id"##), + None, + Some(r##"The GTM Account ID."##), + Some(true), + Some(false)), + + (Some(r##"container-id"##), + None, + Some(r##"The GTM Container ID."##), + Some(true), + Some(false)), + + (Some(r##"folder-id"##), + None, + Some(r##"The GTM Folder ID."##), + Some(true), + Some(false)), + + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), ("containers-get", Some(r##"Gets a Container."##), "Details at http://byron.github.io/google-apis-rs/google_tagmanager1_cli/accounts_containers-get", @@ -3502,9 +3458,9 @@ fn main() { Some(false), Some(false)), ]), - ("containers-macros-create", - Some(r##"Creates a GTM Macro."##), - "Details at http://byron.github.io/google-apis-rs/google_tagmanager1_cli/accounts_containers-macros-create", + ("containers-move-folders-update", + Some(r##"Moves entities to a GTM Folder."##), + "Details at http://byron.github.io/google-apis-rs/google_tagmanager1_cli/accounts_containers-move-folders-update", vec![ (Some(r##"account-id"##), None, @@ -3518,43 +3474,9 @@ fn main() { Some(true), Some(false)), - (Some(r##"kv"##), - Some(r##"r"##), - Some(r##"Set various fields of the request structure, matching the key=value form"##), - Some(true), - Some(true)), - - (Some(r##"v"##), - Some(r##"p"##), - Some(r##"Set various optional parameters, matching the key=value form"##), - Some(false), - Some(true)), - - (Some(r##"out"##), - Some(r##"o"##), - Some(r##"Specify the file into which to write the program's output"##), - Some(false), - Some(false)), - ]), - ("containers-macros-delete", - Some(r##"Deletes a GTM Macro."##), - "Details at http://byron.github.io/google-apis-rs/google_tagmanager1_cli/accounts_containers-macros-delete", - vec![ - (Some(r##"account-id"##), + (Some(r##"folder-id"##), None, - Some(r##"The GTM Account ID."##), - Some(true), - Some(false)), - - (Some(r##"container-id"##), - None, - Some(r##"The GTM Container ID."##), - Some(true), - Some(false)), - - (Some(r##"macro-id"##), - None, - Some(r##"The GTM Macro ID."##), + Some(r##"The GTM Folder ID."##), Some(true), Some(false)), @@ -3564,272 +3486,6 @@ fn main() { Some(false), Some(true)), ]), - ("containers-macros-get", - Some(r##"Gets a GTM Macro."##), - "Details at http://byron.github.io/google-apis-rs/google_tagmanager1_cli/accounts_containers-macros-get", - vec![ - (Some(r##"account-id"##), - None, - Some(r##"The GTM Account ID."##), - Some(true), - Some(false)), - - (Some(r##"container-id"##), - None, - Some(r##"The GTM Container ID."##), - Some(true), - Some(false)), - - (Some(r##"macro-id"##), - None, - Some(r##"The GTM Macro ID."##), - Some(true), - Some(false)), - - (Some(r##"v"##), - Some(r##"p"##), - Some(r##"Set various optional parameters, matching the key=value form"##), - Some(false), - Some(true)), - - (Some(r##"out"##), - Some(r##"o"##), - Some(r##"Specify the file into which to write the program's output"##), - Some(false), - Some(false)), - ]), - ("containers-macros-list", - Some(r##"Lists all GTM Macros of a Container."##), - "Details at http://byron.github.io/google-apis-rs/google_tagmanager1_cli/accounts_containers-macros-list", - vec![ - (Some(r##"account-id"##), - None, - Some(r##"The GTM Account ID."##), - Some(true), - Some(false)), - - (Some(r##"container-id"##), - None, - Some(r##"The GTM Container ID."##), - Some(true), - Some(false)), - - (Some(r##"v"##), - Some(r##"p"##), - Some(r##"Set various optional parameters, matching the key=value form"##), - Some(false), - Some(true)), - - (Some(r##"out"##), - Some(r##"o"##), - Some(r##"Specify the file into which to write the program's output"##), - Some(false), - Some(false)), - ]), - ("containers-macros-update", - Some(r##"Updates a GTM Macro."##), - "Details at http://byron.github.io/google-apis-rs/google_tagmanager1_cli/accounts_containers-macros-update", - vec![ - (Some(r##"account-id"##), - None, - Some(r##"The GTM Account ID."##), - Some(true), - Some(false)), - - (Some(r##"container-id"##), - None, - Some(r##"The GTM Container ID."##), - Some(true), - Some(false)), - - (Some(r##"macro-id"##), - None, - Some(r##"The GTM Macro ID."##), - Some(true), - Some(false)), - - (Some(r##"kv"##), - Some(r##"r"##), - Some(r##"Set various fields of the request structure, matching the key=value form"##), - Some(true), - Some(true)), - - (Some(r##"v"##), - Some(r##"p"##), - Some(r##"Set various optional parameters, matching the key=value form"##), - Some(false), - Some(true)), - - (Some(r##"out"##), - Some(r##"o"##), - Some(r##"Specify the file into which to write the program's output"##), - Some(false), - Some(false)), - ]), - ("containers-rules-create", - Some(r##"Creates a GTM Rule."##), - "Details at http://byron.github.io/google-apis-rs/google_tagmanager1_cli/accounts_containers-rules-create", - vec![ - (Some(r##"account-id"##), - None, - Some(r##"The GTM Account ID."##), - Some(true), - Some(false)), - - (Some(r##"container-id"##), - None, - Some(r##"The GTM Container ID."##), - Some(true), - Some(false)), - - (Some(r##"kv"##), - Some(r##"r"##), - Some(r##"Set various fields of the request structure, matching the key=value form"##), - Some(true), - Some(true)), - - (Some(r##"v"##), - Some(r##"p"##), - Some(r##"Set various optional parameters, matching the key=value form"##), - Some(false), - Some(true)), - - (Some(r##"out"##), - Some(r##"o"##), - Some(r##"Specify the file into which to write the program's output"##), - Some(false), - Some(false)), - ]), - ("containers-rules-delete", - Some(r##"Deletes a GTM Rule."##), - "Details at http://byron.github.io/google-apis-rs/google_tagmanager1_cli/accounts_containers-rules-delete", - vec![ - (Some(r##"account-id"##), - None, - Some(r##"The GTM Account ID."##), - Some(true), - Some(false)), - - (Some(r##"container-id"##), - None, - Some(r##"The GTM Container ID."##), - Some(true), - Some(false)), - - (Some(r##"rule-id"##), - None, - Some(r##"The GTM Rule ID."##), - Some(true), - Some(false)), - - (Some(r##"v"##), - Some(r##"p"##), - Some(r##"Set various optional parameters, matching the key=value form"##), - Some(false), - Some(true)), - ]), - ("containers-rules-get", - Some(r##"Gets a GTM Rule."##), - "Details at http://byron.github.io/google-apis-rs/google_tagmanager1_cli/accounts_containers-rules-get", - vec![ - (Some(r##"account-id"##), - None, - Some(r##"The GTM Account ID."##), - Some(true), - Some(false)), - - (Some(r##"container-id"##), - None, - Some(r##"The GTM Container ID."##), - Some(true), - Some(false)), - - (Some(r##"rule-id"##), - None, - Some(r##"The GTM Rule ID."##), - Some(true), - Some(false)), - - (Some(r##"v"##), - Some(r##"p"##), - Some(r##"Set various optional parameters, matching the key=value form"##), - Some(false), - Some(true)), - - (Some(r##"out"##), - Some(r##"o"##), - Some(r##"Specify the file into which to write the program's output"##), - Some(false), - Some(false)), - ]), - ("containers-rules-list", - Some(r##"Lists all GTM Rules of a Container."##), - "Details at http://byron.github.io/google-apis-rs/google_tagmanager1_cli/accounts_containers-rules-list", - vec![ - (Some(r##"account-id"##), - None, - Some(r##"The GTM Account ID."##), - Some(true), - Some(false)), - - (Some(r##"container-id"##), - None, - Some(r##"The GTM Container ID."##), - Some(true), - Some(false)), - - (Some(r##"v"##), - Some(r##"p"##), - Some(r##"Set various optional parameters, matching the key=value form"##), - Some(false), - Some(true)), - - (Some(r##"out"##), - Some(r##"o"##), - Some(r##"Specify the file into which to write the program's output"##), - Some(false), - Some(false)), - ]), - ("containers-rules-update", - Some(r##"Updates a GTM Rule."##), - "Details at http://byron.github.io/google-apis-rs/google_tagmanager1_cli/accounts_containers-rules-update", - vec![ - (Some(r##"account-id"##), - None, - Some(r##"The GTM Account ID."##), - Some(true), - Some(false)), - - (Some(r##"container-id"##), - None, - Some(r##"The GTM Container ID."##), - Some(true), - Some(false)), - - (Some(r##"rule-id"##), - None, - Some(r##"The GTM Rule ID."##), - Some(true), - Some(false)), - - (Some(r##"kv"##), - Some(r##"r"##), - Some(r##"Set various fields of the request structure, matching the key=value form"##), - Some(true), - Some(true)), - - (Some(r##"v"##), - Some(r##"p"##), - Some(r##"Set various optional parameters, matching the key=value form"##), - Some(false), - Some(true)), - - (Some(r##"out"##), - Some(r##"o"##), - Some(r##"Specify the file into which to write the program's output"##), - Some(false), - Some(false)), - ]), ("containers-tags-create", Some(r##"Creates a GTM Tag."##), "Details at http://byron.github.io/google-apis-rs/google_tagmanager1_cli/accounts_containers-tags-create", @@ -4515,7 +4171,7 @@ fn main() { Some(false)), ]), ("containers-versions-restore", - Some(r##"Restores a Container Version. This will overwrite the container's current configuration (including its macros, rules and tags). The operation will not have any effect on the version that is being served (i.e. the published version)."##), + Some(r##"Restores a Container Version. This will overwrite the container's current configuration (including its variables, triggers and tags). The operation will not have any effect on the version that is being served (i.e. the published version)."##), "Details at http://byron.github.io/google-apis-rs/google_tagmanager1_cli/accounts_containers-versions-restore", vec![ (Some(r##"account-id"##), @@ -4828,7 +4484,7 @@ fn main() { let mut app = App::new("tagmanager1") .author("Sebastian Thiel ") - .version("0.3.2+20150526") + .version("0.3.2+20151008") .about("API for accessing Tag Manager accounts and containers.") .after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_tagmanager1_cli") .arg(Arg::with_name("url") diff --git a/gen/tagmanager1/Cargo.toml b/gen/tagmanager1/Cargo.toml index 9eb0300f3a..0bd89dd4d3 100644 --- a/gen/tagmanager1/Cargo.toml +++ b/gen/tagmanager1/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-tagmanager1" -version = "0.1.9+20150526" +version = "0.1.9+20151008" authors = ["Sebastian Thiel "] description = "A complete library to interact with Tag Manager (protocol v1)" repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/tagmanager1" diff --git a/gen/tagmanager1/README.md b/gen/tagmanager1/README.md index fb3452e607..69b15c2f86 100644 --- a/gen/tagmanager1/README.md +++ b/gen/tagmanager1/README.md @@ -5,7 +5,7 @@ DO NOT EDIT ! --> The `google-tagmanager1` library allows access to all features of the *Google Tag Manager* service. -This documentation was generated from *Tag Manager* crate version *0.1.9+20150526*, where *20150526* is the exact revision of the *tagmanager:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +This documentation was generated from *Tag Manager* crate version *0.1.9+20151008*, where *20151008* is the exact revision of the *tagmanager:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. Everything else about the *Tag Manager* *v1* API can be found at the [official documentation site](https://developers.google.com/tag-manager/api/v1/). @@ -14,7 +14,7 @@ Everything else about the *Tag Manager* *v1* API can be found at the Handle the following *Resources* with ease from the central [hub](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.TagManager.html) ... * [accounts](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.Account.html) - * [*containers create*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerCreateCall.html), [*containers delete*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerDeleteCall.html), [*containers get*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerGetCall.html), [*containers list*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerListCall.html), [*containers macros create*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerMacroCreateCall.html), [*containers macros delete*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerMacroDeleteCall.html), [*containers macros get*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerMacroGetCall.html), [*containers macros list*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerMacroListCall.html), [*containers macros update*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerMacroUpdateCall.html), [*containers rules create*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerRuleCreateCall.html), [*containers rules delete*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerRuleDeleteCall.html), [*containers rules get*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerRuleGetCall.html), [*containers rules list*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerRuleListCall.html), [*containers rules update*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerRuleUpdateCall.html), [*containers tags create*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerTagCreateCall.html), [*containers tags delete*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerTagDeleteCall.html), [*containers tags get*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerTagGetCall.html), [*containers tags list*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerTagListCall.html), [*containers tags update*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerTagUpdateCall.html), [*containers triggers create*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerTriggerCreateCall.html), [*containers triggers delete*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerTriggerDeleteCall.html), [*containers triggers get*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerTriggerGetCall.html), [*containers triggers list*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerTriggerListCall.html), [*containers triggers update*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerTriggerUpdateCall.html), [*containers update*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerUpdateCall.html), [*containers variables create*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerVariableCreateCall.html), [*containers variables delete*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerVariableDeleteCall.html), [*containers variables get*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerVariableGetCall.html), [*containers variables list*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerVariableListCall.html), [*containers variables update*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerVariableUpdateCall.html), [*containers versions create*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerVersionCreateCall.html), [*containers versions delete*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerVersionDeleteCall.html), [*containers versions get*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerVersionGetCall.html), [*containers versions list*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerVersionListCall.html), [*containers versions publish*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerVersionPublishCall.html), [*containers versions restore*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerVersionRestoreCall.html), [*containers versions undelete*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerVersionUndeleteCall.html), [*containers versions update*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerVersionUpdateCall.html), [*get*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountGetCall.html), [*list*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountListCall.html), [*permissions create*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountPermissionCreateCall.html), [*permissions delete*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountPermissionDeleteCall.html), [*permissions get*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountPermissionGetCall.html), [*permissions list*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountPermissionListCall.html), [*permissions update*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountPermissionUpdateCall.html) and [*update*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountUpdateCall.html) + * [*containers create*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerCreateCall.html), [*containers delete*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerDeleteCall.html), [*containers folders create*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerFolderCreateCall.html), [*containers folders delete*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerFolderDeleteCall.html), [*containers folders entities list*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerFolderEntityListCall.html), [*containers folders get*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerFolderGetCall.html), [*containers folders list*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerFolderListCall.html), [*containers folders update*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerFolderUpdateCall.html), [*containers get*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerGetCall.html), [*containers list*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerListCall.html), [*containers move_folders update*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerMoveFolderUpdateCall.html), [*containers tags create*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerTagCreateCall.html), [*containers tags delete*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerTagDeleteCall.html), [*containers tags get*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerTagGetCall.html), [*containers tags list*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerTagListCall.html), [*containers tags update*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerTagUpdateCall.html), [*containers triggers create*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerTriggerCreateCall.html), [*containers triggers delete*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerTriggerDeleteCall.html), [*containers triggers get*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerTriggerGetCall.html), [*containers triggers list*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerTriggerListCall.html), [*containers triggers update*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerTriggerUpdateCall.html), [*containers update*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerUpdateCall.html), [*containers variables create*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerVariableCreateCall.html), [*containers variables delete*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerVariableDeleteCall.html), [*containers variables get*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerVariableGetCall.html), [*containers variables list*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerVariableListCall.html), [*containers variables update*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerVariableUpdateCall.html), [*containers versions create*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerVersionCreateCall.html), [*containers versions delete*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerVersionDeleteCall.html), [*containers versions get*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerVersionGetCall.html), [*containers versions list*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerVersionListCall.html), [*containers versions publish*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerVersionPublishCall.html), [*containers versions restore*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerVersionRestoreCall.html), [*containers versions undelete*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerVersionUndeleteCall.html), [*containers versions update*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountContainerVersionUpdateCall.html), [*get*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountGetCall.html), [*list*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountListCall.html), [*permissions create*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountPermissionCreateCall.html), [*permissions delete*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountPermissionDeleteCall.html), [*permissions get*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountPermissionGetCall.html), [*permissions list*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountPermissionListCall.html), [*permissions update*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountPermissionUpdateCall.html) and [*update*](http://byron.github.io/google-apis-rs/google_tagmanager1/struct.AccountUpdateCall.html) @@ -49,7 +49,7 @@ Or specifically ... ```ignore let r = hub.accounts().containers_list(...).doit() let r = hub.accounts().permissions_list(...).doit() -let r = hub.accounts().containers_versions_undelete(...).doit() +let r = hub.accounts().containers_create(...).doit() let r = hub.accounts().permissions_create(...).doit() let r = hub.accounts().permissions_delete(...).doit() let r = hub.accounts().containers_get(...).doit() @@ -57,39 +57,36 @@ let r = hub.accounts().containers_versions_list(...).doit() let r = hub.accounts().containers_triggers_update(...).doit() let r = hub.accounts().containers_triggers_get(...).doit() let r = hub.accounts().containers_delete(...).doit() -let r = hub.accounts().containers_create(...).doit() +let r = hub.accounts().containers_folders_delete(...).doit() let r = hub.accounts().containers_tags_delete(...).doit() -let r = hub.accounts().containers_rules_update(...).doit() -let r = hub.accounts().containers_rules_delete(...).doit() +let r = hub.accounts().containers_folders_entities_list(...).doit() +let r = hub.accounts().containers_versions_undelete(...).doit() let r = hub.accounts().containers_tags_list(...).doit() let r = hub.accounts().containers_versions_publish(...).doit() +let r = hub.accounts().containers_folders_get(...).doit() let r = hub.accounts().containers_tags_create(...).doit() let r = hub.accounts().containers_triggers_list(...).doit() let r = hub.accounts().containers_versions_delete(...).doit() let r = hub.accounts().update(...).doit() -let r = hub.accounts().containers_macros_delete(...).doit() let r = hub.accounts().containers_versions_create(...).doit() let r = hub.accounts().permissions_get(...).doit() -let r = hub.accounts().containers_rules_create(...).doit() +let r = hub.accounts().containers_move_folders_update(...).doit() let r = hub.accounts().containers_versions_restore(...).doit() -let r = hub.accounts().containers_rules_get(...).doit() let r = hub.accounts().containers_variables_create(...).doit() let r = hub.accounts().containers_variables_list(...).doit() -let r = hub.accounts().containers_macros_create(...).doit() let r = hub.accounts().containers_tags_get(...).doit() let r = hub.accounts().containers_variables_get(...).doit() let r = hub.accounts().containers_triggers_delete(...).doit() -let r = hub.accounts().containers_macros_list(...).doit() let r = hub.accounts().containers_triggers_create(...).doit() -let r = hub.accounts().containers_macros_update(...).doit() +let r = hub.accounts().containers_folders_update(...).doit() let r = hub.accounts().list(...).doit() let r = hub.accounts().permissions_update(...).doit() let r = hub.accounts().containers_variables_delete(...).doit() let r = hub.accounts().get(...).doit() let r = hub.accounts().containers_update(...).doit() -let r = hub.accounts().containers_rules_list(...).doit() let r = hub.accounts().containers_tags_update(...).doit() -let r = hub.accounts().containers_macros_get(...).doit() +let r = hub.accounts().containers_folders_create(...).doit() +let r = hub.accounts().containers_folders_list(...).doit() let r = hub.accounts().containers_versions_update(...).doit() let r = hub.accounts().containers_variables_update(...).doit() let r = hub.accounts().containers_versions_get(...).doit() @@ -117,7 +114,6 @@ google-tagmanager1 = "*" extern crate hyper; extern crate yup_oauth2 as oauth2; extern crate google_tagmanager1 as tagmanager1; -use tagmanager1::Trigger; use tagmanager1::{Result, Error}; use std::default::Default; use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; @@ -135,16 +131,13 @@ let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, hyper::Client::new(), ::default(), None); let mut hub = TagManager::new(hyper::Client::new(), auth); -// As the method needs a request, you would usually fill it with the desired information -// into the respective structure. Some of the parts shown here might not be applicable ! -// Values shown here are possibly random and not representative ! -let mut req = Trigger::default(); - // You can configure optional parameters by calling 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().containers_triggers_update(req, "accountId", "containerId", "triggerId") - .fingerprint("sed") +let result = hub.accounts().containers_move_folders_update("accountId", "containerId", "folderId") + .add_variable_id("sed") + .add_trigger_id("et") + .add_tag_id("dolores") .doit(); match result { diff --git a/gen/tagmanager1/src/lib.rs b/gen/tagmanager1/src/lib.rs index 9e50c9516d..40ecfb7d68 100644 --- a/gen/tagmanager1/src/lib.rs +++ b/gen/tagmanager1/src/lib.rs @@ -2,7 +2,7 @@ // This file was generated automatically from 'src/mako/api/lib.rs.mako' // DO NOT EDIT ! -//! This documentation was generated from *Tag Manager* crate version *0.1.9+20150526*, where *20150526* is the exact revision of the *tagmanager:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +//! This documentation was generated from *Tag Manager* crate version *0.1.9+20151008*, where *20151008* is the exact revision of the *tagmanager:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. //! //! Everything else about the *Tag Manager* *v1* API can be found at the //! [official documentation site](https://developers.google.com/tag-manager/api/v1/). @@ -12,7 +12,7 @@ //! Handle the following *Resources* with ease from the central [hub](struct.TagManager.html) ... //! //! * [accounts](struct.Account.html) -//! * [*containers create*](struct.AccountContainerCreateCall.html), [*containers delete*](struct.AccountContainerDeleteCall.html), [*containers get*](struct.AccountContainerGetCall.html), [*containers list*](struct.AccountContainerListCall.html), [*containers macros create*](struct.AccountContainerMacroCreateCall.html), [*containers macros delete*](struct.AccountContainerMacroDeleteCall.html), [*containers macros get*](struct.AccountContainerMacroGetCall.html), [*containers macros list*](struct.AccountContainerMacroListCall.html), [*containers macros update*](struct.AccountContainerMacroUpdateCall.html), [*containers rules create*](struct.AccountContainerRuleCreateCall.html), [*containers rules delete*](struct.AccountContainerRuleDeleteCall.html), [*containers rules get*](struct.AccountContainerRuleGetCall.html), [*containers rules list*](struct.AccountContainerRuleListCall.html), [*containers rules update*](struct.AccountContainerRuleUpdateCall.html), [*containers tags create*](struct.AccountContainerTagCreateCall.html), [*containers tags delete*](struct.AccountContainerTagDeleteCall.html), [*containers tags get*](struct.AccountContainerTagGetCall.html), [*containers tags list*](struct.AccountContainerTagListCall.html), [*containers tags update*](struct.AccountContainerTagUpdateCall.html), [*containers triggers create*](struct.AccountContainerTriggerCreateCall.html), [*containers triggers delete*](struct.AccountContainerTriggerDeleteCall.html), [*containers triggers get*](struct.AccountContainerTriggerGetCall.html), [*containers triggers list*](struct.AccountContainerTriggerListCall.html), [*containers triggers update*](struct.AccountContainerTriggerUpdateCall.html), [*containers update*](struct.AccountContainerUpdateCall.html), [*containers variables create*](struct.AccountContainerVariableCreateCall.html), [*containers variables delete*](struct.AccountContainerVariableDeleteCall.html), [*containers variables get*](struct.AccountContainerVariableGetCall.html), [*containers variables list*](struct.AccountContainerVariableListCall.html), [*containers variables update*](struct.AccountContainerVariableUpdateCall.html), [*containers versions create*](struct.AccountContainerVersionCreateCall.html), [*containers versions delete*](struct.AccountContainerVersionDeleteCall.html), [*containers versions get*](struct.AccountContainerVersionGetCall.html), [*containers versions list*](struct.AccountContainerVersionListCall.html), [*containers versions publish*](struct.AccountContainerVersionPublishCall.html), [*containers versions restore*](struct.AccountContainerVersionRestoreCall.html), [*containers versions undelete*](struct.AccountContainerVersionUndeleteCall.html), [*containers versions update*](struct.AccountContainerVersionUpdateCall.html), [*get*](struct.AccountGetCall.html), [*list*](struct.AccountListCall.html), [*permissions create*](struct.AccountPermissionCreateCall.html), [*permissions delete*](struct.AccountPermissionDeleteCall.html), [*permissions get*](struct.AccountPermissionGetCall.html), [*permissions list*](struct.AccountPermissionListCall.html), [*permissions update*](struct.AccountPermissionUpdateCall.html) and [*update*](struct.AccountUpdateCall.html) +//! * [*containers create*](struct.AccountContainerCreateCall.html), [*containers delete*](struct.AccountContainerDeleteCall.html), [*containers folders create*](struct.AccountContainerFolderCreateCall.html), [*containers folders delete*](struct.AccountContainerFolderDeleteCall.html), [*containers folders entities list*](struct.AccountContainerFolderEntityListCall.html), [*containers folders get*](struct.AccountContainerFolderGetCall.html), [*containers folders list*](struct.AccountContainerFolderListCall.html), [*containers folders update*](struct.AccountContainerFolderUpdateCall.html), [*containers get*](struct.AccountContainerGetCall.html), [*containers list*](struct.AccountContainerListCall.html), [*containers move_folders update*](struct.AccountContainerMoveFolderUpdateCall.html), [*containers tags create*](struct.AccountContainerTagCreateCall.html), [*containers tags delete*](struct.AccountContainerTagDeleteCall.html), [*containers tags get*](struct.AccountContainerTagGetCall.html), [*containers tags list*](struct.AccountContainerTagListCall.html), [*containers tags update*](struct.AccountContainerTagUpdateCall.html), [*containers triggers create*](struct.AccountContainerTriggerCreateCall.html), [*containers triggers delete*](struct.AccountContainerTriggerDeleteCall.html), [*containers triggers get*](struct.AccountContainerTriggerGetCall.html), [*containers triggers list*](struct.AccountContainerTriggerListCall.html), [*containers triggers update*](struct.AccountContainerTriggerUpdateCall.html), [*containers update*](struct.AccountContainerUpdateCall.html), [*containers variables create*](struct.AccountContainerVariableCreateCall.html), [*containers variables delete*](struct.AccountContainerVariableDeleteCall.html), [*containers variables get*](struct.AccountContainerVariableGetCall.html), [*containers variables list*](struct.AccountContainerVariableListCall.html), [*containers variables update*](struct.AccountContainerVariableUpdateCall.html), [*containers versions create*](struct.AccountContainerVersionCreateCall.html), [*containers versions delete*](struct.AccountContainerVersionDeleteCall.html), [*containers versions get*](struct.AccountContainerVersionGetCall.html), [*containers versions list*](struct.AccountContainerVersionListCall.html), [*containers versions publish*](struct.AccountContainerVersionPublishCall.html), [*containers versions restore*](struct.AccountContainerVersionRestoreCall.html), [*containers versions undelete*](struct.AccountContainerVersionUndeleteCall.html), [*containers versions update*](struct.AccountContainerVersionUpdateCall.html), [*get*](struct.AccountGetCall.html), [*list*](struct.AccountListCall.html), [*permissions create*](struct.AccountPermissionCreateCall.html), [*permissions delete*](struct.AccountPermissionDeleteCall.html), [*permissions get*](struct.AccountPermissionGetCall.html), [*permissions list*](struct.AccountPermissionListCall.html), [*permissions update*](struct.AccountPermissionUpdateCall.html) and [*update*](struct.AccountUpdateCall.html) //! //! //! @@ -49,7 +49,7 @@ //! ```ignore //! let r = hub.accounts().containers_list(...).doit() //! let r = hub.accounts().permissions_list(...).doit() -//! let r = hub.accounts().containers_versions_undelete(...).doit() +//! let r = hub.accounts().containers_create(...).doit() //! let r = hub.accounts().permissions_create(...).doit() //! let r = hub.accounts().permissions_delete(...).doit() //! let r = hub.accounts().containers_get(...).doit() @@ -57,39 +57,36 @@ //! let r = hub.accounts().containers_triggers_update(...).doit() //! let r = hub.accounts().containers_triggers_get(...).doit() //! let r = hub.accounts().containers_delete(...).doit() -//! let r = hub.accounts().containers_create(...).doit() +//! let r = hub.accounts().containers_folders_delete(...).doit() //! let r = hub.accounts().containers_tags_delete(...).doit() -//! let r = hub.accounts().containers_rules_update(...).doit() -//! let r = hub.accounts().containers_rules_delete(...).doit() +//! let r = hub.accounts().containers_folders_entities_list(...).doit() +//! let r = hub.accounts().containers_versions_undelete(...).doit() //! let r = hub.accounts().containers_tags_list(...).doit() //! let r = hub.accounts().containers_versions_publish(...).doit() +//! let r = hub.accounts().containers_folders_get(...).doit() //! let r = hub.accounts().containers_tags_create(...).doit() //! let r = hub.accounts().containers_triggers_list(...).doit() //! let r = hub.accounts().containers_versions_delete(...).doit() //! let r = hub.accounts().update(...).doit() -//! let r = hub.accounts().containers_macros_delete(...).doit() //! let r = hub.accounts().containers_versions_create(...).doit() //! let r = hub.accounts().permissions_get(...).doit() -//! let r = hub.accounts().containers_rules_create(...).doit() +//! let r = hub.accounts().containers_move_folders_update(...).doit() //! let r = hub.accounts().containers_versions_restore(...).doit() -//! let r = hub.accounts().containers_rules_get(...).doit() //! let r = hub.accounts().containers_variables_create(...).doit() //! let r = hub.accounts().containers_variables_list(...).doit() -//! let r = hub.accounts().containers_macros_create(...).doit() //! let r = hub.accounts().containers_tags_get(...).doit() //! let r = hub.accounts().containers_variables_get(...).doit() //! let r = hub.accounts().containers_triggers_delete(...).doit() -//! let r = hub.accounts().containers_macros_list(...).doit() //! let r = hub.accounts().containers_triggers_create(...).doit() -//! let r = hub.accounts().containers_macros_update(...).doit() +//! let r = hub.accounts().containers_folders_update(...).doit() //! let r = hub.accounts().list(...).doit() //! let r = hub.accounts().permissions_update(...).doit() //! let r = hub.accounts().containers_variables_delete(...).doit() //! let r = hub.accounts().get(...).doit() //! let r = hub.accounts().containers_update(...).doit() -//! let r = hub.accounts().containers_rules_list(...).doit() //! let r = hub.accounts().containers_tags_update(...).doit() -//! let r = hub.accounts().containers_macros_get(...).doit() +//! let r = hub.accounts().containers_folders_create(...).doit() +//! let r = hub.accounts().containers_folders_list(...).doit() //! let r = hub.accounts().containers_versions_update(...).doit() //! let r = hub.accounts().containers_variables_update(...).doit() //! let r = hub.accounts().containers_versions_get(...).doit() @@ -117,7 +114,6 @@ //! extern crate hyper; //! extern crate yup_oauth2 as oauth2; //! extern crate google_tagmanager1 as tagmanager1; -//! use tagmanager1::Trigger; //! use tagmanager1::{Result, Error}; //! # #[test] fn egal() { //! use std::default::Default; @@ -136,16 +132,13 @@ //! hyper::Client::new(), //! ::default(), None); //! let mut hub = TagManager::new(hyper::Client::new(), auth); -//! // As the method needs a request, you would usually fill it with the desired information -//! // into the respective structure. Some of the parts shown here might not be applicable ! -//! // Values shown here are possibly random and not representative ! -//! let mut req = Trigger::default(); -//! //! // You can configure optional parameters by calling 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().containers_triggers_update(req, "accountId", "containerId", "triggerId") -//! .fingerprint("diam") +//! let result = hub.accounts().containers_move_folders_update("accountId", "containerId", "folderId") +//! .add_variable_id("clita") +//! .add_trigger_id("diam") +//! .add_tag_id("justo") //! .doit(); //! //! match result { diff --git a/gen/tagmanager1/src/lib.rs.in b/gen/tagmanager1/src/lib.rs.in index 0e06c37967..193de4187a 100644 --- a/gen/tagmanager1/src/lib.rs.in +++ b/gen/tagmanager1/src/lib.rs.in @@ -93,7 +93,6 @@ impl Default for Scope { /// extern crate hyper; /// extern crate yup_oauth2 as oauth2; /// extern crate google_tagmanager1 as tagmanager1; -/// use tagmanager1::Trigger; /// use tagmanager1::{Result, Error}; /// # #[test] fn egal() { /// use std::default::Default; @@ -112,16 +111,13 @@ impl Default for Scope { /// hyper::Client::new(), /// ::default(), None); /// let mut hub = TagManager::new(hyper::Client::new(), auth); -/// // As the method needs a request, you would usually fill it with the desired information -/// // into the respective structure. Some of the parts shown here might not be applicable ! -/// // Values shown here are possibly random and not representative ! -/// let mut req = Trigger::default(); -/// /// // You can configure optional parameters by calling 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().containers_triggers_update(req, "accountId", "containerId", "triggerId") -/// .fingerprint("accusam") +/// let result = hub.accounts().containers_move_folders_update("accountId", "containerId", "folderId") +/// .add_variable_id("justo") +/// .add_trigger_id("amet.") +/// .add_tag_id("erat") /// .doit(); /// /// match result { @@ -180,24 +176,6 @@ impl<'a, C, A> TagManager // ############ // SCHEMAS ### // ########## -/// List Macros 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*). -/// -/// * [containers macros list accounts](struct.AccountContainerMacroListCall.html) (response) -/// -#[derive(Default, Clone, Debug, Serialize, Deserialize)] -pub struct ListMacrosResponse { - /// All GTM Macros of a GTM Container. - pub macros: Option>, -} - -impl ResponseResult for ListMacrosResponse {} - - /// Defines the Google Tag Manager Account access permissions. /// /// This type is not used in any activity, and only used as *part* of another schema. @@ -233,9 +211,15 @@ pub struct Tag { /// GTM Container ID. #[serde(rename="containerId")] pub container_id: Option, + /// Option to fire this tag. + #[serde(rename="tagFiringOption")] + pub tag_firing_option: Option, /// The Tag ID uniquely identifies the GTM Tag. #[serde(rename="tagId")] pub tag_id: Option, + /// The list of setup tags. Currently we only allow one. + #[serde(rename="setupTag")] + pub setup_tag: Option>, /// Blocking rule IDs. If any of the listed rules evaluate to true, the tag will not fire. #[serde(rename="blockingRuleId")] pub blocking_rule_id: Option>, @@ -250,12 +234,18 @@ pub struct Tag { /// GTM Account ID. #[serde(rename="accountId")] pub account_id: Option, + /// The list of teardown tags. Currently we only allow one. + #[serde(rename="teardownTag")] + pub teardown_tag: Option>, /// Tag display name. pub name: Option, /// The tag's parameters. pub parameter: Option>, /// User notes on how to apply this tag in the container. pub notes: Option, + /// Parent folder id. + #[serde(rename="parentFolderId")] + pub parent_folder_id: Option, /// User defined numeric priority of the tag. Tags are fired asynchronously in order of priority. Tags with higher numeric value fire first. A tag's priority can be a positive or negative value. The default value is 0. pub priority: Option, /// If set to true, this tag will only fire in the live environment (e.g. not in preview or debug mode). @@ -342,14 +332,7 @@ impl ResponseResult for ListContainersResponse {} /// Represents a Google Tag Manager Macro. /// -/// # Activities -/// -/// This type is used in activities, which are methods you may call on this type or where this type is involved in. -/// The list links the activity name, along with information about where it is used (one of *request* and *response*). -/// -/// * [containers macros create accounts](struct.AccountContainerMacroCreateCall.html) (request|response) -/// * [containers macros get accounts](struct.AccountContainerMacroGetCall.html) (response) -/// * [containers macros update accounts](struct.AccountContainerMacroUpdateCall.html) (request|response) +/// This type is not used in any activity, and only used as *part* of another schema. /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct Macro { @@ -383,12 +366,14 @@ pub struct Macro { /// GTM Macro Type. #[serde(rename="type")] pub type_: Option, + /// Parent folder id. + #[serde(rename="parentFolderId")] + pub parent_folder_id: Option, /// Macro display name. pub name: Option, } -impl RequestValue for Macro {} -impl ResponseResult for Macro {} +impl Part for Macro {} /// List Variables Response. @@ -418,7 +403,7 @@ impl ResponseResult for ListVariablesResponse {} /// /// * [containers list accounts](struct.AccountContainerListCall.html) (none) /// * [permissions list accounts](struct.AccountPermissionListCall.html) (none) -/// * [containers versions undelete accounts](struct.AccountContainerVersionUndeleteCall.html) (none) +/// * [containers create accounts](struct.AccountContainerCreateCall.html) (none) /// * [permissions create accounts](struct.AccountPermissionCreateCall.html) (none) /// * [permissions delete accounts](struct.AccountPermissionDeleteCall.html) (none) /// * [containers get accounts](struct.AccountContainerGetCall.html) (none) @@ -426,39 +411,36 @@ impl ResponseResult for ListVariablesResponse {} /// * [containers triggers update accounts](struct.AccountContainerTriggerUpdateCall.html) (none) /// * [containers triggers get accounts](struct.AccountContainerTriggerGetCall.html) (none) /// * [containers delete accounts](struct.AccountContainerDeleteCall.html) (none) -/// * [containers create accounts](struct.AccountContainerCreateCall.html) (none) +/// * [containers folders delete accounts](struct.AccountContainerFolderDeleteCall.html) (none) /// * [containers tags delete accounts](struct.AccountContainerTagDeleteCall.html) (none) -/// * [containers rules update accounts](struct.AccountContainerRuleUpdateCall.html) (none) -/// * [containers rules delete accounts](struct.AccountContainerRuleDeleteCall.html) (none) +/// * [containers folders entities list accounts](struct.AccountContainerFolderEntityListCall.html) (none) +/// * [containers versions undelete accounts](struct.AccountContainerVersionUndeleteCall.html) (none) /// * [containers tags list accounts](struct.AccountContainerTagListCall.html) (none) /// * [containers versions publish accounts](struct.AccountContainerVersionPublishCall.html) (none) +/// * [containers folders get accounts](struct.AccountContainerFolderGetCall.html) (none) /// * [containers tags create accounts](struct.AccountContainerTagCreateCall.html) (none) /// * [containers triggers list accounts](struct.AccountContainerTriggerListCall.html) (none) /// * [containers versions delete accounts](struct.AccountContainerVersionDeleteCall.html) (none) /// * [update accounts](struct.AccountUpdateCall.html) (request|response) -/// * [containers macros delete accounts](struct.AccountContainerMacroDeleteCall.html) (none) /// * [containers versions create accounts](struct.AccountContainerVersionCreateCall.html) (none) /// * [permissions get accounts](struct.AccountPermissionGetCall.html) (none) -/// * [containers rules create accounts](struct.AccountContainerRuleCreateCall.html) (none) +/// * [containers move_folders update accounts](struct.AccountContainerMoveFolderUpdateCall.html) (none) /// * [containers versions restore accounts](struct.AccountContainerVersionRestoreCall.html) (none) -/// * [containers rules get accounts](struct.AccountContainerRuleGetCall.html) (none) /// * [containers variables create accounts](struct.AccountContainerVariableCreateCall.html) (none) /// * [containers variables list accounts](struct.AccountContainerVariableListCall.html) (none) -/// * [containers macros create accounts](struct.AccountContainerMacroCreateCall.html) (none) /// * [containers tags get accounts](struct.AccountContainerTagGetCall.html) (none) /// * [containers variables get accounts](struct.AccountContainerVariableGetCall.html) (none) /// * [containers triggers delete accounts](struct.AccountContainerTriggerDeleteCall.html) (none) -/// * [containers macros list accounts](struct.AccountContainerMacroListCall.html) (none) /// * [containers triggers create accounts](struct.AccountContainerTriggerCreateCall.html) (none) -/// * [containers macros update accounts](struct.AccountContainerMacroUpdateCall.html) (none) +/// * [containers folders update accounts](struct.AccountContainerFolderUpdateCall.html) (none) /// * [list accounts](struct.AccountListCall.html) (none) /// * [permissions update accounts](struct.AccountPermissionUpdateCall.html) (none) /// * [containers variables delete accounts](struct.AccountContainerVariableDeleteCall.html) (none) /// * [get accounts](struct.AccountGetCall.html) (response) /// * [containers update accounts](struct.AccountContainerUpdateCall.html) (none) -/// * [containers rules list accounts](struct.AccountContainerRuleListCall.html) (none) /// * [containers tags update accounts](struct.AccountContainerTagUpdateCall.html) (none) -/// * [containers macros get accounts](struct.AccountContainerMacroGetCall.html) (none) +/// * [containers folders create accounts](struct.AccountContainerFolderCreateCall.html) (none) +/// * [containers folders list accounts](struct.AccountContainerFolderListCall.html) (none) /// * [containers versions update accounts](struct.AccountContainerVersionUpdateCall.html) (none) /// * [containers variables update accounts](struct.AccountContainerVariableUpdateCall.html) (none) /// * [containers versions get accounts](struct.AccountContainerVersionGetCall.html) (none) @@ -484,14 +466,7 @@ impl ResponseResult for Account {} /// Represents a Google Tag Manager Rule. /// -/// # Activities -/// -/// This type is used in activities, which are methods you may call on this type or where this type is involved in. -/// The list links the activity name, along with information about where it is used (one of *request* and *response*). -/// -/// * [containers rules get accounts](struct.AccountContainerRuleGetCall.html) (response) -/// * [containers rules create accounts](struct.AccountContainerRuleCreateCall.html) (request|response) -/// * [containers rules update accounts](struct.AccountContainerRuleUpdateCall.html) (request|response) +/// This type is not used in any activity, and only used as *part* of another schema. /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct Rule { @@ -514,8 +489,7 @@ pub struct Rule { pub account_id: Option, } -impl RequestValue for Rule {} -impl ResponseResult for Rule {} +impl Part for Rule {} /// List Accounts Response. @@ -558,6 +532,28 @@ pub struct PublishContainerVersionResponse { impl ResponseResult for PublishContainerVersionResponse {} +/// Represents a Google Tag Manager Folder's contents. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [containers folders entities list accounts](struct.AccountContainerFolderEntityListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct FolderEntities { + /// The list of variables inside the folder. + pub variable: Option>, + /// The list of triggers inside the folder. + pub trigger: Option>, + /// The list of tags inside the folder. + pub tag: Option>, +} + +impl ResponseResult for FolderEntities {} + + /// Represents a Google Tag Manager Trigger /// /// # Activities @@ -620,6 +616,9 @@ pub struct Trigger { /// Defines the data layer event that causes this trigger. #[serde(rename="type")] pub type_: Option, + /// Parent folder id. + #[serde(rename="parentFolderId")] + pub parent_folder_id: Option, } impl RequestValue for Trigger {} @@ -648,24 +647,6 @@ pub struct CreateContainerVersionResponse { impl ResponseResult for CreateContainerVersionResponse {} -/// List Rules 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*). -/// -/// * [containers rules list accounts](struct.AccountContainerRuleListCall.html) (response) -/// -#[derive(Default, Clone, Debug, Serialize, Deserialize)] -pub struct ListRulesResponse { - /// All GTM Rules of a GTM Container. - pub rules: Option>, -} - -impl ResponseResult for ListRulesResponse {} - - /// Defines the Google Tag Manager Container access permissions. /// /// This type is not used in any activity, and only used as *part* of another schema. @@ -716,6 +697,38 @@ impl RequestValue for UserAccess {} impl ResponseResult for UserAccess {} +/// Represents a Google Tag Manager Folder. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where this type is involved in. +/// The list links the activity name, along with information about where it is used (one of *request* and *response*). +/// +/// * [containers folders update accounts](struct.AccountContainerFolderUpdateCall.html) (request|response) +/// * [containers folders create accounts](struct.AccountContainerFolderCreateCall.html) (request|response) +/// * [containers folders get accounts](struct.AccountContainerFolderGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Folder { + /// The Folder ID uniquely identifies the GTM Folder. + #[serde(rename="folderId")] + pub folder_id: Option, + /// GTM Account ID. + #[serde(rename="accountId")] + pub account_id: Option, + /// GTM Container ID. + #[serde(rename="containerId")] + pub container_id: Option, + /// Folder display name. + pub name: Option, + /// The fingerprint of the GTM Folder as computed at storage time. This value is recomputed whenever the folder is modified. + pub fingerprint: Option, +} + +impl RequestValue for Folder {} +impl ResponseResult for Folder {} + + /// Represents a Google Tag Manager Parameter. /// /// This type is not used in any activity, and only used as *part* of another schema. @@ -728,14 +741,14 @@ pub struct Parameter { pub list: Option>, /// The named key that uniquely identifies a parameter. Required for top-level parameters, as well as map values. Ignored for list values. pub key: Option, - /// A parameter's value (may contain macro references such as "{{myMacro}}") as appropriate to the specified type. + /// A parameter's value (may contain variable references such as "{{myVariable}}") as appropriate to the specified type. pub value: Option, /// The parameter type. Valid values are: /// - boolean: The value represents a boolean, represented as 'true' or 'false' /// - integer: The value represents a 64-bit signed integer value, in base 10 /// - list: A list of parameters should be specified /// - map: A map of parameters should be specified - /// - template: The value represents any text; this can include macro references (even macro references that might return non-string types) + /// - template: The value represents any text; this can include variable references (even variable references that might return non-string types) #[serde(rename="type")] pub type_: Option, } @@ -761,6 +774,24 @@ pub struct ListTagsResponse { impl ResponseResult for ListTagsResponse {} +/// List Folders 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*). +/// +/// * [containers folders list accounts](struct.AccountContainerFolderListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ListFoldersResponse { + /// All GTM Folders of a GTM Container. + pub folders: Option>, +} + +impl ResponseResult for ListFoldersResponse {} + + /// List AccountUsers Response. /// /// # Activities @@ -821,6 +852,23 @@ pub struct ListTriggersResponse { impl ResponseResult for ListTriggersResponse {} +/// 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 SetupTag { + /// If true, fire the main tag if and only if the setup tag fires successfully. If false, fire the main tag regardless of setup tag firing status. + #[serde(rename="stopOnSetupFailure")] + pub stop_on_setup_failure: Option, + /// The name of the setup tag. + #[serde(rename="tagName")] + pub tag_name: Option, +} + +impl Part for SetupTag {} + + /// Represents a Google Tag Manager Container Version Header. /// /// This type is not used in any activity, and only used as *part* of another schema. @@ -899,6 +947,8 @@ pub struct ContainerVersion { pub fingerprint: Option, /// The variables in the container that this version was taken from. pub variable: Option>, + /// The folders in the container that this version was taken from. + pub folder: Option>, /// GTM Account ID. #[serde(rename="accountId")] pub account_id: Option, @@ -971,6 +1021,9 @@ pub struct Variable { /// GTM Variable Type. #[serde(rename="type")] pub type_: Option, + /// Parent folder id. + #[serde(rename="parentFolderId")] + pub parent_folder_id: Option, /// For mobile containers only: A list of trigger IDs for disabling conditional variables; the variable is enabled if one of the enabling trigger is true while all the disabling trigger are false. Treated as an unordered set. #[serde(rename="disablingTriggerId")] pub disabling_trigger_id: Option>, @@ -983,6 +1036,23 @@ impl RequestValue for Variable {} impl ResponseResult for Variable {} +/// 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 TeardownTag { + /// If true, fire the teardown tag if and only if the main tag fires successfully. If false, fire the teardown tag regardless of main tag firing status. + #[serde(rename="stopTeardownOnFailure")] + pub stop_teardown_on_failure: Option, + /// The name of the teardown tag. + #[serde(rename="tagName")] + pub tag_name: Option, +} + +impl Part for TeardownTag {} + + /// Represents a predicate. /// /// This type is not used in any activity, and only used as *part* of another schema. @@ -991,7 +1061,7 @@ impl ResponseResult for Variable {} pub struct Condition { /// A list of named parameters (key/value), depending on the condition's type. Notes: /// - For binary operators, include parameters named arg0 and arg1 for specifying the left and right operands, respectively. - /// - At this time, the left operand (arg0) must be a reference to a macro. + /// - At this time, the left operand (arg0) must be a reference to a variable. /// - For case-insensitive Regex matching, include a boolean parameter named ignore_case that is set to true. If not specified or set to any other value, the matching will be case sensitive. /// - To negate an operator, include a boolean parameter named negate boolean parameter that is set to true. pub parameter: Option>, @@ -1031,7 +1101,7 @@ impl Part for Condition {} /// ::default(), None); /// let mut hub = TagManager::new(hyper::Client::new(), auth); /// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* -/// // like `containers_create(...)`, `containers_delete(...)`, `containers_get(...)`, `containers_list(...)`, `containers_macros_create(...)`, `containers_macros_delete(...)`, `containers_macros_get(...)`, `containers_macros_list(...)`, `containers_macros_update(...)`, `containers_rules_create(...)`, `containers_rules_delete(...)`, `containers_rules_get(...)`, `containers_rules_list(...)`, `containers_rules_update(...)`, `containers_tags_create(...)`, `containers_tags_delete(...)`, `containers_tags_get(...)`, `containers_tags_list(...)`, `containers_tags_update(...)`, `containers_triggers_create(...)`, `containers_triggers_delete(...)`, `containers_triggers_get(...)`, `containers_triggers_list(...)`, `containers_triggers_update(...)`, `containers_update(...)`, `containers_variables_create(...)`, `containers_variables_delete(...)`, `containers_variables_get(...)`, `containers_variables_list(...)`, `containers_variables_update(...)`, `containers_versions_create(...)`, `containers_versions_delete(...)`, `containers_versions_get(...)`, `containers_versions_list(...)`, `containers_versions_publish(...)`, `containers_versions_restore(...)`, `containers_versions_undelete(...)`, `containers_versions_update(...)`, `get(...)`, `list(...)`, `permissions_create(...)`, `permissions_delete(...)`, `permissions_get(...)`, `permissions_list(...)`, `permissions_update(...)` and `update(...)` +/// // like `containers_create(...)`, `containers_delete(...)`, `containers_folders_create(...)`, `containers_folders_delete(...)`, `containers_folders_entities_list(...)`, `containers_folders_get(...)`, `containers_folders_list(...)`, `containers_folders_update(...)`, `containers_get(...)`, `containers_list(...)`, `containers_move_folders_update(...)`, `containers_tags_create(...)`, `containers_tags_delete(...)`, `containers_tags_get(...)`, `containers_tags_list(...)`, `containers_tags_update(...)`, `containers_triggers_create(...)`, `containers_triggers_delete(...)`, `containers_triggers_get(...)`, `containers_triggers_list(...)`, `containers_triggers_update(...)`, `containers_update(...)`, `containers_variables_create(...)`, `containers_variables_delete(...)`, `containers_variables_get(...)`, `containers_variables_list(...)`, `containers_variables_update(...)`, `containers_versions_create(...)`, `containers_versions_delete(...)`, `containers_versions_get(...)`, `containers_versions_list(...)`, `containers_versions_publish(...)`, `containers_versions_restore(...)`, `containers_versions_undelete(...)`, `containers_versions_update(...)`, `get(...)`, `list(...)`, `permissions_create(...)`, `permissions_delete(...)`, `permissions_get(...)`, `permissions_list(...)`, `permissions_update(...)` and `update(...)` /// // to build up your call. /// let rb = hub.accounts(); /// # } @@ -1082,19 +1152,17 @@ impl<'a, C, A> AccountMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Undeletes a Container Version. + /// Creates a Container. /// /// # Arguments /// + /// * `request` - No description provided. /// * `accountId` - The GTM Account ID. - /// * `containerId` - The GTM Container ID. - /// * `containerVersionId` - The GTM Container Version ID. - pub fn containers_versions_undelete(&self, account_id: &str, container_id: &str, container_version_id: &str) -> AccountContainerVersionUndeleteCall<'a, C, A> { - AccountContainerVersionUndeleteCall { + pub fn containers_create(&self, request: Container, account_id: &str) -> AccountContainerCreateCall<'a, C, A> { + AccountContainerCreateCall { hub: self.hub, + _request: request, _account_id: account_id.to_string(), - _container_id: container_id.to_string(), - _container_version_id: container_version_id.to_string(), _delegate: Default::default(), _scopes: Default::default(), _additional_params: Default::default(), @@ -1244,17 +1312,19 @@ impl<'a, C, A> AccountMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Creates a Container. + /// Deletes a GTM Folder. /// /// # Arguments /// - /// * `request` - No description provided. /// * `accountId` - The GTM Account ID. - pub fn containers_create(&self, request: Container, account_id: &str) -> AccountContainerCreateCall<'a, C, A> { - AccountContainerCreateCall { + /// * `containerId` - The GTM Container ID. + /// * `folderId` - The GTM Folder ID. + pub fn containers_folders_delete(&self, account_id: &str, container_id: &str, folder_id: &str) -> AccountContainerFolderDeleteCall<'a, C, A> { + AccountContainerFolderDeleteCall { hub: self.hub, - _request: request, _account_id: account_id.to_string(), + _container_id: container_id.to_string(), + _folder_id: folder_id.to_string(), _delegate: Default::default(), _scopes: Default::default(), _additional_params: Default::default(), @@ -1284,22 +1354,19 @@ impl<'a, C, A> AccountMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Updates a GTM Rule. + /// List all entities in a GTM Folder. /// /// # Arguments /// - /// * `request` - No description provided. /// * `accountId` - The GTM Account ID. /// * `containerId` - The GTM Container ID. - /// * `ruleId` - The GTM Rule ID. - pub fn containers_rules_update(&self, request: Rule, account_id: &str, container_id: &str, rule_id: &str) -> AccountContainerRuleUpdateCall<'a, C, A> { - AccountContainerRuleUpdateCall { + /// * `folderId` - The GTM Folder ID. + pub fn containers_folders_entities_list(&self, account_id: &str, container_id: &str, folder_id: &str) -> AccountContainerFolderEntityListCall<'a, C, A> { + AccountContainerFolderEntityListCall { hub: self.hub, - _request: request, _account_id: account_id.to_string(), _container_id: container_id.to_string(), - _rule_id: rule_id.to_string(), - _fingerprint: Default::default(), + _folder_id: folder_id.to_string(), _delegate: Default::default(), _scopes: Default::default(), _additional_params: Default::default(), @@ -1308,19 +1375,19 @@ impl<'a, C, A> AccountMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Deletes a GTM Rule. + /// Undeletes a Container Version. /// /// # Arguments /// /// * `accountId` - The GTM Account ID. /// * `containerId` - The GTM Container ID. - /// * `ruleId` - The GTM Rule ID. - pub fn containers_rules_delete(&self, account_id: &str, container_id: &str, rule_id: &str) -> AccountContainerRuleDeleteCall<'a, C, A> { - AccountContainerRuleDeleteCall { + /// * `containerVersionId` - The GTM Container Version ID. + pub fn containers_versions_undelete(&self, account_id: &str, container_id: &str, container_version_id: &str) -> AccountContainerVersionUndeleteCall<'a, C, A> { + AccountContainerVersionUndeleteCall { hub: self.hub, _account_id: account_id.to_string(), _container_id: container_id.to_string(), - _rule_id: rule_id.to_string(), + _container_version_id: container_version_id.to_string(), _delegate: Default::default(), _scopes: Default::default(), _additional_params: Default::default(), @@ -1368,6 +1435,27 @@ impl<'a, C, A> AccountMethods<'a, C, A> { } } + /// Create a builder to help you perform the following task: + /// + /// Gets a GTM Folder. + /// + /// # Arguments + /// + /// * `accountId` - The GTM Account ID. + /// * `containerId` - The GTM Container ID. + /// * `folderId` - The GTM Folder ID. + pub fn containers_folders_get(&self, account_id: &str, container_id: &str, folder_id: &str) -> AccountContainerFolderGetCall<'a, C, A> { + AccountContainerFolderGetCall { + hub: self.hub, + _account_id: account_id.to_string(), + _container_id: container_id.to_string(), + _folder_id: folder_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 GTM Tag. @@ -1449,27 +1537,6 @@ impl<'a, C, A> AccountMethods<'a, C, A> { } } - /// Create a builder to help you perform the following task: - /// - /// Deletes a GTM Macro. - /// - /// # Arguments - /// - /// * `accountId` - The GTM Account ID. - /// * `containerId` - The GTM Container ID. - /// * `macroId` - The GTM Macro ID. - pub fn containers_macros_delete(&self, account_id: &str, container_id: &str, macro_id: &str) -> AccountContainerMacroDeleteCall<'a, C, A> { - AccountContainerMacroDeleteCall { - hub: self.hub, - _account_id: account_id.to_string(), - _container_id: container_id.to_string(), - _macro_id: macro_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 Container Version. @@ -1512,28 +1579,30 @@ impl<'a, C, A> AccountMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Creates a GTM Rule. + /// Moves entities to a GTM Folder. /// /// # Arguments /// - /// * `request` - No description provided. /// * `accountId` - The GTM Account ID. /// * `containerId` - The GTM Container ID. - pub fn containers_rules_create(&self, request: Rule, account_id: &str, container_id: &str) -> AccountContainerRuleCreateCall<'a, C, A> { - AccountContainerRuleCreateCall { + /// * `folderId` - The GTM Folder ID. + pub fn containers_move_folders_update(&self, account_id: &str, container_id: &str, folder_id: &str) -> AccountContainerMoveFolderUpdateCall<'a, C, A> { + AccountContainerMoveFolderUpdateCall { hub: self.hub, - _request: request, _account_id: account_id.to_string(), _container_id: container_id.to_string(), + _folder_id: folder_id.to_string(), + _variable_id: Default::default(), + _trigger_id: Default::default(), + _tag_id: Default::default(), _delegate: Default::default(), - _scopes: Default::default(), _additional_params: Default::default(), } } /// Create a builder to help you perform the following task: /// - /// Restores a Container Version. This will overwrite the container's current configuration (including its macros, rules and tags). The operation will not have any effect on the version that is being served (i.e. the published version). + /// Restores a Container Version. This will overwrite the container's current configuration (including its variables, triggers and tags). The operation will not have any effect on the version that is being served (i.e. the published version). /// /// # Arguments /// @@ -1552,27 +1621,6 @@ impl<'a, C, A> AccountMethods<'a, C, A> { } } - /// Create a builder to help you perform the following task: - /// - /// Gets a GTM Rule. - /// - /// # Arguments - /// - /// * `accountId` - The GTM Account ID. - /// * `containerId` - The GTM Container ID. - /// * `ruleId` - The GTM Rule ID. - pub fn containers_rules_get(&self, account_id: &str, container_id: &str, rule_id: &str) -> AccountContainerRuleGetCall<'a, C, A> { - AccountContainerRuleGetCall { - hub: self.hub, - _account_id: account_id.to_string(), - _container_id: container_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: /// /// Creates a GTM Variable. @@ -1613,27 +1661,6 @@ impl<'a, C, A> AccountMethods<'a, C, A> { } } - /// Create a builder to help you perform the following task: - /// - /// Creates a GTM Macro. - /// - /// # Arguments - /// - /// * `request` - No description provided. - /// * `accountId` - The GTM Account ID. - /// * `containerId` - The GTM Container ID. - pub fn containers_macros_create(&self, request: Macro, account_id: &str, container_id: &str) -> AccountContainerMacroCreateCall<'a, C, A> { - AccountContainerMacroCreateCall { - hub: self.hub, - _request: request, - _account_id: account_id.to_string(), - _container_id: container_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 GTM Tag. @@ -1697,25 +1724,6 @@ impl<'a, C, A> AccountMethods<'a, C, A> { } } - /// Create a builder to help you perform the following task: - /// - /// Lists all GTM Macros of a Container. - /// - /// # Arguments - /// - /// * `accountId` - The GTM Account ID. - /// * `containerId` - The GTM Container ID. - pub fn containers_macros_list(&self, account_id: &str, container_id: &str) -> AccountContainerMacroListCall<'a, C, A> { - AccountContainerMacroListCall { - hub: self.hub, - _account_id: account_id.to_string(), - _container_id: container_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 GTM Trigger. @@ -1739,21 +1747,21 @@ impl<'a, C, A> AccountMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Updates a GTM Macro. + /// Updates a GTM Folder. /// /// # Arguments /// /// * `request` - No description provided. /// * `accountId` - The GTM Account ID. /// * `containerId` - The GTM Container ID. - /// * `macroId` - The GTM Macro ID. - pub fn containers_macros_update(&self, request: Macro, account_id: &str, container_id: &str, macro_id: &str) -> AccountContainerMacroUpdateCall<'a, C, A> { - AccountContainerMacroUpdateCall { + /// * `folderId` - The GTM Folder ID. + pub fn containers_folders_update(&self, request: Folder, account_id: &str, container_id: &str, folder_id: &str) -> AccountContainerFolderUpdateCall<'a, C, A> { + AccountContainerFolderUpdateCall { hub: self.hub, _request: request, _account_id: account_id.to_string(), _container_id: container_id.to_string(), - _macro_id: macro_id.to_string(), + _folder_id: folder_id.to_string(), _fingerprint: Default::default(), _delegate: Default::default(), _scopes: Default::default(), @@ -1854,25 +1862,6 @@ impl<'a, C, A> AccountMethods<'a, C, A> { } } - /// Create a builder to help you perform the following task: - /// - /// Lists all GTM Rules of a Container. - /// - /// # Arguments - /// - /// * `accountId` - The GTM Account ID. - /// * `containerId` - The GTM Container ID. - pub fn containers_rules_list(&self, account_id: &str, container_id: &str) -> AccountContainerRuleListCall<'a, C, A> { - AccountContainerRuleListCall { - hub: self.hub, - _account_id: account_id.to_string(), - _container_id: container_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 GTM Tag. @@ -1899,19 +1888,38 @@ impl<'a, C, A> AccountMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// Gets a GTM Macro. + /// Creates a GTM Folder. + /// + /// # Arguments + /// + /// * `request` - No description provided. + /// * `accountId` - The GTM Account ID. + /// * `containerId` - The GTM Container ID. + pub fn containers_folders_create(&self, request: Folder, account_id: &str, container_id: &str) -> AccountContainerFolderCreateCall<'a, C, A> { + AccountContainerFolderCreateCall { + hub: self.hub, + _request: request, + _account_id: account_id.to_string(), + _container_id: container_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 GTM Folders of a Container. /// /// # Arguments /// /// * `accountId` - The GTM Account ID. /// * `containerId` - The GTM Container ID. - /// * `macroId` - The GTM Macro ID. - pub fn containers_macros_get(&self, account_id: &str, container_id: &str, macro_id: &str) -> AccountContainerMacroGetCall<'a, C, A> { - AccountContainerMacroGetCall { + pub fn containers_folders_list(&self, account_id: &str, container_id: &str) -> AccountContainerFolderListCall<'a, C, A> { + AccountContainerFolderListCall { hub: self.hub, _account_id: account_id.to_string(), _container_id: container_id.to_string(), - _macro_id: macro_id.to_string(), _delegate: Default::default(), _scopes: Default::default(), _additional_params: Default::default(), @@ -2468,9 +2476,9 @@ impl<'a, C, A> AccountPermissionListCall<'a, C, A> where C: BorrowMut AccountPermissionListCall<'a, C, A> where C: BorrowMut AccountPermissionListCall<'a, C, A> where C: BorrowMut::default(), None); /// # let mut hub = TagManager::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req = Container::default(); +/// /// // You can configure optional parameters by calling 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().containers_versions_undelete("accountId", "containerId", "containerVersionId") +/// let result = hub.accounts().containers_create(req, "accountId") /// .doit(); /// # } /// ``` -pub struct AccountContainerVersionUndeleteCall<'a, C, A> +pub struct AccountContainerCreateCall<'a, C, A> where C: 'a, A: 'a { hub: &'a TagManager, + _request: Container, _account_id: String, - _container_id: String, - _container_version_id: String, _delegate: Option<&'a mut Delegate>, _additional_params: HashMap, _scopes: BTreeMap } -impl<'a, C, A> CallBuilder for AccountContainerVersionUndeleteCall<'a, C, A> {} +impl<'a, C, A> CallBuilder for AccountContainerCreateCall<'a, C, A> {} -impl<'a, C, A> AccountContainerVersionUndeleteCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { +impl<'a, C, A> AccountContainerCreateCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { /// Perform the operation you have build so far. - pub fn doit(mut self) -> Result<(hyper::client::Response, ContainerVersion)> { + pub fn doit(mut self) -> Result<(hyper::client::Response, Container)> { use std::io::{Read, Seek}; use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; let mut dd = DefaultDelegate; @@ -2524,13 +2537,11 @@ impl<'a, C, A> AccountContainerVersionUndeleteCall<'a, C, A> where C: BorrowMut< Some(d) => d, None => &mut dd }; - dlg.begin(MethodInfo { id: "tagmanager.accounts.containers.versions.undelete", + dlg.begin(MethodInfo { id: "tagmanager.accounts.containers.create", http_method: hyper::method::Method::Post }); - let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); params.push(("accountId", self._account_id.to_string())); - params.push(("containerId", self._container_id.to_string())); - params.push(("containerVersionId", self._container_version_id.to_string())); - for &field in ["alt", "accountId", "containerId", "containerVersionId"].iter() { + for &field in ["alt", "accountId"].iter() { if self._additional_params.contains_key(field) { dlg.finished(false); return Err(Error::FieldClash(field)); @@ -2542,12 +2553,12 @@ impl<'a, C, A> AccountContainerVersionUndeleteCall<'a, C, A> where C: BorrowMut< params.push(("alt", "json".to_string())); - let mut url = "https://www.googleapis.com/tagmanager/v1/accounts/{accountId}/containers/{containerId}/versions/{containerVersionId}/undelete".to_string(); + let mut url = "https://www.googleapis.com/tagmanager/v1/accounts/{accountId}/containers".to_string(); if self._scopes.len() == 0 { - self._scopes.insert(Scope::EditContainerversion.as_ref().to_string(), ()); + self._scopes.insert(Scope::EditContainer.as_ref().to_string(), ()); } - for &(find_this, param_name) in [("{accountId}", "accountId"), ("{containerId}", "containerId"), ("{containerVersionId}", "containerVersionId")].iter() { + 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 { @@ -2558,8 +2569,8 @@ impl<'a, C, A> AccountContainerVersionUndeleteCall<'a, C, A> where C: BorrowMut< 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 ["containerVersionId", "containerId", "accountId"].iter() { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["accountId"].iter() { if let Some(index) = params.iter().position(|t| &t.0 == param_name) { indices_for_removal.push(index); } @@ -2574,6 +2585,17 @@ impl<'a, C, A> AccountContainerVersionUndeleteCall<'a, C, A> where C: BorrowMut< url.push_str(&url::form_urlencoded::serialize(params)); } + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); loop { @@ -2591,11 +2613,15 @@ impl<'a, C, A> AccountContainerVersionUndeleteCall<'a, C, A> where C: BorrowMut< }; let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()); + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); dlg.pre_request(); req.send() @@ -2646,43 +2672,32 @@ impl<'a, C, A> AccountContainerVersionUndeleteCall<'a, C, A> where C: BorrowMut< } + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: Container) -> AccountContainerCreateCall<'a, C, A> { + self._request = new_value; + self + } /// The GTM Account ID. /// /// 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. - pub fn account_id(mut self, new_value: &str) -> AccountContainerVersionUndeleteCall<'a, C, A> { + pub fn account_id(mut self, new_value: &str) -> AccountContainerCreateCall<'a, C, A> { self._account_id = new_value.to_string(); self } - /// The GTM Container ID. - /// - /// Sets the *container id* path property to the given value. - /// - /// Even though the property as already been set when instantiating this call, - /// we provide this method for API completeness. - pub fn container_id(mut self, new_value: &str) -> AccountContainerVersionUndeleteCall<'a, C, A> { - self._container_id = new_value.to_string(); - self - } - /// The GTM Container Version ID. - /// - /// Sets the *container version id* path property to the given value. - /// - /// Even though the property as already been set when instantiating this call, - /// we provide this method for API completeness. - pub fn container_version_id(mut self, new_value: &str) -> AccountContainerVersionUndeleteCall<'a, C, A> { - self._container_version_id = new_value.to_string(); - self - } /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong /// while executing the actual API request. /// /// It should be used to handle progress information, and to implement a certain level of resilience. /// /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountContainerVersionUndeleteCall<'a, C, A> { + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountContainerCreateCall<'a, C, A> { self._delegate = Some(new_value); self } @@ -2703,7 +2718,7 @@ impl<'a, C, A> AccountContainerVersionUndeleteCall<'a, C, A> where C: BorrowMut< /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. /// * *alt* (query-string) - Data format for the response. - pub fn param(mut self, name: T, value: T) -> AccountContainerVersionUndeleteCall<'a, C, A> + pub fn param(mut self, name: T, value: T) -> AccountContainerCreateCall<'a, C, A> where T: AsRef { self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); self @@ -2712,7 +2727,7 @@ impl<'a, C, A> AccountContainerVersionUndeleteCall<'a, C, A> where C: BorrowMut< /// Identifies the authorization scope for the method you are building. /// /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::EditContainerversion`. + /// `Scope::EditContainer`. /// /// The `scope` will be added to a set of scopes. This is important as one can maintain access /// tokens for more than one scope. @@ -2720,7 +2735,7 @@ impl<'a, C, A> AccountContainerVersionUndeleteCall<'a, C, A> where C: BorrowMut< /// Usually there is more than one suitable scope to authorize an operation, some of which may /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be /// sufficient, a read-write scope will do as well. - pub fn add_scope(mut self, scope: T) -> AccountContainerVersionUndeleteCall<'a, C, A> + pub fn add_scope(mut self, scope: T) -> AccountContainerCreateCall<'a, C, A> where T: AsRef { self._scopes.insert(scope.as_ref().to_string(), ()); self @@ -3507,7 +3522,7 @@ impl<'a, C, A> AccountContainerGetCall<'a, C, A> where C: BorrowMut AccountContainerVersionListCall<'a, C, A> where C: BorrowMut AccountContainerDeleteCall<'a, C, A> where C: BorrowMut AccountContainerDeleteCall<'a, C, A> where C: BorrowMut AccountContainerDeleteCall<'a, C, A> where C: BorrowMut::default(), None); /// # let mut hub = TagManager::new(hyper::Client::new(), auth); -/// // As the method needs a request, you would usually fill it with the desired information -/// // into the respective structure. Some of the parts shown here might not be applicable ! -/// // Values shown here are possibly random and not representative ! -/// let mut req = Container::default(); -/// /// // You can configure optional parameters by calling 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().containers_create(req, "accountId") +/// let result = hub.accounts().containers_folders_delete("accountId", "containerId", "folderId") /// .doit(); /// # } /// ``` -pub struct AccountContainerCreateCall<'a, C, A> +pub struct AccountContainerFolderDeleteCall<'a, C, A> where C: 'a, A: 'a { hub: &'a TagManager, - _request: Container, _account_id: String, + _container_id: String, + _folder_id: String, _delegate: Option<&'a mut Delegate>, _additional_params: HashMap, _scopes: BTreeMap } -impl<'a, C, A> CallBuilder for AccountContainerCreateCall<'a, C, A> {} +impl<'a, C, A> CallBuilder for AccountContainerFolderDeleteCall<'a, C, A> {} -impl<'a, C, A> AccountContainerCreateCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { +impl<'a, C, A> AccountContainerFolderDeleteCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { /// Perform the operation you have build so far. - pub fn doit(mut self) -> Result<(hyper::client::Response, Container)> { + pub fn doit(mut self) -> Result { use std::io::{Read, Seek}; use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; let mut dd = DefaultDelegate; @@ -4601,11 +4611,13 @@ impl<'a, C, A> AccountContainerCreateCall<'a, C, A> where C: BorrowMut d, None => &mut dd }; - dlg.begin(MethodInfo { id: "tagmanager.accounts.containers.create", - http_method: hyper::method::Method::Post }); + dlg.begin(MethodInfo { id: "tagmanager.accounts.containers.folders.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())); - for &field in ["alt", "accountId"].iter() { + params.push(("containerId", self._container_id.to_string())); + params.push(("folderId", self._folder_id.to_string())); + for &field in ["accountId", "containerId", "folderId"].iter() { if self._additional_params.contains_key(field) { dlg.finished(false); return Err(Error::FieldClash(field)); @@ -4615,14 +4627,13 @@ impl<'a, C, A> AccountContainerCreateCall<'a, C, A> where C: BorrowMut = None; for &(name, ref value) in params.iter() { if name == param_name { @@ -4633,8 +4644,8 @@ impl<'a, C, A> AccountContainerCreateCall<'a, C, A> where C: BorrowMut = Vec::with_capacity(1); - for param_name in ["accountId"].iter() { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["folderId", "containerId", "accountId"].iter() { if let Some(index) = params.iter().position(|t| &t.0 == param_name) { indices_for_removal.push(index); } @@ -4649,17 +4660,6 @@ impl<'a, C, A> AccountContainerCreateCall<'a, C, A> where C: BorrowMut AccountContainerCreateCall<'a, C, A> where C: BorrowMut AccountContainerCreateCall<'a, C, A> where C: BorrowMut Err(Error::BadRequest(serr)) } } - let result_value = { - let mut json_response = String::new(); - res.read_to_string(&mut json_response).unwrap(); - match json::from_str(&json_response) { - Ok(decoded) => (res, decoded), - Err(err) => { - dlg.response_json_decode_error(&json_response, &err); - return Err(Error::JsonDecodeError(json_response, err)); - } - } - }; + let result_value = res; dlg.finished(true); return Ok(result_value) @@ -4736,32 +4722,43 @@ impl<'a, C, A> AccountContainerCreateCall<'a, C, A> where C: BorrowMut AccountContainerCreateCall<'a, C, A> { - self._request = new_value; - self - } /// The GTM Account ID. /// /// 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. - pub fn account_id(mut self, new_value: &str) -> AccountContainerCreateCall<'a, C, A> { + pub fn account_id(mut self, new_value: &str) -> AccountContainerFolderDeleteCall<'a, C, A> { self._account_id = new_value.to_string(); self } + /// The GTM Container ID. + /// + /// Sets the *container id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn container_id(mut self, new_value: &str) -> AccountContainerFolderDeleteCall<'a, C, A> { + self._container_id = new_value.to_string(); + self + } + /// The GTM Folder ID. + /// + /// 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. + pub fn folder_id(mut self, new_value: &str) -> AccountContainerFolderDeleteCall<'a, C, A> { + self._folder_id = new_value.to_string(); + self + } /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong /// while executing the actual API request. /// /// It should be used to handle progress information, and to implement a certain level of resilience. /// /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountContainerCreateCall<'a, C, A> { + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountContainerFolderDeleteCall<'a, C, A> { self._delegate = Some(new_value); self } @@ -4782,7 +4779,7 @@ impl<'a, C, A> AccountContainerCreateCall<'a, C, A> where C: BorrowMut(mut self, name: T, value: T) -> AccountContainerCreateCall<'a, C, A> + pub fn param(mut self, name: T, value: T) -> AccountContainerFolderDeleteCall<'a, C, A> where T: AsRef { self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); self @@ -4799,7 +4796,7 @@ impl<'a, C, A> AccountContainerCreateCall<'a, C, A> where C: BorrowMut(mut self, scope: T) -> AccountContainerCreateCall<'a, C, A> + pub fn add_scope(mut self, scope: T) -> AccountContainerFolderDeleteCall<'a, C, A> where T: AsRef { self._scopes.insert(scope.as_ref().to_string(), ()); self @@ -5056,9 +5053,9 @@ impl<'a, C, A> AccountContainerTagDeleteCall<'a, C, A> where C: BorrowMut AccountContainerTagDeleteCall<'a, C, A> where C: BorrowMut AccountContainerTagDeleteCall<'a, C, A> where C: BorrowMut::default(), None); /// # let mut hub = TagManager::new(hyper::Client::new(), auth); -/// // As the method needs a request, you would usually fill it with the desired information -/// // into the respective structure. Some of the parts shown here might not be applicable ! -/// // Values shown here are possibly random and not representative ! -/// let mut req = Rule::default(); -/// /// // You can configure optional parameters by calling 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().containers_rules_update(req, "accountId", "containerId", "ruleId") -/// .fingerprint("eirmod") +/// let result = hub.accounts().containers_folders_entities_list("accountId", "containerId", "folderId") /// .doit(); /// # } /// ``` -pub struct AccountContainerRuleUpdateCall<'a, C, A> +pub struct AccountContainerFolderEntityListCall<'a, C, A> where C: 'a, A: 'a { hub: &'a TagManager, - _request: Rule, _account_id: String, _container_id: String, - _rule_id: String, - _fingerprint: Option, + _folder_id: String, _delegate: Option<&'a mut Delegate>, _additional_params: HashMap, _scopes: BTreeMap } -impl<'a, C, A> CallBuilder for AccountContainerRuleUpdateCall<'a, C, A> {} +impl<'a, C, A> CallBuilder for AccountContainerFolderEntityListCall<'a, C, A> {} -impl<'a, C, A> AccountContainerRuleUpdateCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { +impl<'a, C, A> AccountContainerFolderEntityListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { /// Perform the operation you have build so far. - pub fn doit(mut self) -> Result<(hyper::client::Response, Rule)> { + pub fn doit(mut self) -> Result<(hyper::client::Response, FolderEntities)> { use std::io::{Read, Seek}; use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; let mut dd = DefaultDelegate; @@ -5121,16 +5109,13 @@ impl<'a, C, A> AccountContainerRuleUpdateCall<'a, C, A> where C: BorrowMut d, None => &mut dd }; - dlg.begin(MethodInfo { id: "tagmanager.accounts.containers.rules.update", - http_method: hyper::method::Method::Put }); - let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + dlg.begin(MethodInfo { id: "tagmanager.accounts.containers.folders.entities.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())); params.push(("containerId", self._container_id.to_string())); - params.push(("ruleId", self._rule_id.to_string())); - if let Some(value) = self._fingerprint { - params.push(("fingerprint", value.to_string())); - } - for &field in ["alt", "accountId", "containerId", "ruleId", "fingerprint"].iter() { + params.push(("folderId", self._folder_id.to_string())); + for &field in ["alt", "accountId", "containerId", "folderId"].iter() { if self._additional_params.contains_key(field) { dlg.finished(false); return Err(Error::FieldClash(field)); @@ -5142,12 +5127,12 @@ impl<'a, C, A> AccountContainerRuleUpdateCall<'a, C, A> where C: BorrowMut = None; for &(name, ref value) in params.iter() { if name == param_name { @@ -5159,7 +5144,7 @@ impl<'a, C, A> AccountContainerRuleUpdateCall<'a, C, A> where C: BorrowMut = Vec::with_capacity(3); - for param_name in ["ruleId", "containerId", "accountId"].iter() { + for param_name in ["folderId", "containerId", "accountId"].iter() { if let Some(index) = params.iter().position(|t| &t.0 == param_name) { indices_for_removal.push(index); } @@ -5174,17 +5159,6 @@ impl<'a, C, A> AccountContainerRuleUpdateCall<'a, C, A> where C: BorrowMut AccountContainerRuleUpdateCall<'a, C, A> where C: BorrowMut AccountContainerRuleUpdateCall<'a, C, A> where C: BorrowMut AccountContainerRuleUpdateCall<'a, C, A> { - self._request = new_value; - self - } /// The GTM Account ID. /// /// 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. - pub fn account_id(mut self, new_value: &str) -> AccountContainerRuleUpdateCall<'a, C, A> { + pub fn account_id(mut self, new_value: &str) -> AccountContainerFolderEntityListCall<'a, C, A> { self._account_id = new_value.to_string(); self } @@ -5286,25 +5247,18 @@ impl<'a, C, A> AccountContainerRuleUpdateCall<'a, C, A> where C: BorrowMut AccountContainerRuleUpdateCall<'a, C, A> { + pub fn container_id(mut self, new_value: &str) -> AccountContainerFolderEntityListCall<'a, C, A> { self._container_id = new_value.to_string(); self } - /// The GTM Rule ID. + /// The GTM Folder ID. /// - /// Sets the *rule id* path property to the given 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. - pub fn rule_id(mut self, new_value: &str) -> AccountContainerRuleUpdateCall<'a, C, A> { - self._rule_id = new_value.to_string(); - self - } - /// When provided, this fingerprint must match the fingerprint of the rule in storage. - /// - /// Sets the *fingerprint* query property to the given value. - pub fn fingerprint(mut self, new_value: &str) -> AccountContainerRuleUpdateCall<'a, C, A> { - self._fingerprint = Some(new_value.to_string()); + pub fn folder_id(mut self, new_value: &str) -> AccountContainerFolderEntityListCall<'a, C, A> { + self._folder_id = new_value.to_string(); self } /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong @@ -5313,7 +5267,7 @@ impl<'a, C, A> AccountContainerRuleUpdateCall<'a, C, A> where C: BorrowMut AccountContainerRuleUpdateCall<'a, C, A> { + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountContainerFolderEntityListCall<'a, C, A> { self._delegate = Some(new_value); self } @@ -5334,7 +5288,7 @@ impl<'a, C, A> AccountContainerRuleUpdateCall<'a, C, A> where C: BorrowMut(mut self, name: T, value: T) -> AccountContainerRuleUpdateCall<'a, C, A> + pub fn param(mut self, name: T, value: T) -> AccountContainerFolderEntityListCall<'a, C, A> where T: AsRef { self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); self @@ -5343,7 +5297,7 @@ impl<'a, C, A> AccountContainerRuleUpdateCall<'a, C, A> where C: BorrowMut AccountContainerRuleUpdateCall<'a, C, A> where C: BorrowMut(mut self, scope: T) -> AccountContainerRuleUpdateCall<'a, C, A> + pub fn add_scope(mut self, scope: T) -> AccountContainerFolderEntityListCall<'a, C, A> where T: AsRef { self._scopes.insert(scope.as_ref().to_string(), ()); self @@ -5359,9 +5313,9 @@ impl<'a, C, A> AccountContainerRuleUpdateCall<'a, C, A> where C: BorrowMut AccountContainerRuleUpdateCall<'a, C, A> where C: BorrowMut +pub struct AccountContainerVersionUndeleteCall<'a, C, A> where C: 'a, A: 'a { hub: &'a TagManager, _account_id: String, _container_id: String, - _rule_id: String, + _container_version_id: String, _delegate: Option<&'a mut Delegate>, _additional_params: HashMap, _scopes: BTreeMap } -impl<'a, C, A> CallBuilder for AccountContainerRuleDeleteCall<'a, C, A> {} +impl<'a, C, A> CallBuilder for AccountContainerVersionUndeleteCall<'a, C, A> {} -impl<'a, C, A> AccountContainerRuleDeleteCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { +impl<'a, C, A> AccountContainerVersionUndeleteCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { /// Perform the operation you have build so far. - pub fn doit(mut self) -> Result { + pub fn doit(mut self) -> Result<(hyper::client::Response, ContainerVersion)> { use std::io::{Read, Seek}; use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; let mut dd = DefaultDelegate; @@ -5415,13 +5369,13 @@ impl<'a, C, A> AccountContainerRuleDeleteCall<'a, C, A> where C: BorrowMut d, None => &mut dd }; - dlg.begin(MethodInfo { id: "tagmanager.accounts.containers.rules.delete", - http_method: hyper::method::Method::Delete }); - let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + dlg.begin(MethodInfo { id: "tagmanager.accounts.containers.versions.undelete", + 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(("containerId", self._container_id.to_string())); - params.push(("ruleId", self._rule_id.to_string())); - for &field in ["accountId", "containerId", "ruleId"].iter() { + params.push(("containerVersionId", self._container_version_id.to_string())); + for &field in ["alt", "accountId", "containerId", "containerVersionId"].iter() { if self._additional_params.contains_key(field) { dlg.finished(false); return Err(Error::FieldClash(field)); @@ -5431,13 +5385,14 @@ impl<'a, C, A> AccountContainerRuleDeleteCall<'a, C, A> where C: BorrowMut = None; for &(name, ref value) in params.iter() { if name == param_name { @@ -5449,7 +5404,7 @@ impl<'a, C, A> AccountContainerRuleDeleteCall<'a, C, A> where C: BorrowMut = Vec::with_capacity(3); - for param_name in ["ruleId", "containerId", "accountId"].iter() { + for param_name in ["containerVersionId", "containerId", "accountId"].iter() { if let Some(index) = params.iter().position(|t| &t.0 == param_name) { indices_for_removal.push(index); } @@ -5483,7 +5438,7 @@ impl<'a, C, A> AccountContainerRuleDeleteCall<'a, C, A> where C: BorrowMut AccountContainerRuleDeleteCall<'a, C, A> where C: BorrowMut Err(Error::BadRequest(serr)) } } - let result_value = res; + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; dlg.finished(true); return Ok(result_value) @@ -5532,7 +5497,7 @@ impl<'a, C, A> AccountContainerRuleDeleteCall<'a, C, A> where C: BorrowMut AccountContainerRuleDeleteCall<'a, C, A> { + pub fn account_id(mut self, new_value: &str) -> AccountContainerVersionUndeleteCall<'a, C, A> { self._account_id = new_value.to_string(); self } @@ -5542,18 +5507,18 @@ impl<'a, C, A> AccountContainerRuleDeleteCall<'a, C, A> where C: BorrowMut AccountContainerRuleDeleteCall<'a, C, A> { + pub fn container_id(mut self, new_value: &str) -> AccountContainerVersionUndeleteCall<'a, C, A> { self._container_id = new_value.to_string(); self } - /// The GTM Rule ID. + /// The GTM Container Version ID. /// - /// Sets the *rule id* path property to the given value. + /// Sets the *container version id* path property to the given value. /// /// Even though the property as already been set when instantiating this call, /// we provide this method for API completeness. - pub fn rule_id(mut self, new_value: &str) -> AccountContainerRuleDeleteCall<'a, C, A> { - self._rule_id = new_value.to_string(); + pub fn container_version_id(mut self, new_value: &str) -> AccountContainerVersionUndeleteCall<'a, C, A> { + self._container_version_id = new_value.to_string(); self } /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong @@ -5562,7 +5527,7 @@ impl<'a, C, A> AccountContainerRuleDeleteCall<'a, C, A> where C: BorrowMut AccountContainerRuleDeleteCall<'a, C, A> { + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountContainerVersionUndeleteCall<'a, C, A> { self._delegate = Some(new_value); self } @@ -5583,7 +5548,7 @@ impl<'a, C, A> AccountContainerRuleDeleteCall<'a, C, A> where C: BorrowMut(mut self, name: T, value: T) -> AccountContainerRuleDeleteCall<'a, C, A> + pub fn param(mut self, name: T, value: T) -> AccountContainerVersionUndeleteCall<'a, C, A> where T: AsRef { self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); self @@ -5592,7 +5557,7 @@ impl<'a, C, A> AccountContainerRuleDeleteCall<'a, C, A> where C: BorrowMut AccountContainerRuleDeleteCall<'a, C, A> where C: BorrowMut(mut self, scope: T) -> AccountContainerRuleDeleteCall<'a, C, A> + pub fn add_scope(mut self, scope: T) -> AccountContainerVersionUndeleteCall<'a, C, A> where T: AsRef { self._scopes.insert(scope.as_ref().to_string(), ()); self @@ -5883,7 +5848,7 @@ impl<'a, C, A> AccountContainerTagListCall<'a, C, A> where C: BorrowMut AccountContainerVersionPublishCall<'a, C, A> where C: BorrowMut::default(), None); +/// # let mut hub = TagManager::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling 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().containers_folders_get("accountId", "containerId", "folderId") +/// .doit(); +/// # } +/// ``` +pub struct AccountContainerFolderGetCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a TagManager, + _account_id: String, + _container_id: String, + _folder_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for AccountContainerFolderGetCall<'a, C, A> {} + +impl<'a, C, A> AccountContainerFolderGetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Folder)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "tagmanager.accounts.containers.folders.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(("containerId", self._container_id.to_string())); + params.push(("folderId", self._folder_id.to_string())); + for &field in ["alt", "accountId", "containerId", "folderId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/tagmanager/v1/accounts/{accountId}/containers/{containerId}/folders/{folderId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::Readonly.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{containerId}", "containerId"), ("{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(3); + for param_name in ["folderId", "containerId", "accountId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The GTM Account ID. + /// + /// 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. + pub fn account_id(mut self, new_value: &str) -> AccountContainerFolderGetCall<'a, C, A> { + self._account_id = new_value.to_string(); + self + } + /// The GTM Container ID. + /// + /// Sets the *container id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn container_id(mut self, new_value: &str) -> AccountContainerFolderGetCall<'a, C, A> { + self._container_id = new_value.to_string(); + self + } + /// The GTM Folder ID. + /// + /// 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. + pub fn folder_id(mut self, new_value: &str) -> AccountContainerFolderGetCall<'a, C, A> { + self._folder_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountContainerFolderGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountContainerFolderGetCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::Readonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountContainerFolderGetCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + /// Creates a GTM Tag. /// /// A builder for the *containers.tags.create* method supported by a *account* resource. @@ -6937,7 +7162,7 @@ impl<'a, C, A> AccountContainerVersionDeleteCall<'a, C, A> where C: BorrowMut AccountUpdateCall<'a, C, A> where C: BorrowMut, A: } -/// Deletes a GTM Macro. -/// -/// A builder for the *containers.macros.delete* method supported by a *account* resource. -/// It is not used directly, but through a `AccountMethods` instance. -/// -/// # Example -/// -/// Instantiate a resource method builder -/// -/// ```test_harness,no_run -/// # extern crate hyper; -/// # extern crate yup_oauth2 as oauth2; -/// # extern crate google_tagmanager1 as tagmanager1; -/// # #[test] fn egal() { -/// # use std::default::Default; -/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; -/// # use tagmanager1::TagManager; -/// -/// # let secret: ApplicationSecret = Default::default(); -/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, -/// # hyper::Client::new(), -/// # ::default(), None); -/// # let mut hub = TagManager::new(hyper::Client::new(), auth); -/// // You can configure optional parameters by calling 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().containers_macros_delete("accountId", "containerId", "macroId") -/// .doit(); -/// # } -/// ``` -pub struct AccountContainerMacroDeleteCall<'a, C, A> - where C: 'a, A: 'a { - - hub: &'a TagManager, - _account_id: String, - _container_id: String, - _macro_id: String, - _delegate: Option<&'a mut Delegate>, - _additional_params: HashMap, - _scopes: BTreeMap -} - -impl<'a, C, A> CallBuilder for AccountContainerMacroDeleteCall<'a, C, A> {} - -impl<'a, C, A> AccountContainerMacroDeleteCall<'a, C, A> where 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: "tagmanager.accounts.containers.macros.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(("containerId", self._container_id.to_string())); - params.push(("macroId", self._macro_id.to_string())); - for &field in ["accountId", "containerId", "macroId"].iter() { - if self._additional_params.contains_key(field) { - dlg.finished(false); - return Err(Error::FieldClash(field)); - } - } - for (name, value) in self._additional_params.iter() { - params.push((&name, value.clone())); - } - - - let mut url = "https://www.googleapis.com/tagmanager/v1/accounts/{accountId}/containers/{containerId}/macros/{macroId}".to_string(); - if self._scopes.len() == 0 { - self._scopes.insert(Scope::EditContainer.as_ref().to_string(), ()); - } - - for &(find_this, param_name) in [("{accountId}", "accountId"), ("{containerId}", "containerId"), ("{macroId}", "macroId")].iter() { - let mut replace_with: Option<&str> = None; - for &(name, ref value) in params.iter() { - if name == param_name { - replace_with = Some(value); - 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 ["macroId", "containerId", "accountId"].iter() { - if let Some(index) = params.iter().position(|t| &t.0 == param_name) { - indices_for_removal.push(index); - } - } - for &index in indices_for_removal.iter() { - params.remove(index); - } - } - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_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) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = res; - - dlg.finished(true); - return Ok(result_value) - } - } - } - } - - - /// The GTM Account ID. - /// - /// 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. - pub fn account_id(mut self, new_value: &str) -> AccountContainerMacroDeleteCall<'a, C, A> { - self._account_id = new_value.to_string(); - self - } - /// The GTM Container ID. - /// - /// Sets the *container id* path property to the given value. - /// - /// Even though the property as already been set when instantiating this call, - /// we provide this method for API completeness. - pub fn container_id(mut self, new_value: &str) -> AccountContainerMacroDeleteCall<'a, C, A> { - self._container_id = new_value.to_string(); - self - } - /// The GTM Macro ID. - /// - /// Sets the *macro id* path property to the given value. - /// - /// Even though the property as already been set when instantiating this call, - /// we provide this method for API completeness. - pub fn macro_id(mut self, new_value: &str) -> AccountContainerMacroDeleteCall<'a, C, A> { - self._macro_id = new_value.to_string(); - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountContainerMacroDeleteCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. - /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. - /// * *alt* (query-string) - Data format for the response. - pub fn param(mut self, name: T, value: T) -> AccountContainerMacroDeleteCall<'a, C, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::EditContainer`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be - /// sufficient, a read-write scope will do as well. - pub fn add_scope(mut self, scope: T) -> AccountContainerMacroDeleteCall<'a, C, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().to_string(), ()); - self - } -} - - /// Creates a Container Version. /// /// A builder for the *containers.versions.create* method supported by a *account* resource. @@ -7959,9 +7935,9 @@ impl<'a, C, A> AccountPermissionGetCall<'a, C, A> where C: BorrowMut AccountPermissionGetCall<'a, C, A> where C: BorrowMut AccountPermissionGetCall<'a, C, A> where C: BorrowMut::default(), None); /// # let mut hub = TagManager::new(hyper::Client::new(), auth); -/// // As the method needs a request, you would usually fill it with the desired information -/// // into the respective structure. Some of the parts shown here might not be applicable ! -/// // Values shown here are possibly random and not representative ! -/// let mut req = Rule::default(); -/// /// // You can configure optional parameters by calling 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().containers_rules_create(req, "accountId", "containerId") +/// let result = hub.accounts().containers_move_folders_update("accountId", "containerId", "folderId") +/// .add_variable_id("gubergren") +/// .add_trigger_id("justo") +/// .add_tag_id("sit") /// .doit(); /// # } /// ``` -pub struct AccountContainerRuleCreateCall<'a, C, A> +pub struct AccountContainerMoveFolderUpdateCall<'a, C, A> where C: 'a, A: 'a { hub: &'a TagManager, - _request: Rule, _account_id: String, _container_id: String, + _folder_id: String, + _variable_id: Vec, + _trigger_id: Vec, + _tag_id: Vec, _delegate: Option<&'a mut Delegate>, _additional_params: HashMap, - _scopes: BTreeMap } -impl<'a, C, A> CallBuilder for AccountContainerRuleCreateCall<'a, C, A> {} +impl<'a, C, A> CallBuilder for AccountContainerMoveFolderUpdateCall<'a, C, A> {} -impl<'a, C, A> AccountContainerRuleCreateCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { +impl<'a, C, A> AccountContainerMoveFolderUpdateCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { /// Perform the operation you have build so far. - pub fn doit(mut self) -> Result<(hyper::client::Response, Rule)> { + pub fn doit(mut self) -> Result { use std::io::{Read, Seek}; use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; let mut dd = DefaultDelegate; @@ -8021,12 +7996,34 @@ impl<'a, C, A> AccountContainerRuleCreateCall<'a, C, A> where C: BorrowMut d, None => &mut dd }; - dlg.begin(MethodInfo { id: "tagmanager.accounts.containers.rules.create", - http_method: hyper::method::Method::Post }); - let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + dlg.begin(MethodInfo { id: "tagmanager.accounts.containers.move_folders.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(("containerId", self._container_id.to_string())); - for &field in ["alt", "accountId", "containerId"].iter() { + params.push(("folderId", self._folder_id.to_string())); + if self._variable_id.len() > 0 { + let mut s = String::new(); + for f in self._variable_id.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("variableId", s)); + } + if self._trigger_id.len() > 0 { + let mut s = String::new(); + for f in self._trigger_id.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("triggerId", s)); + } + if self._tag_id.len() > 0 { + let mut s = String::new(); + for f in self._tag_id.iter() { + s.push_str(&("/".to_string() + &f.to_string())); + } + params.push(("tagId", s)); + } + for &field in ["accountId", "containerId", "folderId", "variableId", "triggerId", "tagId"].iter() { if self._additional_params.contains_key(field) { dlg.finished(false); return Err(Error::FieldClash(field)); @@ -8036,14 +8033,22 @@ impl<'a, C, A> AccountContainerRuleCreateCall<'a, C, A> where C: BorrowMut params.push(("key", value)), + None => { + dlg.finished(false); + return Err(Error::MissingAPIKey) + } } - for &(find_this, param_name) in [("{accountId}", "accountId"), ("{containerId}", "containerId")].iter() { + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{containerId}", "containerId"), ("{folderId}", "folderId")].iter() { let mut replace_with: Option<&str> = None; for &(name, ref value) in params.iter() { if name == param_name { @@ -8054,8 +8059,8 @@ impl<'a, C, A> AccountContainerRuleCreateCall<'a, C, A> where C: BorrowMut = Vec::with_capacity(2); - for param_name in ["containerId", "accountId"].iter() { + let mut indices_for_removal: Vec = Vec::with_capacity(3); + for param_name in ["folderId", "containerId", "accountId"].iter() { if let Some(index) = params.iter().position(|t| &t.0 == param_name) { indices_for_removal.push(index); } @@ -8070,43 +8075,13 @@ impl<'a, C, A> AccountContainerRuleCreateCall<'a, C, A> where C: BorrowMut token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_token }); - request_value_reader.seek(io::SeekFrom::Start(0)).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) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()) - .header(ContentType(json_mime_type.clone())) - .header(ContentLength(request_size as u64)) - .body(&mut request_value_reader); + let mut req = client.borrow_mut().request(hyper::method::Method::Put, &url) + .header(UserAgent(self.hub._user_agent.clone())); dlg.pre_request(); req.send() @@ -8137,17 +8112,7 @@ impl<'a, C, A> AccountContainerRuleCreateCall<'a, C, A> where C: BorrowMut Err(Error::BadRequest(serr)) } } - let result_value = { - let mut json_response = String::new(); - res.read_to_string(&mut json_response).unwrap(); - match json::from_str(&json_response) { - Ok(decoded) => (res, decoded), - Err(err) => { - dlg.response_json_decode_error(&json_response, &err); - return Err(Error::JsonDecodeError(json_response, err)); - } - } - }; + let result_value = res; dlg.finished(true); return Ok(result_value) @@ -8157,22 +8122,13 @@ impl<'a, C, A> AccountContainerRuleCreateCall<'a, C, A> where C: BorrowMut AccountContainerRuleCreateCall<'a, C, A> { - self._request = new_value; - self - } /// The GTM Account ID. /// /// 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. - pub fn account_id(mut self, new_value: &str) -> AccountContainerRuleCreateCall<'a, C, A> { + pub fn account_id(mut self, new_value: &str) -> AccountContainerMoveFolderUpdateCall<'a, C, A> { self._account_id = new_value.to_string(); self } @@ -8182,17 +8138,51 @@ impl<'a, C, A> AccountContainerRuleCreateCall<'a, C, A> where C: BorrowMut AccountContainerRuleCreateCall<'a, C, A> { + pub fn container_id(mut self, new_value: &str) -> AccountContainerMoveFolderUpdateCall<'a, C, A> { self._container_id = new_value.to_string(); self } + /// The GTM Folder ID. + /// + /// 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. + pub fn folder_id(mut self, new_value: &str) -> AccountContainerMoveFolderUpdateCall<'a, C, A> { + self._folder_id = new_value.to_string(); + self + } + /// The variables to be moved to the folder. + /// + /// Append the given value to the *variable id* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + pub fn add_variable_id(mut self, new_value: &str) -> AccountContainerMoveFolderUpdateCall<'a, C, A> { + self._variable_id.push(new_value.to_string()); + self + } + /// The triggers to be moved to the folder. + /// + /// Append the given value to the *trigger id* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + pub fn add_trigger_id(mut self, new_value: &str) -> AccountContainerMoveFolderUpdateCall<'a, C, A> { + self._trigger_id.push(new_value.to_string()); + self + } + /// The tags to be moved to the folder. + /// + /// Append the given value to the *tag id* query property. + /// Each appended value will retain its original ordering and be '/'-separated in the URL's parameters. + pub fn add_tag_id(mut self, new_value: &str) -> AccountContainerMoveFolderUpdateCall<'a, C, A> { + self._tag_id.push(new_value.to_string()); + self + } /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong /// while executing the actual API request. /// /// It should be used to handle progress information, and to implement a certain level of resilience. /// /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountContainerRuleCreateCall<'a, C, A> { + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountContainerMoveFolderUpdateCall<'a, C, A> { self._delegate = Some(new_value); self } @@ -8213,32 +8203,16 @@ impl<'a, C, A> AccountContainerRuleCreateCall<'a, C, A> where C: BorrowMut(mut self, name: T, value: T) -> AccountContainerRuleCreateCall<'a, C, A> + pub fn param(mut self, name: T, value: T) -> AccountContainerMoveFolderUpdateCall<'a, C, A> where T: AsRef { self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); self } - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::EditContainer`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be - /// sufficient, a read-write scope will do as well. - pub fn add_scope(mut self, scope: T) -> AccountContainerRuleCreateCall<'a, C, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().to_string(), ()); - self - } } -/// Restores a Container Version. This will overwrite the container's current configuration (including its macros, rules and tags). The operation will not have any effect on the version that is being served (i.e. the published version). +/// Restores a Container Version. This will overwrite the container's current configuration (including its variables, triggers and tags). The operation will not have any effect on the version that is being served (i.e. the published version). /// /// A builder for the *containers.versions.restore* method supported by a *account* resource. /// It is not used directly, but through a `AccountMethods` instance. @@ -8498,266 +8472,6 @@ impl<'a, C, A> AccountContainerVersionRestoreCall<'a, C, A> where C: BorrowMut::default(), None); -/// # let mut hub = TagManager::new(hyper::Client::new(), auth); -/// // You can configure optional parameters by calling 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().containers_rules_get("accountId", "containerId", "ruleId") -/// .doit(); -/// # } -/// ``` -pub struct AccountContainerRuleGetCall<'a, C, A> - where C: 'a, A: 'a { - - hub: &'a TagManager, - _account_id: String, - _container_id: String, - _rule_id: String, - _delegate: Option<&'a mut Delegate>, - _additional_params: HashMap, - _scopes: BTreeMap -} - -impl<'a, C, A> CallBuilder for AccountContainerRuleGetCall<'a, C, A> {} - -impl<'a, C, A> AccountContainerRuleGetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { - - - /// Perform the operation you have build so far. - pub fn doit(mut self) -> Result<(hyper::client::Response, Rule)> { - use std::io::{Read, Seek}; - use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; - let mut dd = DefaultDelegate; - let mut dlg: &mut Delegate = match self._delegate { - Some(d) => d, - None => &mut dd - }; - dlg.begin(MethodInfo { id: "tagmanager.accounts.containers.rules.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(("containerId", self._container_id.to_string())); - params.push(("ruleId", self._rule_id.to_string())); - for &field in ["alt", "accountId", "containerId", "ruleId"].iter() { - if self._additional_params.contains_key(field) { - dlg.finished(false); - return Err(Error::FieldClash(field)); - } - } - for (name, value) in self._additional_params.iter() { - params.push((&name, value.clone())); - } - - params.push(("alt", "json".to_string())); - - let mut url = "https://www.googleapis.com/tagmanager/v1/accounts/{accountId}/containers/{containerId}/rules/{ruleId}".to_string(); - if self._scopes.len() == 0 { - self._scopes.insert(Scope::Readonly.as_ref().to_string(), ()); - } - - for &(find_this, param_name) in [("{accountId}", "accountId"), ("{containerId}", "containerId"), ("{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(3); - for param_name in ["ruleId", "containerId", "accountId"].iter() { - if let Some(index) = params.iter().position(|t| &t.0 == param_name) { - indices_for_removal.push(index); - } - } - for &index in indices_for_removal.iter() { - params.remove(index); - } - } - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_token }); - let mut req_result = { - let mut client = &mut *self.hub.client.borrow_mut(); - let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = { - let mut json_response = String::new(); - res.read_to_string(&mut json_response).unwrap(); - match json::from_str(&json_response) { - Ok(decoded) => (res, decoded), - Err(err) => { - dlg.response_json_decode_error(&json_response, &err); - return Err(Error::JsonDecodeError(json_response, err)); - } - } - }; - - dlg.finished(true); - return Ok(result_value) - } - } - } - } - - - /// The GTM Account ID. - /// - /// 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. - pub fn account_id(mut self, new_value: &str) -> AccountContainerRuleGetCall<'a, C, A> { - self._account_id = new_value.to_string(); - self - } - /// The GTM Container ID. - /// - /// Sets the *container id* path property to the given value. - /// - /// Even though the property as already been set when instantiating this call, - /// we provide this method for API completeness. - pub fn container_id(mut self, new_value: &str) -> AccountContainerRuleGetCall<'a, C, A> { - self._container_id = new_value.to_string(); - self - } - /// The GTM Rule ID. - /// - /// 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. - pub fn rule_id(mut self, new_value: &str) -> AccountContainerRuleGetCall<'a, C, A> { - self._rule_id = new_value.to_string(); - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountContainerRuleGetCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. - /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. - /// * *alt* (query-string) - Data format for the response. - pub fn param(mut self, name: T, value: T) -> AccountContainerRuleGetCall<'a, C, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::Readonly`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be - /// sufficient, a read-write scope will do as well. - pub fn add_scope(mut self, scope: T) -> AccountContainerRuleGetCall<'a, C, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().to_string(), ()); - self - } -} - - /// Creates a GTM Variable. /// /// A builder for the *containers.variables.create* method supported by a *account* resource. @@ -9285,285 +8999,6 @@ impl<'a, C, A> AccountContainerVariableListCall<'a, C, A> where C: BorrowMut::default(), None); -/// # let mut hub = TagManager::new(hyper::Client::new(), auth); -/// // As the method needs a request, you would usually fill it with the desired information -/// // into the respective structure. Some of the parts shown here might not be applicable ! -/// // Values shown here are possibly random and not representative ! -/// let mut req = Macro::default(); -/// -/// // You can configure optional parameters by calling 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().containers_macros_create(req, "accountId", "containerId") -/// .doit(); -/// # } -/// ``` -pub struct AccountContainerMacroCreateCall<'a, C, A> - where C: 'a, A: 'a { - - hub: &'a TagManager, - _request: Macro, - _account_id: String, - _container_id: String, - _delegate: Option<&'a mut Delegate>, - _additional_params: HashMap, - _scopes: BTreeMap -} - -impl<'a, C, A> CallBuilder for AccountContainerMacroCreateCall<'a, C, A> {} - -impl<'a, C, A> AccountContainerMacroCreateCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { - - - /// Perform the operation you have build so far. - pub fn doit(mut self) -> Result<(hyper::client::Response, Macro)> { - use std::io::{Read, Seek}; - use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; - let mut dd = DefaultDelegate; - let mut dlg: &mut Delegate = match self._delegate { - Some(d) => d, - None => &mut dd - }; - dlg.begin(MethodInfo { id: "tagmanager.accounts.containers.macros.create", - 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(("containerId", self._container_id.to_string())); - for &field in ["alt", "accountId", "containerId"].iter() { - if self._additional_params.contains_key(field) { - dlg.finished(false); - return Err(Error::FieldClash(field)); - } - } - for (name, value) in self._additional_params.iter() { - params.push((&name, value.clone())); - } - - params.push(("alt", "json".to_string())); - - let mut url = "https://www.googleapis.com/tagmanager/v1/accounts/{accountId}/containers/{containerId}/macros".to_string(); - if self._scopes.len() == 0 { - self._scopes.insert(Scope::EditContainer.as_ref().to_string(), ()); - } - - for &(find_this, param_name) in [("{accountId}", "accountId"), ("{containerId}", "containerId")].iter() { - let mut replace_with: Option<&str> = None; - for &(name, ref value) in params.iter() { - if name == param_name { - replace_with = Some(value); - break; - } - } - url = url.replace(find_this, replace_with.expect("to find substitution value in params")); - } - { - let mut indices_for_removal: Vec = Vec::with_capacity(2); - for param_name in ["containerId", "accountId"].iter() { - if let Some(index) = params.iter().position(|t| &t.0 == param_name) { - indices_for_removal.push(index); - } - } - for &index in indices_for_removal.iter() { - params.remove(index); - } - } - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); - let mut request_value_reader = - { - let mut value = json::value::to_value(&self._request); - remove_json_null_values(&mut value); - let mut dst = io::Cursor::new(Vec::with_capacity(128)); - json::to_writer(&mut dst, &value).unwrap(); - dst - }; - let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); - request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_token }); - request_value_reader.seek(io::SeekFrom::Start(0)).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) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()) - .header(ContentType(json_mime_type.clone())) - .header(ContentLength(request_size as u64)) - .body(&mut request_value_reader); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = { - let mut json_response = String::new(); - res.read_to_string(&mut json_response).unwrap(); - match json::from_str(&json_response) { - Ok(decoded) => (res, decoded), - Err(err) => { - dlg.response_json_decode_error(&json_response, &err); - return Err(Error::JsonDecodeError(json_response, err)); - } - } - }; - - dlg.finished(true); - return Ok(result_value) - } - } - } - } - - - /// - /// Sets the *request* property to the given value. - /// - /// Even though the property as already been set when instantiating this call, - /// we provide this method for API completeness. - pub fn request(mut self, new_value: Macro) -> AccountContainerMacroCreateCall<'a, C, A> { - self._request = new_value; - self - } - /// The GTM Account ID. - /// - /// 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. - pub fn account_id(mut self, new_value: &str) -> AccountContainerMacroCreateCall<'a, C, A> { - self._account_id = new_value.to_string(); - self - } - /// The GTM Container ID. - /// - /// Sets the *container id* path property to the given value. - /// - /// Even though the property as already been set when instantiating this call, - /// we provide this method for API completeness. - pub fn container_id(mut self, new_value: &str) -> AccountContainerMacroCreateCall<'a, C, A> { - self._container_id = new_value.to_string(); - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountContainerMacroCreateCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. - /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. - /// * *alt* (query-string) - Data format for the response. - pub fn param(mut self, name: T, value: T) -> AccountContainerMacroCreateCall<'a, C, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::EditContainer`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be - /// sufficient, a read-write scope will do as well. - pub fn add_scope(mut self, scope: T) -> AccountContainerMacroCreateCall<'a, C, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().to_string(), ()); - self - } -} - - /// Gets a GTM Tag. /// /// A builder for the *containers.tags.get* method supported by a *account* resource. @@ -10333,254 +9768,6 @@ impl<'a, C, A> AccountContainerTriggerDeleteCall<'a, C, A> where C: BorrowMut::default(), None); -/// # let mut hub = TagManager::new(hyper::Client::new(), auth); -/// // You can configure optional parameters by calling 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().containers_macros_list("accountId", "containerId") -/// .doit(); -/// # } -/// ``` -pub struct AccountContainerMacroListCall<'a, C, A> - where C: 'a, A: 'a { - - hub: &'a TagManager, - _account_id: String, - _container_id: String, - _delegate: Option<&'a mut Delegate>, - _additional_params: HashMap, - _scopes: BTreeMap -} - -impl<'a, C, A> CallBuilder for AccountContainerMacroListCall<'a, C, A> {} - -impl<'a, C, A> AccountContainerMacroListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { - - - /// Perform the operation you have build so far. - pub fn doit(mut self) -> Result<(hyper::client::Response, ListMacrosResponse)> { - use std::io::{Read, Seek}; - use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; - let mut dd = DefaultDelegate; - let mut dlg: &mut Delegate = match self._delegate { - Some(d) => d, - None => &mut dd - }; - dlg.begin(MethodInfo { id: "tagmanager.accounts.containers.macros.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())); - params.push(("containerId", self._container_id.to_string())); - for &field in ["alt", "accountId", "containerId"].iter() { - if self._additional_params.contains_key(field) { - dlg.finished(false); - return Err(Error::FieldClash(field)); - } - } - for (name, value) in self._additional_params.iter() { - params.push((&name, value.clone())); - } - - params.push(("alt", "json".to_string())); - - let mut url = "https://www.googleapis.com/tagmanager/v1/accounts/{accountId}/containers/{containerId}/macros".to_string(); - if self._scopes.len() == 0 { - self._scopes.insert(Scope::Readonly.as_ref().to_string(), ()); - } - - for &(find_this, param_name) in [("{accountId}", "accountId"), ("{containerId}", "containerId")].iter() { - let mut replace_with: Option<&str> = None; - for &(name, ref value) in params.iter() { - if name == param_name { - replace_with = Some(value); - break; - } - } - url = url.replace(find_this, replace_with.expect("to find substitution value in params")); - } - { - let mut indices_for_removal: Vec = Vec::with_capacity(2); - for param_name in ["containerId", "accountId"].iter() { - if let Some(index) = params.iter().position(|t| &t.0 == param_name) { - indices_for_removal.push(index); - } - } - for &index in indices_for_removal.iter() { - params.remove(index); - } - } - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_token }); - let mut req_result = { - let mut client = &mut *self.hub.client.borrow_mut(); - let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = { - let mut json_response = String::new(); - res.read_to_string(&mut json_response).unwrap(); - match json::from_str(&json_response) { - Ok(decoded) => (res, decoded), - Err(err) => { - dlg.response_json_decode_error(&json_response, &err); - return Err(Error::JsonDecodeError(json_response, err)); - } - } - }; - - dlg.finished(true); - return Ok(result_value) - } - } - } - } - - - /// The GTM Account ID. - /// - /// 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. - pub fn account_id(mut self, new_value: &str) -> AccountContainerMacroListCall<'a, C, A> { - self._account_id = new_value.to_string(); - self - } - /// The GTM Container ID. - /// - /// Sets the *container id* path property to the given value. - /// - /// Even though the property as already been set when instantiating this call, - /// we provide this method for API completeness. - pub fn container_id(mut self, new_value: &str) -> AccountContainerMacroListCall<'a, C, A> { - self._container_id = new_value.to_string(); - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountContainerMacroListCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. - /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. - /// * *alt* (query-string) - Data format for the response. - pub fn param(mut self, name: T, value: T) -> AccountContainerMacroListCall<'a, C, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::Readonly`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be - /// sufficient, a read-write scope will do as well. - pub fn add_scope(mut self, scope: T) -> AccountContainerMacroListCall<'a, C, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().to_string(), ()); - self - } -} - - /// Creates a GTM Trigger. /// /// A builder for the *containers.triggers.create* method supported by a *account* resource. @@ -10860,9 +10047,9 @@ impl<'a, C, A> AccountContainerTriggerCreateCall<'a, C, A> where C: BorrowMut AccountContainerTriggerCreateCall<'a, C, A> where C: BorrowMut AccountContainerTriggerCreateCall<'a, C, A> where C: BorrowMut +pub struct AccountContainerFolderUpdateCall<'a, C, A> where C: 'a, A: 'a { hub: &'a TagManager, - _request: Macro, + _request: Folder, _account_id: String, _container_id: String, - _macro_id: String, + _folder_id: String, _fingerprint: Option, _delegate: Option<&'a mut Delegate>, _additional_params: HashMap, _scopes: BTreeMap } -impl<'a, C, A> CallBuilder for AccountContainerMacroUpdateCall<'a, C, A> {} +impl<'a, C, A> CallBuilder for AccountContainerFolderUpdateCall<'a, C, A> {} -impl<'a, C, A> AccountContainerMacroUpdateCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { +impl<'a, C, A> AccountContainerFolderUpdateCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { /// Perform the operation you have build so far. - pub fn doit(mut self) -> Result<(hyper::client::Response, Macro)> { + pub fn doit(mut self) -> Result<(hyper::client::Response, Folder)> { use std::io::{Read, Seek}; use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; let mut dd = DefaultDelegate; @@ -10925,16 +10112,16 @@ impl<'a, C, A> AccountContainerMacroUpdateCall<'a, C, A> where C: BorrowMut d, None => &mut dd }; - dlg.begin(MethodInfo { id: "tagmanager.accounts.containers.macros.update", + dlg.begin(MethodInfo { id: "tagmanager.accounts.containers.folders.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(("containerId", self._container_id.to_string())); - params.push(("macroId", self._macro_id.to_string())); + params.push(("folderId", self._folder_id.to_string())); if let Some(value) = self._fingerprint { params.push(("fingerprint", value.to_string())); } - for &field in ["alt", "accountId", "containerId", "macroId", "fingerprint"].iter() { + for &field in ["alt", "accountId", "containerId", "folderId", "fingerprint"].iter() { if self._additional_params.contains_key(field) { dlg.finished(false); return Err(Error::FieldClash(field)); @@ -10946,12 +10133,12 @@ impl<'a, C, A> AccountContainerMacroUpdateCall<'a, C, A> where C: BorrowMut = None; for &(name, ref value) in params.iter() { if name == param_name { @@ -10963,7 +10150,7 @@ impl<'a, C, A> AccountContainerMacroUpdateCall<'a, C, A> where C: BorrowMut = Vec::with_capacity(3); - for param_name in ["macroId", "containerId", "accountId"].iter() { + for param_name in ["folderId", "containerId", "accountId"].iter() { if let Some(index) = params.iter().position(|t| &t.0 == param_name) { indices_for_removal.push(index); } @@ -11070,7 +10257,7 @@ impl<'a, C, A> AccountContainerMacroUpdateCall<'a, C, A> where C: BorrowMut AccountContainerMacroUpdateCall<'a, C, A> { + pub fn request(mut self, new_value: Folder) -> AccountContainerFolderUpdateCall<'a, C, A> { self._request = new_value; self } @@ -11080,7 +10267,7 @@ impl<'a, C, A> AccountContainerMacroUpdateCall<'a, C, A> where C: BorrowMut AccountContainerMacroUpdateCall<'a, C, A> { + pub fn account_id(mut self, new_value: &str) -> AccountContainerFolderUpdateCall<'a, C, A> { self._account_id = new_value.to_string(); self } @@ -11090,24 +10277,24 @@ impl<'a, C, A> AccountContainerMacroUpdateCall<'a, C, A> where C: BorrowMut AccountContainerMacroUpdateCall<'a, C, A> { + pub fn container_id(mut self, new_value: &str) -> AccountContainerFolderUpdateCall<'a, C, A> { self._container_id = new_value.to_string(); self } - /// The GTM Macro ID. + /// The GTM Folder ID. /// - /// Sets the *macro id* path property to the given 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. - pub fn macro_id(mut self, new_value: &str) -> AccountContainerMacroUpdateCall<'a, C, A> { - self._macro_id = new_value.to_string(); + pub fn folder_id(mut self, new_value: &str) -> AccountContainerFolderUpdateCall<'a, C, A> { + self._folder_id = new_value.to_string(); self } - /// When provided, this fingerprint must match the fingerprint of the macro in storage. + /// When provided, this fingerprint must match the fingerprint of the folder in storage. /// /// Sets the *fingerprint* query property to the given value. - pub fn fingerprint(mut self, new_value: &str) -> AccountContainerMacroUpdateCall<'a, C, A> { + pub fn fingerprint(mut self, new_value: &str) -> AccountContainerFolderUpdateCall<'a, C, A> { self._fingerprint = Some(new_value.to_string()); self } @@ -11117,7 +10304,7 @@ impl<'a, C, A> AccountContainerMacroUpdateCall<'a, C, A> where C: BorrowMut AccountContainerMacroUpdateCall<'a, C, A> { + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountContainerFolderUpdateCall<'a, C, A> { self._delegate = Some(new_value); self } @@ -11138,7 +10325,7 @@ impl<'a, C, A> AccountContainerMacroUpdateCall<'a, C, A> where C: BorrowMut(mut self, name: T, value: T) -> AccountContainerMacroUpdateCall<'a, C, A> + pub fn param(mut self, name: T, value: T) -> AccountContainerFolderUpdateCall<'a, C, A> where T: AsRef { self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); self @@ -11155,7 +10342,7 @@ impl<'a, C, A> AccountContainerMacroUpdateCall<'a, C, A> where C: BorrowMut(mut self, scope: T) -> AccountContainerMacroUpdateCall<'a, C, A> + pub fn add_scope(mut self, scope: T) -> AccountContainerFolderUpdateCall<'a, C, A> where T: AsRef { self._scopes.insert(scope.as_ref().to_string(), ()); self @@ -12421,254 +11608,6 @@ impl<'a, C, A> AccountContainerUpdateCall<'a, C, A> where C: BorrowMut::default(), None); -/// # let mut hub = TagManager::new(hyper::Client::new(), auth); -/// // You can configure optional parameters by calling 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().containers_rules_list("accountId", "containerId") -/// .doit(); -/// # } -/// ``` -pub struct AccountContainerRuleListCall<'a, C, A> - where C: 'a, A: 'a { - - hub: &'a TagManager, - _account_id: String, - _container_id: String, - _delegate: Option<&'a mut Delegate>, - _additional_params: HashMap, - _scopes: BTreeMap -} - -impl<'a, C, A> CallBuilder for AccountContainerRuleListCall<'a, C, A> {} - -impl<'a, C, A> AccountContainerRuleListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { - - - /// Perform the operation you have build so far. - pub fn doit(mut self) -> Result<(hyper::client::Response, ListRulesResponse)> { - use std::io::{Read, Seek}; - use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; - let mut dd = DefaultDelegate; - let mut dlg: &mut Delegate = match self._delegate { - Some(d) => d, - None => &mut dd - }; - dlg.begin(MethodInfo { id: "tagmanager.accounts.containers.rules.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())); - params.push(("containerId", self._container_id.to_string())); - for &field in ["alt", "accountId", "containerId"].iter() { - if self._additional_params.contains_key(field) { - dlg.finished(false); - return Err(Error::FieldClash(field)); - } - } - for (name, value) in self._additional_params.iter() { - params.push((&name, value.clone())); - } - - params.push(("alt", "json".to_string())); - - let mut url = "https://www.googleapis.com/tagmanager/v1/accounts/{accountId}/containers/{containerId}/rules".to_string(); - if self._scopes.len() == 0 { - self._scopes.insert(Scope::Readonly.as_ref().to_string(), ()); - } - - for &(find_this, param_name) in [("{accountId}", "accountId"), ("{containerId}", "containerId")].iter() { - let mut replace_with: Option<&str> = None; - for &(name, ref value) in params.iter() { - if name == param_name { - replace_with = Some(value); - break; - } - } - url = url.replace(find_this, replace_with.expect("to find substitution value in params")); - } - { - let mut indices_for_removal: Vec = Vec::with_capacity(2); - for param_name in ["containerId", "accountId"].iter() { - if let Some(index) = params.iter().position(|t| &t.0 == param_name) { - indices_for_removal.push(index); - } - } - for &index in indices_for_removal.iter() { - params.remove(index); - } - } - - if params.len() > 0 { - url.push('?'); - url.push_str(&url::form_urlencoded::serialize(params)); - } - - - - loop { - let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { - Ok(token) => token, - Err(err) => { - match dlg.token(&*err) { - Some(token) => token, - None => { - dlg.finished(false); - return Err(Error::MissingToken(err)) - } - } - } - }; - let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, - access_token: token.access_token }); - let mut req_result = { - let mut client = &mut *self.hub.client.borrow_mut(); - let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) - .header(UserAgent(self.hub._user_agent.clone())) - .header(auth_header.clone()); - - dlg.pre_request(); - req.send() - }; - - match req_result { - Err(err) => { - if let oauth2::Retry::After(d) = dlg.http_error(&err) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return Err(Error::HttpError(err)) - } - Ok(mut res) => { - if !res.status.is_success() { - let mut json_err = String::new(); - res.read_to_string(&mut json_err).unwrap(); - if let oauth2::Retry::After(d) = dlg.http_failure(&res, - json::from_str(&json_err).ok(), - json::from_str(&json_err).ok()) { - sleep_ms(d.num_milliseconds() as u32); - continue; - } - dlg.finished(false); - return match json::from_str::(&json_err){ - Err(_) => Err(Error::Failure(res)), - Ok(serr) => Err(Error::BadRequest(serr)) - } - } - let result_value = { - let mut json_response = String::new(); - res.read_to_string(&mut json_response).unwrap(); - match json::from_str(&json_response) { - Ok(decoded) => (res, decoded), - Err(err) => { - dlg.response_json_decode_error(&json_response, &err); - return Err(Error::JsonDecodeError(json_response, err)); - } - } - }; - - dlg.finished(true); - return Ok(result_value) - } - } - } - } - - - /// The GTM Account ID. - /// - /// 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. - pub fn account_id(mut self, new_value: &str) -> AccountContainerRuleListCall<'a, C, A> { - self._account_id = new_value.to_string(); - self - } - /// The GTM Container ID. - /// - /// Sets the *container id* path property to the given value. - /// - /// Even though the property as already been set when instantiating this call, - /// we provide this method for API completeness. - pub fn container_id(mut self, new_value: &str) -> AccountContainerRuleListCall<'a, C, A> { - self._container_id = new_value.to_string(); - self - } - /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong - /// while executing the actual API request. - /// - /// It should be used to handle progress information, and to implement a certain level of resilience. - /// - /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountContainerRuleListCall<'a, C, A> { - self._delegate = Some(new_value); - self - } - - /// Set any additional parameter of the query string used in the request. - /// It should be used to set parameters which are not yet available through their own - /// setters. - /// - /// Please note that this method must not be used to set any of the known paramters - /// which have their own setter method. If done anyway, the request will fail. - /// - /// # Additional Parameters - /// - /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. - /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. - /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. - /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. - /// * *alt* (query-string) - Data format for the response. - pub fn param(mut self, name: T, value: T) -> AccountContainerRuleListCall<'a, C, A> - where T: AsRef { - self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); - self - } - - /// Identifies the authorization scope for the method you are building. - /// - /// Use this method to actively specify which scope should be used, instead the default `Scope` variant - /// `Scope::Readonly`. - /// - /// The `scope` will be added to a set of scopes. This is important as one can maintain access - /// tokens for more than one scope. - /// - /// Usually there is more than one suitable scope to authorize an operation, some of which may - /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be - /// sufficient, a read-write scope will do as well. - pub fn add_scope(mut self, scope: T) -> AccountContainerRuleListCall<'a, C, A> - where T: AsRef { - self._scopes.insert(scope.as_ref().to_string(), ()); - self - } -} - - /// Updates a GTM Tag. /// /// A builder for the *containers.tags.update* method supported by a *account* resource. @@ -12702,7 +11641,7 @@ impl<'a, C, A> AccountContainerRuleListCall<'a, C, A> where C: BorrowMut AccountContainerTagUpdateCall<'a, C, A> where C: BorrowMut::default(), None); +/// # let mut hub = TagManager::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the respective structure. Some of the parts shown here might not be applicable ! +/// // Values shown here are possibly random and not representative ! +/// let mut req = Folder::default(); +/// +/// // You can configure optional parameters by calling 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().containers_folders_create(req, "accountId", "containerId") +/// .doit(); +/// # } +/// ``` +pub struct AccountContainerFolderCreateCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a TagManager, + _request: Folder, + _account_id: String, + _container_id: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for AccountContainerFolderCreateCall<'a, C, A> {} + +impl<'a, C, A> AccountContainerFolderCreateCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Folder)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "tagmanager.accounts.containers.folders.create", + 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(("containerId", self._container_id.to_string())); + for &field in ["alt", "accountId", "containerId"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://www.googleapis.com/tagmanager/v1/accounts/{accountId}/containers/{containerId}/folders".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::EditContainer.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{accountId}", "accountId"), ("{containerId}", "containerId")].iter() { + let mut replace_with: Option<&str> = None; + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = Some(value); + break; + } + } + url = url.replace(find_this, replace_with.expect("to find substitution value in params")); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["containerId", "accountId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn request(mut self, new_value: Folder) -> AccountContainerFolderCreateCall<'a, C, A> { + self._request = new_value; + self + } + /// The GTM Account ID. + /// + /// 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. + pub fn account_id(mut self, new_value: &str) -> AccountContainerFolderCreateCall<'a, C, A> { + self._account_id = new_value.to_string(); + self + } + /// The GTM Container ID. + /// + /// Sets the *container id* path property to the given value. + /// + /// Even though the property as already been set when instantiating this call, + /// we provide this method for API completeness. + pub fn container_id(mut self, new_value: &str) -> AccountContainerFolderCreateCall<'a, C, A> { + self._container_id = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountContainerFolderCreateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *alt* (query-string) - Data format for the response. + pub fn param(mut self, name: T, value: T) -> AccountContainerFolderCreateCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::EditContainer`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> AccountContainerFolderCreateCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Lists all GTM Folders of a Container. +/// +/// A builder for the *containers.folders.list* method supported by a *account* resource. /// It is not used directly, but through a `AccountMethods` instance. /// /// # Example @@ -12998,29 +12216,28 @@ impl<'a, C, A> AccountContainerTagUpdateCall<'a, C, A> where C: BorrowMut +pub struct AccountContainerFolderListCall<'a, C, A> where C: 'a, A: 'a { hub: &'a TagManager, _account_id: String, _container_id: String, - _macro_id: String, _delegate: Option<&'a mut Delegate>, _additional_params: HashMap, _scopes: BTreeMap } -impl<'a, C, A> CallBuilder for AccountContainerMacroGetCall<'a, C, A> {} +impl<'a, C, A> CallBuilder for AccountContainerFolderListCall<'a, C, A> {} -impl<'a, C, A> AccountContainerMacroGetCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { +impl<'a, C, A> AccountContainerFolderListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { /// Perform the operation you have build so far. - pub fn doit(mut self) -> Result<(hyper::client::Response, Macro)> { + pub fn doit(mut self) -> Result<(hyper::client::Response, ListFoldersResponse)> { use std::io::{Read, Seek}; use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; let mut dd = DefaultDelegate; @@ -13028,13 +12245,12 @@ impl<'a, C, A> AccountContainerMacroGetCall<'a, C, A> where C: BorrowMut d, None => &mut dd }; - dlg.begin(MethodInfo { id: "tagmanager.accounts.containers.macros.get", + dlg.begin(MethodInfo { id: "tagmanager.accounts.containers.folders.list", http_method: hyper::method::Method::Get }); - let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); params.push(("accountId", self._account_id.to_string())); params.push(("containerId", self._container_id.to_string())); - params.push(("macroId", self._macro_id.to_string())); - for &field in ["alt", "accountId", "containerId", "macroId"].iter() { + for &field in ["alt", "accountId", "containerId"].iter() { if self._additional_params.contains_key(field) { dlg.finished(false); return Err(Error::FieldClash(field)); @@ -13046,12 +12262,12 @@ impl<'a, C, A> AccountContainerMacroGetCall<'a, C, A> where C: BorrowMut = None; for &(name, ref value) in params.iter() { if name == param_name { @@ -13062,8 +12278,8 @@ impl<'a, C, A> AccountContainerMacroGetCall<'a, C, A> where C: BorrowMut = Vec::with_capacity(3); - for param_name in ["macroId", "containerId", "accountId"].iter() { + let mut indices_for_removal: Vec = Vec::with_capacity(2); + for param_name in ["containerId", "accountId"].iter() { if let Some(index) = params.iter().position(|t| &t.0 == param_name) { indices_for_removal.push(index); } @@ -13156,7 +12372,7 @@ impl<'a, C, A> AccountContainerMacroGetCall<'a, C, A> where C: BorrowMut AccountContainerMacroGetCall<'a, C, A> { + pub fn account_id(mut self, new_value: &str) -> AccountContainerFolderListCall<'a, C, A> { self._account_id = new_value.to_string(); self } @@ -13166,27 +12382,17 @@ impl<'a, C, A> AccountContainerMacroGetCall<'a, C, A> where C: BorrowMut AccountContainerMacroGetCall<'a, C, A> { + pub fn container_id(mut self, new_value: &str) -> AccountContainerFolderListCall<'a, C, A> { self._container_id = new_value.to_string(); self } - /// The GTM Macro ID. - /// - /// Sets the *macro id* path property to the given value. - /// - /// Even though the property as already been set when instantiating this call, - /// we provide this method for API completeness. - pub fn macro_id(mut self, new_value: &str) -> AccountContainerMacroGetCall<'a, C, A> { - self._macro_id = new_value.to_string(); - self - } /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong /// while executing the actual API request. /// /// It should be used to handle progress information, and to implement a certain level of resilience. /// /// Sets the *delegate* property to the given value. - pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountContainerMacroGetCall<'a, C, A> { + pub fn delegate(mut self, new_value: &'a mut Delegate) -> AccountContainerFolderListCall<'a, C, A> { self._delegate = Some(new_value); self } @@ -13207,7 +12413,7 @@ impl<'a, C, A> AccountContainerMacroGetCall<'a, C, A> where C: BorrowMut(mut self, name: T, value: T) -> AccountContainerMacroGetCall<'a, C, A> + pub fn param(mut self, name: T, value: T) -> AccountContainerFolderListCall<'a, C, A> where T: AsRef { self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); self @@ -13224,7 +12430,7 @@ impl<'a, C, A> AccountContainerMacroGetCall<'a, C, A> where C: BorrowMut(mut self, scope: T) -> AccountContainerMacroGetCall<'a, C, A> + pub fn add_scope(mut self, scope: T) -> AccountContainerFolderListCall<'a, C, A> where T: AsRef { self._scopes.insert(scope.as_ref().to_string(), ()); self @@ -13265,7 +12471,7 @@ impl<'a, C, A> AccountContainerMacroGetCall<'a, C, A> where C: BorrowMut AccountContainerVersionUpdateCall<'a, C, A> where C: BorrowMut"] description = "A complete library to interact with webmasters (protocol v3)" repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/webmasters3-cli" diff --git a/gen/webmasters3-cli/README.md b/gen/webmasters3-cli/README.md index 83af890f93..3e39287dca 100644 --- a/gen/webmasters3-cli/README.md +++ b/gen/webmasters3-cli/README.md @@ -24,7 +24,7 @@ Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/ma # Usage -This documentation was generated from the *webmasters* API at revision *20150624*. The CLI is at version *0.3.2*. +This documentation was generated from the *webmasters* API at revision *20150804*. The CLI is at version *0.3.2*. ```bash webmasters3 [options] diff --git a/gen/webmasters3-cli/mkdocs.yml b/gen/webmasters3-cli/mkdocs.yml index bc6e4319e9..f62f2608f6 100644 --- a/gen/webmasters3-cli/mkdocs.yml +++ b/gen/webmasters3-cli/mkdocs.yml @@ -1,4 +1,4 @@ -site_name: webmasters v0.3.2+20150624 +site_name: webmasters v0.3.2+20150804 site_url: http://byron.github.io/google-apis-rs/google-webmasters3-cli site_description: Write integrating applications with bcore diff --git a/gen/webmasters3-cli/src/main.rs b/gen/webmasters3-cli/src/main.rs index 74ac43bf23..95e8675eb3 100644 --- a/gen/webmasters3-cli/src/main.rs +++ b/gen/webmasters3-cli/src/main.rs @@ -901,9 +901,7 @@ fn main() { let arg_data = [ ("searchanalytics", "methods: 'query'", vec![ ("query", - Some(r##"[LIMITED ACCESS] - - Query your data with filters and parameters that you define. Returns zero or more rows grouped by the row keys that you define. You must define a date range of one or more days. + Some(r##"Query your data with filters and parameters that you define. Returns zero or more rows grouped by the row keys that you define. You must define a date range of one or more days. When date is one of the group by values, any days without data are omitted from the result list. If you need to know which days have data, issue a broad date range query grouped by date for any metric, and see which day rows are returned."##), "Details at http://byron.github.io/google-apis-rs/google_webmasters3_cli/searchanalytics_query", @@ -1244,7 +1242,7 @@ fn main() { let mut app = App::new("webmasters3") .author("Sebastian Thiel ") - .version("0.3.2+20150624") + .version("0.3.2+20150804") .about("Lets you view Google Webmaster Tools data for your verified sites.") .after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_webmasters3_cli") .arg(Arg::with_name("url") diff --git a/gen/webmasters3/Cargo.toml b/gen/webmasters3/Cargo.toml index aa3cb46917..146a4990ad 100644 --- a/gen/webmasters3/Cargo.toml +++ b/gen/webmasters3/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-webmasters3" -version = "0.1.9+20150624" +version = "0.1.9+20150804" authors = ["Sebastian Thiel "] description = "A complete library to interact with webmasters (protocol v3)" repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/webmasters3" diff --git a/gen/webmasters3/README.md b/gen/webmasters3/README.md index 5d06d46dd1..a41493ddb9 100644 --- a/gen/webmasters3/README.md +++ b/gen/webmasters3/README.md @@ -5,7 +5,7 @@ DO NOT EDIT ! --> The `google-webmasters3` library allows access to all features of the *Google webmasters* service. -This documentation was generated from *webmasters* crate version *0.1.9+20150624*, where *20150624* is the exact revision of the *webmasters:v3* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +This documentation was generated from *webmasters* crate version *0.1.9+20150804*, where *20150804* is the exact revision of the *webmasters:v3* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. Everything else about the *webmasters* *v3* API can be found at the [official documentation site](https://developers.google.com/webmaster-tools/). diff --git a/gen/webmasters3/src/lib.rs b/gen/webmasters3/src/lib.rs index 2e32efc1aa..7c36e7dc58 100644 --- a/gen/webmasters3/src/lib.rs +++ b/gen/webmasters3/src/lib.rs @@ -2,7 +2,7 @@ // This file was generated automatically from 'src/mako/api/lib.rs.mako' // DO NOT EDIT ! -//! This documentation was generated from *webmasters* crate version *0.1.9+20150624*, where *20150624* is the exact revision of the *webmasters:v3* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +//! This documentation was generated from *webmasters* crate version *0.1.9+20150804*, where *20150804* is the exact revision of the *webmasters:v3* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. //! //! Everything else about the *webmasters* *v3* API can be found at the //! [official documentation site](https://developers.google.com/webmaster-tools/). diff --git a/gen/webmasters3/src/lib.rs.in b/gen/webmasters3/src/lib.rs.in index 397f336e57..a1d5910508 100644 --- a/gen/webmasters3/src/lib.rs.in +++ b/gen/webmasters3/src/lib.rs.in @@ -369,20 +369,20 @@ pub struct SearchAnalyticsQueryRequest { pub end_date: Option, /// [Optional] Zero or more dimensions to group results by. Dimensions are the group-by values in the Search Analytics page. Dimensions are combined to create a unique row key for each row. Results are grouped in the order that you supply these dimensions. pub dimensions: Option>, - /// [Optional; Default is WEB] The search type to filter for. + /// [Optional; Default is "web"] The search type to filter for. #[serde(rename="searchType")] pub search_type: Option, - /// [Optional] Zero or more filters to apply to the dimension grouping values; for example, 'Country CONTAINS "Guinea"' to see only data where the country contains the substring "Guinea". You can filter by a dimension without grouping by it. + /// [Optional] Zero or more filters to apply to the dimension grouping values; for example, 'query contains "buy"' to see only data where the query string contains the substring "buy" (not case-sensitive). You can filter by a dimension without grouping by it. #[serde(rename="dimensionFilterGroups")] pub dimension_filter_groups: Option>, - /// [Optional; Default is AUTO] How data is aggregated. If aggregated by property, all data for the same property is aggregated; if aggregated by page, all data is aggregated by canonical URI. If you filter or group by page, choose AUTO; otherwise you can aggregate either by property or by page, depending on how you want your data calculated; see the help documentation to learn how data is calculated differently by site versus by page. + /// [Optional; Default is "auto"] How data is aggregated. If aggregated by property, all data for the same property is aggregated; if aggregated by page, all data is aggregated by canonical URI. If you filter or group by page, choose AUTO; otherwise you can aggregate either by property or by page, depending on how you want your data calculated; see the help documentation to learn how data is calculated differently by site versus by page. /// /// Note: If you group or filter by page, you cannot aggregate by property. /// /// If you specify any value other than AUTO, the aggregation type in the result will match the requested type, or if you request an invalid type, you will get an error. The API will never change your aggregation type if the requested type is invalid. #[serde(rename="aggregationType")] pub aggregation_type: Option, - /// [Optional; Default is 1000] The maximum number of rows to return. Must be a number from 1 to 1,000 (inclusive). + /// [Optional; Default is 1000] The maximum number of rows to return. Must be a number from 1 to 5,000 (inclusive). #[serde(rename="rowLimit")] pub row_limit: Option, } @@ -778,8 +778,6 @@ impl<'a, C, A> SearchanalyticMethods<'a, C, A> { /// Create a builder to help you perform the following task: /// - /// [LIMITED ACCESS] - /// /// Query your data with filters and parameters that you define. Returns zero or more rows grouped by the row keys that you define. You must define a date range of one or more days. /// /// When date is one of the group by values, any days without data are omitted from the result list. If you need to know which days have data, issue a broad date range query grouped by date for any metric, and see which day rows are returned. @@ -2836,8 +2834,6 @@ impl<'a, C, A> SiteDeleteCall<'a, C, A> where C: BorrowMut, A: oa } -/// [LIMITED ACCESS] -/// /// Query your data with filters and parameters that you define. Returns zero or more rows grouped by the row keys that you define. You must define a date range of one or more days. /// /// When date is one of the group by values, any days without data are omitted from the result list. If you need to know which days have data, issue a broad date range query grouped by date for any metric, and see which day rows are returned. diff --git a/gen/youtube3-cli/Cargo.toml b/gen/youtube3-cli/Cargo.toml index 05bf6dd0c4..9e4fa4d00c 100644 --- a/gen/youtube3-cli/Cargo.toml +++ b/gen/youtube3-cli/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-youtube3-cli" -version = "0.3.2+20150706" +version = "0.3.2+20151012" authors = ["Sebastian Thiel "] description = "A complete library to interact with YouTube (protocol v3)" repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/youtube3-cli" diff --git a/gen/youtube3-cli/README.md b/gen/youtube3-cli/README.md index 0cd2d216a2..660a62c314 100644 --- a/gen/youtube3-cli/README.md +++ b/gen/youtube3-cli/README.md @@ -24,7 +24,7 @@ Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/ma # Usage -This documentation was generated from the *YouTube* API at revision *20150706*. The CLI is at version *0.3.2*. +This documentation was generated from the *YouTube* API at revision *20151012*. The CLI is at version *0.3.2*. ```bash youtube3 [options] diff --git a/gen/youtube3-cli/mkdocs.yml b/gen/youtube3-cli/mkdocs.yml index b7a568957a..9061edd3a1 100644 --- a/gen/youtube3-cli/mkdocs.yml +++ b/gen/youtube3-cli/mkdocs.yml @@ -1,4 +1,4 @@ -site_name: YouTube v0.3.2+20150706 +site_name: YouTube v0.3.2+20151012 site_url: http://byron.github.io/google-apis-rs/google-youtube3-cli site_description: Write integrating applications with bcore diff --git a/gen/youtube3-cli/src/main.rs b/gen/youtube3-cli/src/main.rs index 9a3e78a4eb..e81a78f96f 100644 --- a/gen/youtube3-cli/src/main.rs +++ b/gen/youtube3-cli/src/main.rs @@ -301,9 +301,6 @@ impl<'n, 'a> Engine<'n, 'a> { "on-behalf-of" => { call = call.on_behalf_of(value.unwrap_or("")); }, - "debug-project-id-override" => { - call = call.debug_project_id_override(value.unwrap_or("")); - }, _ => { let mut found = false; for param in &self.gp { @@ -317,7 +314,7 @@ impl<'n, 'a> Engine<'n, 'a> { err.issues.push(CLIError::UnknownParameter(key.to_string(), {let mut v = Vec::new(); v.extend(self.gp.iter().map(|v|*v)); - v.extend(["on-behalf-of-content-owner", "on-behalf-of", "debug-project-id-override"].iter().map(|v|*v)); + v.extend(["on-behalf-of-content-owner", "on-behalf-of"].iter().map(|v|*v)); v } )); } } @@ -362,9 +359,6 @@ impl<'n, 'a> Engine<'n, 'a> { "on-behalf-of" => { call = call.on_behalf_of(value.unwrap_or("")); }, - "debug-project-id-override" => { - call = call.debug_project_id_override(value.unwrap_or("")); - }, _ => { let mut found = false; for param in &self.gp { @@ -381,7 +375,7 @@ impl<'n, 'a> Engine<'n, 'a> { err.issues.push(CLIError::UnknownParameter(key.to_string(), {let mut v = Vec::new(); v.extend(self.gp.iter().map(|v|*v)); - v.extend(["tfmt", "on-behalf-of-content-owner", "on-behalf-of", "tlang", "debug-project-id-override"].iter().map(|v|*v)); + v.extend(["tfmt", "on-behalf-of-content-owner", "on-behalf-of", "tlang"].iter().map(|v|*v)); v } )); } } @@ -479,9 +473,6 @@ impl<'n, 'a> Engine<'n, 'a> { "on-behalf-of" => { call = call.on_behalf_of(value.unwrap_or("")); }, - "debug-project-id-override" => { - call = call.debug_project_id_override(value.unwrap_or("")); - }, _ => { let mut found = false; for param in &self.gp { @@ -495,7 +486,7 @@ impl<'n, 'a> Engine<'n, 'a> { err.issues.push(CLIError::UnknownParameter(key.to_string(), {let mut v = Vec::new(); v.extend(self.gp.iter().map(|v|*v)); - v.extend(["on-behalf-of-content-owner", "on-behalf-of", "sync", "debug-project-id-override"].iter().map(|v|*v)); + v.extend(["on-behalf-of-content-owner", "on-behalf-of", "sync"].iter().map(|v|*v)); v } )); } } @@ -548,9 +539,6 @@ impl<'n, 'a> Engine<'n, 'a> { "id" => { call = call.id(value.unwrap_or("")); }, - "debug-project-id-override" => { - call = call.debug_project_id_override(value.unwrap_or("")); - }, _ => { let mut found = false; for param in &self.gp { @@ -564,7 +552,7 @@ impl<'n, 'a> Engine<'n, 'a> { err.issues.push(CLIError::UnknownParameter(key.to_string(), {let mut v = Vec::new(); v.extend(self.gp.iter().map(|v|*v)); - v.extend(["on-behalf-of-content-owner", "debug-project-id-override", "on-behalf-of", "id"].iter().map(|v|*v)); + v.extend(["on-behalf-of-content-owner", "on-behalf-of", "id"].iter().map(|v|*v)); v } )); } } @@ -661,9 +649,6 @@ impl<'n, 'a> Engine<'n, 'a> { "on-behalf-of" => { call = call.on_behalf_of(value.unwrap_or("")); }, - "debug-project-id-override" => { - call = call.debug_project_id_override(value.unwrap_or("")); - }, _ => { let mut found = false; for param in &self.gp { @@ -677,7 +662,7 @@ impl<'n, 'a> Engine<'n, 'a> { err.issues.push(CLIError::UnknownParameter(key.to_string(), {let mut v = Vec::new(); v.extend(self.gp.iter().map(|v|*v)); - v.extend(["on-behalf-of-content-owner", "on-behalf-of", "sync", "debug-project-id-override"].iter().map(|v|*v)); + v.extend(["on-behalf-of-content-owner", "on-behalf-of", "sync"].iter().map(|v|*v)); v } )); } } @@ -1467,9 +1452,6 @@ impl<'n, 'a> Engine<'n, 'a> { for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { let (key, value) = parse_kv_arg(&*parg, err, false); match key { - "share-on-google-plus" => { - call = call.share_on_google_plus(arg_from_str(value.unwrap_or("false"), err, "share-on-google-plus", "boolean")); - }, _ => { let mut found = false; for param in &self.gp { @@ -1483,7 +1465,6 @@ impl<'n, 'a> Engine<'n, 'a> { err.issues.push(CLIError::UnknownParameter(key.to_string(), {let mut v = Vec::new(); v.extend(self.gp.iter().map(|v|*v)); - v.extend(["share-on-google-plus"].iter().map(|v|*v)); v } )); } } @@ -2584,6 +2565,7 @@ impl<'n, 'a> Engine<'n, 'a> { "snippet.title" => Some(("snippet.title", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "snippet.channel-id" => Some(("snippet.channelId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "snippet.published-at" => Some(("snippet.publishedAt", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "snippet.live-chat-id" => Some(("snippet.liveChatId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "snippet.scheduled-start-time" => Some(("snippet.scheduledStartTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "snippet.actual-start-time" => Some(("snippet.actualStartTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "snippet.scheduled-end-time" => Some(("snippet.scheduledEndTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), @@ -2606,7 +2588,7 @@ impl<'n, 'a> Engine<'n, 'a> { "etag" => Some(("etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), _ => { - let suggestion = FieldCursor::did_you_mean(key, &vec!["actual-end-time", "actual-start-time", "bound-stream-id", "broadcast-stream-delay-ms", "channel-id", "concurrent-viewers", "content-details", "default", "description", "embed-html", "enable-closed-captions", "enable-content-encryption", "enable-dvr", "enable-embed", "enable-low-latency", "enable-monitor-stream", "etag", "height", "high", "id", "is-default-broadcast", "kind", "life-cycle-status", "live-broadcast-priority", "maxres", "medium", "monitor-stream", "privacy-status", "published-at", "record-from-start", "recording-status", "scheduled-end-time", "scheduled-start-time", "snippet", "standard", "start-with-slate", "statistics", "status", "thumbnails", "title", "total-chat-count", "url", "width"]); + let suggestion = FieldCursor::did_you_mean(key, &vec!["actual-end-time", "actual-start-time", "bound-stream-id", "broadcast-stream-delay-ms", "channel-id", "concurrent-viewers", "content-details", "default", "description", "embed-html", "enable-closed-captions", "enable-content-encryption", "enable-dvr", "enable-embed", "enable-low-latency", "enable-monitor-stream", "etag", "height", "high", "id", "is-default-broadcast", "kind", "life-cycle-status", "live-broadcast-priority", "live-chat-id", "maxres", "medium", "monitor-stream", "privacy-status", "published-at", "record-from-start", "recording-status", "scheduled-end-time", "scheduled-start-time", "snippet", "standard", "start-with-slate", "statistics", "status", "thumbnails", "title", "total-chat-count", "url", "width"]); err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); None } @@ -2852,6 +2834,7 @@ impl<'n, 'a> Engine<'n, 'a> { "snippet.title" => Some(("snippet.title", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "snippet.channel-id" => Some(("snippet.channelId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "snippet.published-at" => Some(("snippet.publishedAt", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "snippet.live-chat-id" => Some(("snippet.liveChatId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "snippet.scheduled-start-time" => Some(("snippet.scheduledStartTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "snippet.actual-start-time" => Some(("snippet.actualStartTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "snippet.scheduled-end-time" => Some(("snippet.scheduledEndTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), @@ -2874,7 +2857,7 @@ impl<'n, 'a> Engine<'n, 'a> { "etag" => Some(("etag", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), _ => { - let suggestion = FieldCursor::did_you_mean(key, &vec!["actual-end-time", "actual-start-time", "bound-stream-id", "broadcast-stream-delay-ms", "channel-id", "concurrent-viewers", "content-details", "default", "description", "embed-html", "enable-closed-captions", "enable-content-encryption", "enable-dvr", "enable-embed", "enable-low-latency", "enable-monitor-stream", "etag", "height", "high", "id", "is-default-broadcast", "kind", "life-cycle-status", "live-broadcast-priority", "maxres", "medium", "monitor-stream", "privacy-status", "published-at", "record-from-start", "recording-status", "scheduled-end-time", "scheduled-start-time", "snippet", "standard", "start-with-slate", "statistics", "status", "thumbnails", "title", "total-chat-count", "url", "width"]); + let suggestion = FieldCursor::did_you_mean(key, &vec!["actual-end-time", "actual-start-time", "bound-stream-id", "broadcast-stream-delay-ms", "channel-id", "concurrent-viewers", "content-details", "default", "description", "embed-html", "enable-closed-captions", "enable-content-encryption", "enable-dvr", "enable-embed", "enable-low-latency", "enable-monitor-stream", "etag", "height", "high", "id", "is-default-broadcast", "kind", "life-cycle-status", "live-broadcast-priority", "live-chat-id", "maxres", "medium", "monitor-stream", "privacy-status", "published-at", "record-from-start", "recording-status", "scheduled-end-time", "scheduled-start-time", "snippet", "standard", "start-with-slate", "statistics", "status", "thumbnails", "title", "total-chat-count", "url", "width"]); err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); None } @@ -4743,6 +4726,7 @@ impl<'n, 'a> Engine<'n, 'a> { "content-details.content-rating.pefilm-rating" => Some(("contentDetails.contentRating.pefilmRating", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "content-details.content-rating.djctq-rating-reasons" => Some(("contentDetails.contentRating.djctqRatingReasons", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), "content-details.content-rating.incaa-rating" => Some(("contentDetails.contentRating.incaaRating", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "content-details.content-rating.cnc-rating" => Some(("contentDetails.contentRating.cncRating", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "content-details.content-rating.oflc-rating" => Some(("contentDetails.contentRating.oflcRating", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "content-details.content-rating.fpb-rating" => Some(("contentDetails.contentRating.fpbRating", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "content-details.content-rating.mccaa-rating" => Some(("contentDetails.contentRating.mccaaRating", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), @@ -4867,7 +4851,7 @@ impl<'n, 'a> Engine<'n, 'a> { "recording-details.location.longitude" => Some(("recordingDetails.location.longitude", JsonTypeInfo { jtype: JsonType::Float, ctype: ComplexType::Pod })), "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), _ => { - let suggestion = FieldCursor::did_you_mean(key, &vec!["acb-rating", "access", "actual-end-time", "actual-start-time", "agcom-rating", "age-gating", "alcohol-content", "allowed", "altitude", "anatel-rating", "bbfc-rating", "bfvc-rating", "bitrate-bps", "blocked", "bmukk-rating", "caption", "category-id", "catv-rating", "catvfr-rating", "cbfc-rating", "ccc-rating", "cce-rating", "channel-id", "channel-title", "chfilm-rating", "chvrs-rating", "cicf-rating", "cna-rating", "comment-count", "concurrent-viewers", "container", "content-details", "content-rating", "country-restriction", "creation-time", "csa-rating", "cscf-rating", "czfilm-rating", "default", "default-audio-language", "default-language", "definition", "description", "dimension", "dislike-count", "djctq-rating", "djctq-rating-reasons", "duration", "duration-ms", "editor-suggestions", "editor-suggestions-availability", "eefilm-rating", "egfilm-rating", "eirin-rating", "embed-html", "embeddable", "etag", "exception", "failure-reason", "favorite-count", "fcbm-rating", "fco-rating", "file-details", "file-details-availability", "file-name", "file-size", "file-type", "fmoc-rating", "fpb-rating", "fsk-rating", "grfilm-rating", "height", "high", "icaa-rating", "id", "ifco-rating", "ilfilm-rating", "incaa-rating", "kfcb-rating", "kijkwijzer-rating", "kind", "kmrb-rating", "latitude", "license", "licensed-content", "like-count", "live-broadcast-content", "live-streaming-details", "localized", "location", "location-description", "longitude", "lsf-rating", "maxres", "mccaa-rating", "mccyp-rating", "mda-rating", "medietilsynet-rating", "medium", "meku-rating", "mibac-rating", "moc-rating", "moctw-rating", "monetization-details", "mpaa-rating", "mtrcb-rating", "nbc-rating", "nbcpl-rating", "nfrc-rating", "nfvcb-rating", "nkclv-rating", "oflc-rating", "parts-processed", "parts-total", "pefilm-rating", "player", "privacy-status", "processing-details", "processing-errors", "processing-failure-reason", "processing-hints", "processing-issues-availability", "processing-progress", "processing-status", "processing-warnings", "project-details", "public-stats-viewable", "publish-at", "published-at", "rcnof-rating", "recording-date", "recording-details", "recording-location", "region-restriction", "rejection-reason", "relevant-topic-ids", "resorteviolencia-rating", "restricted", "rtc-rating", "rte-rating", "russia-rating", "scheduled-end-time", "scheduled-start-time", "skfilm-rating", "smais-rating", "smsa-rating", "snippet", "standard", "statistics", "status", "suggestions", "tag-suggestions-availability", "tags", "thumbnails", "thumbnails-availability", "time-left-ms", "title", "topic-details", "topic-ids", "tvpg-rating", "upload-status", "url", "video-game-rating", "view-count", "width", "yt-rating"]); + let suggestion = FieldCursor::did_you_mean(key, &vec!["acb-rating", "access", "actual-end-time", "actual-start-time", "agcom-rating", "age-gating", "alcohol-content", "allowed", "altitude", "anatel-rating", "bbfc-rating", "bfvc-rating", "bitrate-bps", "blocked", "bmukk-rating", "caption", "category-id", "catv-rating", "catvfr-rating", "cbfc-rating", "ccc-rating", "cce-rating", "channel-id", "channel-title", "chfilm-rating", "chvrs-rating", "cicf-rating", "cna-rating", "cnc-rating", "comment-count", "concurrent-viewers", "container", "content-details", "content-rating", "country-restriction", "creation-time", "csa-rating", "cscf-rating", "czfilm-rating", "default", "default-audio-language", "default-language", "definition", "description", "dimension", "dislike-count", "djctq-rating", "djctq-rating-reasons", "duration", "duration-ms", "editor-suggestions", "editor-suggestions-availability", "eefilm-rating", "egfilm-rating", "eirin-rating", "embed-html", "embeddable", "etag", "exception", "failure-reason", "favorite-count", "fcbm-rating", "fco-rating", "file-details", "file-details-availability", "file-name", "file-size", "file-type", "fmoc-rating", "fpb-rating", "fsk-rating", "grfilm-rating", "height", "high", "icaa-rating", "id", "ifco-rating", "ilfilm-rating", "incaa-rating", "kfcb-rating", "kijkwijzer-rating", "kind", "kmrb-rating", "latitude", "license", "licensed-content", "like-count", "live-broadcast-content", "live-streaming-details", "localized", "location", "location-description", "longitude", "lsf-rating", "maxres", "mccaa-rating", "mccyp-rating", "mda-rating", "medietilsynet-rating", "medium", "meku-rating", "mibac-rating", "moc-rating", "moctw-rating", "monetization-details", "mpaa-rating", "mtrcb-rating", "nbc-rating", "nbcpl-rating", "nfrc-rating", "nfvcb-rating", "nkclv-rating", "oflc-rating", "parts-processed", "parts-total", "pefilm-rating", "player", "privacy-status", "processing-details", "processing-errors", "processing-failure-reason", "processing-hints", "processing-issues-availability", "processing-progress", "processing-status", "processing-warnings", "project-details", "public-stats-viewable", "publish-at", "published-at", "rcnof-rating", "recording-date", "recording-details", "recording-location", "region-restriction", "rejection-reason", "relevant-topic-ids", "resorteviolencia-rating", "restricted", "rtc-rating", "rte-rating", "russia-rating", "scheduled-end-time", "scheduled-start-time", "skfilm-rating", "smais-rating", "smsa-rating", "snippet", "standard", "statistics", "status", "suggestions", "tag-suggestions-availability", "tags", "thumbnails", "thumbnails-availability", "time-left-ms", "title", "topic-details", "topic-ids", "tvpg-rating", "upload-status", "url", "video-game-rating", "view-count", "width", "yt-rating"]); err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); None } @@ -4980,9 +4964,6 @@ impl<'n, 'a> Engine<'n, 'a> { "hl" => { call = call.hl(value.unwrap_or("")); }, - "debug-project-id-override" => { - call = call.debug_project_id_override(value.unwrap_or("")); - }, "chart" => { call = call.chart(value.unwrap_or("")); }, @@ -4999,7 +4980,7 @@ impl<'n, 'a> Engine<'n, 'a> { err.issues.push(CLIError::UnknownParameter(key.to_string(), {let mut v = Vec::new(); v.extend(self.gp.iter().map(|v|*v)); - v.extend(["on-behalf-of-content-owner", "region-code", "page-token", "locale", "chart", "max-results", "video-category-id", "debug-project-id-override", "hl", "my-rating", "id"].iter().map(|v|*v)); + v.extend(["on-behalf-of-content-owner", "region-code", "page-token", "locale", "chart", "max-results", "video-category-id", "hl", "my-rating", "id"].iter().map(|v|*v)); v } )); } } @@ -5221,6 +5202,7 @@ impl<'n, 'a> Engine<'n, 'a> { "content-details.content-rating.pefilm-rating" => Some(("contentDetails.contentRating.pefilmRating", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "content-details.content-rating.djctq-rating-reasons" => Some(("contentDetails.contentRating.djctqRatingReasons", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Vec })), "content-details.content-rating.incaa-rating" => Some(("contentDetails.contentRating.incaaRating", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "content-details.content-rating.cnc-rating" => Some(("contentDetails.contentRating.cncRating", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "content-details.content-rating.oflc-rating" => Some(("contentDetails.contentRating.oflcRating", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "content-details.content-rating.fpb-rating" => Some(("contentDetails.contentRating.fpbRating", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), "content-details.content-rating.mccaa-rating" => Some(("contentDetails.contentRating.mccaaRating", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), @@ -5345,7 +5327,7 @@ impl<'n, 'a> Engine<'n, 'a> { "recording-details.location.longitude" => Some(("recordingDetails.location.longitude", JsonTypeInfo { jtype: JsonType::Float, ctype: ComplexType::Pod })), "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), _ => { - let suggestion = FieldCursor::did_you_mean(key, &vec!["acb-rating", "access", "actual-end-time", "actual-start-time", "agcom-rating", "age-gating", "alcohol-content", "allowed", "altitude", "anatel-rating", "bbfc-rating", "bfvc-rating", "bitrate-bps", "blocked", "bmukk-rating", "caption", "category-id", "catv-rating", "catvfr-rating", "cbfc-rating", "ccc-rating", "cce-rating", "channel-id", "channel-title", "chfilm-rating", "chvrs-rating", "cicf-rating", "cna-rating", "comment-count", "concurrent-viewers", "container", "content-details", "content-rating", "country-restriction", "creation-time", "csa-rating", "cscf-rating", "czfilm-rating", "default", "default-audio-language", "default-language", "definition", "description", "dimension", "dislike-count", "djctq-rating", "djctq-rating-reasons", "duration", "duration-ms", "editor-suggestions", "editor-suggestions-availability", "eefilm-rating", "egfilm-rating", "eirin-rating", "embed-html", "embeddable", "etag", "exception", "failure-reason", "favorite-count", "fcbm-rating", "fco-rating", "file-details", "file-details-availability", "file-name", "file-size", "file-type", "fmoc-rating", "fpb-rating", "fsk-rating", "grfilm-rating", "height", "high", "icaa-rating", "id", "ifco-rating", "ilfilm-rating", "incaa-rating", "kfcb-rating", "kijkwijzer-rating", "kind", "kmrb-rating", "latitude", "license", "licensed-content", "like-count", "live-broadcast-content", "live-streaming-details", "localized", "location", "location-description", "longitude", "lsf-rating", "maxres", "mccaa-rating", "mccyp-rating", "mda-rating", "medietilsynet-rating", "medium", "meku-rating", "mibac-rating", "moc-rating", "moctw-rating", "monetization-details", "mpaa-rating", "mtrcb-rating", "nbc-rating", "nbcpl-rating", "nfrc-rating", "nfvcb-rating", "nkclv-rating", "oflc-rating", "parts-processed", "parts-total", "pefilm-rating", "player", "privacy-status", "processing-details", "processing-errors", "processing-failure-reason", "processing-hints", "processing-issues-availability", "processing-progress", "processing-status", "processing-warnings", "project-details", "public-stats-viewable", "publish-at", "published-at", "rcnof-rating", "recording-date", "recording-details", "recording-location", "region-restriction", "rejection-reason", "relevant-topic-ids", "resorteviolencia-rating", "restricted", "rtc-rating", "rte-rating", "russia-rating", "scheduled-end-time", "scheduled-start-time", "skfilm-rating", "smais-rating", "smsa-rating", "snippet", "standard", "statistics", "status", "suggestions", "tag-suggestions-availability", "tags", "thumbnails", "thumbnails-availability", "time-left-ms", "title", "topic-details", "topic-ids", "tvpg-rating", "upload-status", "url", "video-game-rating", "view-count", "width", "yt-rating"]); + let suggestion = FieldCursor::did_you_mean(key, &vec!["acb-rating", "access", "actual-end-time", "actual-start-time", "agcom-rating", "age-gating", "alcohol-content", "allowed", "altitude", "anatel-rating", "bbfc-rating", "bfvc-rating", "bitrate-bps", "blocked", "bmukk-rating", "caption", "category-id", "catv-rating", "catvfr-rating", "cbfc-rating", "ccc-rating", "cce-rating", "channel-id", "channel-title", "chfilm-rating", "chvrs-rating", "cicf-rating", "cna-rating", "cnc-rating", "comment-count", "concurrent-viewers", "container", "content-details", "content-rating", "country-restriction", "creation-time", "csa-rating", "cscf-rating", "czfilm-rating", "default", "default-audio-language", "default-language", "definition", "description", "dimension", "dislike-count", "djctq-rating", "djctq-rating-reasons", "duration", "duration-ms", "editor-suggestions", "editor-suggestions-availability", "eefilm-rating", "egfilm-rating", "eirin-rating", "embed-html", "embeddable", "etag", "exception", "failure-reason", "favorite-count", "fcbm-rating", "fco-rating", "file-details", "file-details-availability", "file-name", "file-size", "file-type", "fmoc-rating", "fpb-rating", "fsk-rating", "grfilm-rating", "height", "high", "icaa-rating", "id", "ifco-rating", "ilfilm-rating", "incaa-rating", "kfcb-rating", "kijkwijzer-rating", "kind", "kmrb-rating", "latitude", "license", "licensed-content", "like-count", "live-broadcast-content", "live-streaming-details", "localized", "location", "location-description", "longitude", "lsf-rating", "maxres", "mccaa-rating", "mccyp-rating", "mda-rating", "medietilsynet-rating", "medium", "meku-rating", "mibac-rating", "moc-rating", "moctw-rating", "monetization-details", "mpaa-rating", "mtrcb-rating", "nbc-rating", "nbcpl-rating", "nfrc-rating", "nfvcb-rating", "nkclv-rating", "oflc-rating", "parts-processed", "parts-total", "pefilm-rating", "player", "privacy-status", "processing-details", "processing-errors", "processing-failure-reason", "processing-hints", "processing-issues-availability", "processing-progress", "processing-status", "processing-warnings", "project-details", "public-stats-viewable", "publish-at", "published-at", "rcnof-rating", "recording-date", "recording-details", "recording-location", "region-restriction", "rejection-reason", "relevant-topic-ids", "resorteviolencia-rating", "restricted", "rtc-rating", "rte-rating", "russia-rating", "scheduled-end-time", "scheduled-start-time", "skfilm-rating", "smais-rating", "smsa-rating", "snippet", "standard", "statistics", "status", "suggestions", "tag-suggestions-availability", "tags", "thumbnails", "thumbnails-availability", "time-left-ms", "title", "topic-details", "topic-ids", "tvpg-rating", "upload-status", "url", "video-game-rating", "view-count", "width", "yt-rating"]); err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); None } @@ -7456,7 +7438,7 @@ fn main() { let mut app = App::new("youtube3") .author("Sebastian Thiel ") - .version("0.3.2+20150706") + .version("0.3.2+20151012") .about("Programmatic access to YouTube features.") .after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_youtube3_cli") .arg(Arg::with_name("url") diff --git a/gen/youtube3/README.md b/gen/youtube3/README.md index 058ed7abcf..e544a23b2e 100644 --- a/gen/youtube3/README.md +++ b/gen/youtube3/README.md @@ -5,7 +5,7 @@ DO NOT EDIT ! --> The `google-youtube3` library allows access to all features of the *Google YouTube* service. -This documentation was generated from *YouTube* crate version *0.1.9+20150706*, where *20150706* is the exact revision of the *youtube:v3* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +This documentation was generated from *YouTube* crate version *0.1.9+20151012*, where *20151012* is the exact revision of the *youtube:v3* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. Everything else about the *YouTube* *v3* API can be found at the [official documentation site](https://developers.google.com/youtube/v3). diff --git a/gen/youtube3/cargo.toml b/gen/youtube3/cargo.toml index 263f7454e5..6f7fa81b28 100644 --- a/gen/youtube3/cargo.toml +++ b/gen/youtube3/cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-youtube3" -version = "0.1.9+20150706" +version = "0.1.9+20151012" authors = ["Sebastian Thiel "] description = "A complete library to interact with YouTube (protocol v3)" repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/youtube3" diff --git a/gen/youtube3/src/lib.rs b/gen/youtube3/src/lib.rs index 0a63dc0922..84f8bf0dda 100644 --- a/gen/youtube3/src/lib.rs +++ b/gen/youtube3/src/lib.rs @@ -2,7 +2,7 @@ // This file was generated automatically from 'src/mako/api/lib.rs.mako' // DO NOT EDIT ! -//! This documentation was generated from *YouTube* crate version *0.1.9+20150706*, where *20150706* is the exact revision of the *youtube:v3* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +//! This documentation was generated from *YouTube* crate version *0.1.9+20151012*, where *20151012* is the exact revision of the *youtube:v3* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. //! //! Everything else about the *YouTube* *v3* API can be found at the //! [official documentation site](https://developers.google.com/youtube/v3). @@ -158,13 +158,13 @@ //! // execute the final call using `doit()`. //! // Values shown here are possibly random and not representative ! //! let result = hub.live_broadcasts().list("part") -//! .page_token("erat") -//! .on_behalf_of_content_owner_channel("amet.") -//! .on_behalf_of_content_owner("dolores") +//! .page_token("Lorem") +//! .on_behalf_of_content_owner_channel("dolor") +//! .on_behalf_of_content_owner("vero") //! .mine(false) -//! .max_results(78) -//! .id("sed") -//! .broadcast_status("et") +//! .max_results(93) +//! .id("dolores") +//! .broadcast_status("consetetur") //! .doit(); //! //! match result { diff --git a/gen/youtube3/src/lib.rs.in b/gen/youtube3/src/lib.rs.in index 03111e6b07..4e4b3d225c 100644 --- a/gen/youtube3/src/lib.rs.in +++ b/gen/youtube3/src/lib.rs.in @@ -1235,7 +1235,7 @@ impl Part for GuideCategorySnippet {} pub struct VideoSnippet { /// The video's description. pub description: Option, - /// A list of keyword tags associated with the video. Tags may contain spaces. This field is only visible to the video's uploader. + /// A list of keyword tags associated with the video. Tags may contain spaces. pub tags: Option>, /// The default_audio_language property specifies the language spoken in the video's default audio track. #[serde(rename="defaultAudioLanguage")] @@ -2033,202 +2033,205 @@ pub struct LiveStreamStatus { impl Part for LiveStreamStatus {} -/// Ratings schemes. The country-specific ratings are mostly for movies and shows. NEXT_ID: 65 +/// Ratings schemes. The country-specific ratings are mostly for movies and shows. NEXT_ID: 66 /// /// This type is not used in any activity, and only used as *part* of another schema. /// #[derive(Default, Clone, Debug, Serialize, Deserialize)] pub struct ContentRating { - /// Internal YouTube rating. + /// A rating that YouTube uses to identify age-restricted content. #[serde(rename="ytRating")] pub yt_rating: Option, - /// Rating system for French Canadian TV - Regie du cinema + /// The video's rating from the Canadian Radio-Television and Telecommunications Commission (CRTC) for Canadian French-language broadcasts. For more information, see the Canadian Broadcast Standards Council website. #[serde(rename="catvfrRating")] pub catvfr_rating: Option, - /// Rating system in India - Central Board of Film Certification + /// The video's Central Board of Film Certification (CBFC - India) rating. #[serde(rename="cbfcRating")] pub cbfc_rating: Option, - /// Rating system for Thailand - Board of Filmand Video Censors + /// The video's rating from Thailand's Board of Film and Video Censors. #[serde(rename="bfvcRating")] pub bfvc_rating: Option, - /// Rating system for Austria - Bundesministerium f�r Unterricht, Kunst und Kultur + /// The video's rating from the Austrian Board of Media Classification (Bundesministerium für Unterricht, Kunst und Kultur). #[serde(rename="bmukkRating")] pub bmukk_rating: Option, - /// Rating system for Switzerland - Switzerland Rating System + /// The video's rating in Switzerland. #[serde(rename="chfilmRating")] pub chfilm_rating: Option, - /// Rating system for Taiwan - Ministry of Culture - Tawan + /// The video's rating from Taiwan's Ministry of Culture (文化部). #[serde(rename="moctwRating")] pub moctw_rating: Option, - /// Rating system for Canadian TV - Canadian TV Classification System + /// Rating system for Canadian TV - Canadian TV Classification System The video's rating from the Canadian Radio-Television and Telecommunications Commission (CRTC) for Canadian English-language broadcasts. For more information, see the Canadian Broadcast Standards Council website. #[serde(rename="catvRating")] pub catv_rating: Option, - /// Rating system for Peru - Peru Rating System + /// The video's rating in Peru. #[serde(rename="pefilmRating")] pub pefilm_rating: Option, - /// no description provided + /// Reasons that explain why the video received its DJCQT (Brazil) rating. #[serde(rename="djctqRatingReasons")] pub djctq_rating_reasons: Option>, - /// Rating system for Argentina - Instituto Nacional de Cine y Artes Audiovisuales + /// The video's INCAA (Instituto Nacional de Cine y Artes Audiovisuales - Argentina) rating. #[serde(rename="incaaRating")] pub incaa_rating: Option, - /// Rating system for Israel - Israel Rating System + /// The video's rating in Israel. #[serde(rename="ilfilmRating")] pub ilfilm_rating: Option, - /// Rating system for Luxembourg - Commission de surveillance de la classification des films + /// The video's rating from Luxembourg's Commission de surveillance de la classification des films (CSCF). #[serde(rename="cscfRating")] pub cscf_rating: Option, - /// Rating system in Germany - Voluntary Self Regulation of the Movie Industry + /// The video's Freiwillige Selbstkontrolle der Filmwirtschaft (FSK - Germany) rating. #[serde(rename="fskRating")] pub fsk_rating: Option, - /// Rating system in South Korea - Korea Media Rating Board + /// The video's Korea Media Rating Board (영상물등급위원회) rating. The KMRB rates videos in South Korea. #[serde(rename="kmrbRating")] pub kmrb_rating: Option, - /// Rating system in Brazil - Department of Justice, Rating, Titles and Qualification + /// The video's Departamento de Justiça, Classificação, Qualificação e Títulos (DJCQT - Brazil) rating. #[serde(rename="djctqRating")] pub djctq_rating: Option, - /// Rating system for Hong kong - Office for Film, Newspaper and Article Administration + /// The video's rating from Hong Kong's Office for Film, Newspaper and Article Administration. #[serde(rename="fcoRating")] pub fco_rating: Option, - /// Rating system for Norway - Medietilsynet + /// The video's rating from Medietilsynet, the Norwegian Media Authority. #[serde(rename="medietilsynetRating")] pub medietilsynet_rating: Option, - /// Rating system for Greece - Greece Rating System + /// The video's rating in Greece. #[serde(rename="grfilmRating")] pub grfilm_rating: Option, - /// Rating system for Chile - Consejo de Calificaci�n Cinematogr�fica + /// The video's Consejo de Calificación Cinematográfica (Chile) rating. #[serde(rename="cccRating")] pub ccc_rating: Option, - /// Rating system for Ireland - Raidi� Teilif�s �ireann + /// The video's rating from Ireland's Raidió Teilifís Éireann. #[serde(rename="rteRating")] pub rte_rating: Option, - /// Rating system in France - French Minister of Culture + /// This property has been deprecated. Use the contentDetails.contentRating.cncRating instead. #[serde(rename="fmocRating")] pub fmoc_rating: Option, - /// Rating system in Japan - Eiga Rinri Kanri Iinkai + /// The video's Eirin (映倫) rating. Eirin is the Japanese rating system. #[serde(rename="eirinRating")] pub eirin_rating: Option, - /// Rating system for Portugal - Comiss�o de Classifica��o de Espect�culos + /// The video's rating from Portugal's Comissão de Classificação de Espect´culos. #[serde(rename="cceRating")] pub cce_rating: Option, - /// Rating system for Latvia - National Film Center of Latvia + /// The video's rating from the Nacionãlais Kino centrs (National Film Centre of Latvia). #[serde(rename="nkclvRating")] pub nkclv_rating: Option, - /// Rating system for South africa - Film & Publication Board + /// The video's rating from South Africa's Film and Publication Board. #[serde(rename="fpbRating")] pub fpb_rating: Option, - /// Rating system for Iceland - SMAIS + /// The video's rating in Iceland. #[serde(rename="smaisRating")] pub smais_rating: Option, - /// Canadian Home Video Rating System + /// The video's Canadian Home Video Rating System (CHVRS) rating. #[serde(rename="chvrsRating")] pub chvrs_rating: Option, - /// Rating system for Italy - Autorit� per le Garanzie nelle Comunicazioni + /// The video's rating from Italy's Autorità per le Garanzie nelle Comunicazioni (AGCOM). #[serde(rename="agcomRating")] pub agcom_rating: Option, - /// Rating system for Colombia - MoC + /// The video's Ministerio de Cultura (Colombia) rating. #[serde(rename="mocRating")] pub moc_rating: Option, - /// Rating system for Hungary - Rating Committee of the National Office of Film + /// The video's rating from the Hungarian Nemzeti Filmiroda, the Rating Committee of the National Office of Film. #[serde(rename="rcnofRating")] pub rcnof_rating: Option, - /// Rating system for Malaysia - Film Censorship Board of Malaysia + /// The video's rating from Malaysia's Film Censorship Board. #[serde(rename="fcbmRating")] pub fcbm_rating: Option, - /// Rating system for Netherlands - Nederlands Instituut voor de Classificatie van Audiovisuele Media + /// voor de Classificatie van Audiovisuele Media (Netherlands). #[serde(rename="kijkwijzerRating")] pub kijkwijzer_rating: Option, - /// Rating system for Singapore - Media Development Authority + /// Rating system in France - Commission de classification cinematographique + #[serde(rename="cncRating")] + pub cnc_rating: Option, + /// The video's rating from Singapore's Media Development Authority (MDA) and, specifically, it's Board of Film Censors (BFC). #[serde(rename="mdaRating")] pub mda_rating: Option, - /// Rating system for Nigeria - National Film and Video Censors Board + /// The video's rating from Nigeria's National Film and Video Censors Board. #[serde(rename="nfvcbRating")] pub nfvcb_rating: Option, - /// Rating system for Venezuela - SiBCI + /// The video's rating in Venezuela. #[serde(rename="resorteviolenciaRating")] pub resorteviolencia_rating: Option, - /// Rating system for France - Conseil sup�rieur de l?audiovisuel + /// The video's rating from France's Conseil supérieur de l?audiovisuel, which rates broadcast content. #[serde(rename="csaRating")] pub csa_rating: Option, - /// Rating system in New Zealand - Office of Film and Literature Classification + /// The video's Office of Film and Literature Classification (OFLC - New Zealand) rating. #[serde(rename="oflcRating")] pub oflc_rating: Option, - /// TV Parental Guidelines rating of the content. + /// The video's TV Parental Guidelines (TVPG) rating. #[serde(rename="tvpgRating")] pub tvpg_rating: Option, - /// Rating system for Bulgaria - National Film Centre + /// The video's rating from the Bulgarian National Film Center. #[serde(rename="nfrcRating")] pub nfrc_rating: Option, - /// Rating system for Malta - Film Age-Classification Board + /// The video's rating from Malta's Film Age-Classification Board. #[serde(rename="mccaaRating")] pub mccaa_rating: Option, - /// Rating system in Mexico - General Directorate of Radio, Television and Cinematography + /// The video's General Directorate of Radio, Television and Cinematography (Mexico) rating. #[serde(rename="rtcRating")] pub rtc_rating: Option, - /// Rating system in Italy - Ministero dei Beni e delle Attivita Culturali e del Turismo + /// The video's rating from the Ministero dei Beni e delle Attività Culturali e del Turismo (Italy). #[serde(rename="mibacRating")] pub mibac_rating: Option, - /// British Board of Film Classification + /// The video's British Board of Film Classification (BBFC) rating. #[serde(rename="bbfcRating")] pub bbfc_rating: Option, - /// Rating system for Egypt - Egypt Rating System + /// The video's rating in Egypt. #[serde(rename="egfilmRating")] pub egfilm_rating: Option, - /// Rating system for Belgium - Belgium Rating System + /// The video's rating from the Commission de Contrôle des Films (Belgium). #[serde(rename="cicfRating")] pub cicf_rating: Option, - /// Rating system for Poland - National Broadcasting Council + /// The video's rating in Poland. #[serde(rename="nbcplRating")] pub nbcpl_rating: Option, - /// Rating system for Maldives - National Bureau of Classification + /// The video's rating from the Maldives National Bureau of Classification. #[serde(rename="nbcRating")] pub nbc_rating: Option, - /// Motion Picture Association of America rating for the content. + /// The video's Motion Picture Association of America (MPAA) rating. #[serde(rename="mpaaRating")] pub mpaa_rating: Option, - /// Rating system in Ireland - Irish Film Classification Office + /// The video's Irish Film Classification Office (IFCO - Ireland) rating. See the IFCO website for more information. #[serde(rename="ifcoRating")] pub ifco_rating: Option, - /// Rating system in Australia - Australian Classification Board + /// The video's Australian Classification Board (ACB) or Australian Communications and Media Authority (ACMA) rating. ACMA ratings are used to classify children's television programming. #[serde(rename="acbRating")] pub acb_rating: Option, - /// Rating system for Estonia - Estonia Rating System + /// The video's rating in Estonia. #[serde(rename="eefilmRating")] pub eefilm_rating: Option, - /// Rating system for Czech republic - Czech republic Rating System + /// The video's rating in the Czech Republic. #[serde(rename="czfilmRating")] pub czfilm_rating: Option, - /// Rating system for Indonesia - Lembaga Sensor Film + /// The video's rating from Indonesia's Lembaga Sensor Film. #[serde(rename="lsfRating")] pub lsf_rating: Option, - /// Rating system in Russia + /// The video's National Film Registry of the Russian Federation (MKRF - Russia) rating. #[serde(rename="russiaRating")] pub russia_rating: Option, - /// Rating system for Kenya - Kenya Film Classification Board + /// The video's rating from the Kenya Film Classification Board. #[serde(rename="kfcbRating")] pub kfcb_rating: Option, - /// Rating system for Philippines - MOVIE AND TELEVISION REVIEW AND CLASSIFICATION BOARD + /// The video's rating from the Movie and Television Review and Classification Board (Philippines). #[serde(rename="mtrcbRating")] pub mtrcb_rating: Option, - /// Rating system for Chile - Asociaci�n Nacional de Televisi�n + /// The video's Anatel (Asociación Nacional de Televisión) rating for Chilean television. #[serde(rename="anatelRating")] pub anatel_rating: Option, - /// Rating system for Sweden - Statens medier�d (National Media Council) + /// The video's rating from Statens medieråd (Sweden's National Media Council). #[serde(rename="smsaRating")] pub smsa_rating: Option, - /// Rating system for Romania - CONSILIUL NATIONAL AL AUDIOVIZUALULUI - CNA + /// The video's rating from Romania's CONSILIUL NATIONAL AL AUDIOVIZUALULUI (CNA). #[serde(rename="cnaRating")] pub cna_rating: Option, - /// Rating system in Spain - Instituto de Cinematografia y de las Artes Audiovisuales + /// The video's Instituto de la Cinematografía y de las Artes Audiovisuales (ICAA - Spain) rating. #[serde(rename="icaaRating")] pub icaa_rating: Option, - /// Rating system for Denmark - The Media Council for Children and Young People + /// The video's rating from the Danish Film Institute's (Det Danske Filminstitut) Media Council for Children and Young People. #[serde(rename="mccypRating")] pub mccyp_rating: Option, - /// Rating system for Slovakia - Slovakia Rating System + /// The video's rating in Slovakia. #[serde(rename="skfilmRating")] pub skfilm_rating: Option, - /// Rating system for Finland - Finnish Centre for Media Education and Audiovisual Media + /// The video's rating from Finland's Kansallinen Audiovisuaalinen Instituutti (National Audiovisual Institute). #[serde(rename="mekuRating")] pub meku_rating: Option, } @@ -3617,7 +3620,7 @@ pub struct Video { pub monetization_details: Option, /// The suggestions object encapsulates suggestions that identify opportunities to improve the video quality or the metadata for the uploaded video. This data can only be retrieved by the video owner. pub suggestions: Option, - /// Age restriction details related to a video. + /// Age restriction details related to a video. This data can only be retrieved by the video owner. #[serde(rename="ageGating")] pub age_gating: Option, /// The fileDetails object encapsulates information about the video file that was uploaded to YouTube, including the file's resolution, duration, audio and video codecs, stream bitrates, and more. This data can only be retrieved by the video owner. @@ -4530,6 +4533,9 @@ pub struct LiveBroadcastSnippet { /// The date and time that the broadcast was added to YouTube's live broadcast schedule. The value is specified in ISO 8601 (YYYY-MM-DDThh:mm:ss.sZ) format. #[serde(rename="publishedAt")] pub published_at: Option, + /// The id of the live chat for this broadcast. + #[serde(rename="liveChatId")] + pub live_chat_id: Option, /// The date and time that the broadcast is scheduled to start. The value is specified in ISO 8601 (YYYY-MM-DDThh:mm:ss.sZ) format. #[serde(rename="scheduledStartTime")] pub scheduled_start_time: Option, @@ -5379,7 +5385,6 @@ impl<'a, C, A> VideoMethods<'a, C, A> { _locale: Default::default(), _id: Default::default(), _hl: Default::default(), - _debug_project_id_override: Default::default(), _chart: Default::default(), _delegate: Default::default(), _scopes: Default::default(), @@ -5838,7 +5843,6 @@ impl<'a, C, A> CommentThreadMethods<'a, C, A> { hub: self.hub, _request: request, _part: parts, - _share_on_google_plus: Default::default(), _delegate: Default::default(), _scopes: Default::default(), _additional_params: Default::default(), @@ -6747,7 +6751,6 @@ impl<'a, C, A> CaptionMethods<'a, C, A> { _sync: Default::default(), _on_behalf_of_content_owner: Default::default(), _on_behalf_of: Default::default(), - _debug_project_id_override: Default::default(), _delegate: Default::default(), _scopes: Default::default(), _additional_params: Default::default(), @@ -6770,7 +6773,6 @@ impl<'a, C, A> CaptionMethods<'a, C, A> { _on_behalf_of_content_owner: Default::default(), _on_behalf_of: Default::default(), _id: Default::default(), - _debug_project_id_override: Default::default(), _delegate: Default::default(), _scopes: Default::default(), _additional_params: Default::default(), @@ -6792,7 +6794,6 @@ impl<'a, C, A> CaptionMethods<'a, C, A> { _tfmt: Default::default(), _on_behalf_of_content_owner: Default::default(), _on_behalf_of: Default::default(), - _debug_project_id_override: Default::default(), _delegate: Default::default(), _scopes: Default::default(), _additional_params: Default::default(), @@ -6812,7 +6813,6 @@ impl<'a, C, A> CaptionMethods<'a, C, A> { _id: id.to_string(), _on_behalf_of_content_owner: Default::default(), _on_behalf_of: Default::default(), - _debug_project_id_override: Default::default(), _delegate: Default::default(), _scopes: Default::default(), _additional_params: Default::default(), @@ -6835,7 +6835,6 @@ impl<'a, C, A> CaptionMethods<'a, C, A> { _sync: Default::default(), _on_behalf_of_content_owner: Default::default(), _on_behalf_of: Default::default(), - _debug_project_id_override: Default::default(), _delegate: Default::default(), _scopes: Default::default(), _additional_params: Default::default(), @@ -7507,10 +7506,10 @@ impl<'a, C, A> ChannelBannerInsertCall<'a, C, A> where C: BorrowMut ThumbnailSetCall<'a, C, A> where C: BorrowMut, A: self.doit(stream, mime_type, "simple") } /// Upload media in a resumable fashion. - /// Even if the upload fails or is interrupted, it can be resumed for a + /// Even if the upload fails or is interrupted, it can be resumed for a /// certain amount of time as the server maintains state temporarily. /// - /// The delegate will be asked for an `upload_url()`, and if not provided, will be asked to store an upload URL + /// The delegate will be asked for an `upload_url()`, and if not provided, will be asked to store an upload URL /// that was provided by the server, using `store_upload_url(...)`. The upload will be done in chunks, the delegate /// may specify the `chunk_size()` and may cancel the operation before each chunk is uploaded, using /// `cancel_chunk_upload(...)`. @@ -10668,7 +10667,6 @@ impl<'a, C, A> VideoReportAbuseCall<'a, C, A> where C: BorrowMut, /// .locale("ut") /// .id("ea") /// .hl("sed") -/// .debug_project_id_override("dolor") /// .chart("dolor") /// .doit(); /// # } @@ -10687,7 +10685,6 @@ pub struct VideoListCall<'a, C, A> _locale: Option, _id: Option, _hl: Option, - _debug_project_id_override: Option, _chart: Option, _delegate: Option<&'a mut Delegate>, _additional_params: HashMap, @@ -10710,7 +10707,7 @@ impl<'a, C, A> VideoListCall<'a, C, A> where C: BorrowMut, A: oau }; dlg.begin(MethodInfo { id: "youtube.videos.list", http_method: hyper::method::Method::Get }); - let mut params: Vec<(&str, String)> = Vec::with_capacity((14 + self._additional_params.len())); + let mut params: Vec<(&str, String)> = Vec::with_capacity((13 + self._additional_params.len())); params.push(("part", self._part.to_string())); if let Some(value) = self._video_category_id { params.push(("videoCategoryId", value.to_string())); @@ -10739,13 +10736,10 @@ impl<'a, C, A> VideoListCall<'a, C, A> where C: BorrowMut, A: oau if let Some(value) = self._hl { params.push(("hl", value.to_string())); } - if let Some(value) = self._debug_project_id_override { - params.push(("debugProjectIdOverride", value.to_string())); - } if let Some(value) = self._chart { params.push(("chart", value.to_string())); } - for &field in ["alt", "part", "videoCategoryId", "regionCode", "pageToken", "onBehalfOfContentOwner", "myRating", "maxResults", "locale", "id", "hl", "debugProjectIdOverride", "chart"].iter() { + for &field in ["alt", "part", "videoCategoryId", "regionCode", "pageToken", "onBehalfOfContentOwner", "myRating", "maxResults", "locale", "id", "hl", "chart"].iter() { if self._additional_params.contains_key(field) { dlg.finished(false); return Err(Error::FieldClash(field)); @@ -10923,13 +10917,6 @@ impl<'a, C, A> VideoListCall<'a, C, A> where C: BorrowMut, A: oau self._hl = Some(new_value.to_string()); self } - /// The debugProjectIdOverride parameter should be used for mimicking a request for a certain project ID - /// - /// Sets the *debug project id override* query property to the given value. - pub fn debug_project_id_override(mut self, new_value: &str) -> VideoListCall<'a, C, A> { - self._debug_project_id_override = Some(new_value.to_string()); - self - } /// The chart parameter identifies the chart that you want to retrieve. /// /// Sets the *chart* query property to the given value. @@ -11232,7 +11219,7 @@ impl<'a, C, A> VideoRateCall<'a, C, A> where C: BorrowMut, A: oau /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.videos().get_rating("id") -/// .on_behalf_of_content_owner("amet.") +/// .on_behalf_of_content_owner("consetetur") /// .doit(); /// # } /// ``` @@ -11461,7 +11448,7 @@ impl<'a, C, A> VideoGetRatingCall<'a, C, A> where C: BorrowMut, A /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.videos().delete("id") -/// .on_behalf_of_content_owner("Lorem") +/// .on_behalf_of_content_owner("voluptua.") /// .doit(); /// # } /// ``` @@ -11685,7 +11672,7 @@ impl<'a, C, A> VideoDeleteCall<'a, C, A> where C: BorrowMut, A: o /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.videos().update(req) -/// .on_behalf_of_content_owner("gubergren") +/// .on_behalf_of_content_owner("Lorem") /// .doit(); /// # } /// ``` @@ -11957,10 +11944,10 @@ impl<'a, C, A> VideoUpdateCall<'a, C, A> where C: BorrowMut, A: o /// // Values shown here are possibly random and not representative ! /// let result = hub.videos().insert(req) /// .stabilize(true) -/// .on_behalf_of_content_owner_channel("sit") -/// .on_behalf_of_content_owner("vero") +/// .on_behalf_of_content_owner_channel("justo") +/// .on_behalf_of_content_owner("sit") /// .notify_subscribers(true) -/// .auto_levels(false) +/// .auto_levels(true) /// .upload_resumable(fs::File::open("file.ext").unwrap(), "application/octet-stream".parse().unwrap()); /// # } /// ``` @@ -12223,10 +12210,10 @@ impl<'a, C, A> VideoInsertCall<'a, C, A> where C: BorrowMut, A: o self.doit(stream, mime_type, "simple") } /// Upload media in a resumable fashion. - /// Even if the upload fails or is interrupted, it can be resumed for a + /// Even if the upload fails or is interrupted, it can be resumed for a /// certain amount of time as the server maintains state temporarily. /// - /// The delegate will be asked for an `upload_url()`, and if not provided, will be asked to store an upload URL + /// The delegate will be asked for an `upload_url()`, and if not provided, will be asked to store an upload URL /// that was provided by the server, using `store_upload_url(...)`. The upload will be done in chunks, the delegate /// may specify the `chunk_size()` and may cancel the operation before each chunk is uploaded, using /// `cancel_chunk_upload(...)`. @@ -12635,16 +12622,16 @@ impl<'a, C, A> SubscriptionInsertCall<'a, C, A> where C: BorrowMut SubscriptionDeleteCall<'a, C, A> where C: BorrowMut SearchListCall<'a, C, A> where C: BorrowMut, A: oa /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.i18n_regions().list("part") -/// .hl("diam") +/// .hl("sit") /// .doit(); /// # } /// ``` @@ -13998,16 +13985,16 @@ impl<'a, C, A> I18nRegionListCall<'a, C, A> where C: BorrowMut, A /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.comment_threads().list("part") -/// .video_id("justo") -/// .text_format("est") -/// .search_terms("amet") -/// .page_token("accusam") -/// .order("clita") -/// .moderation_status("diam") -/// .max_results(30) -/// .id("est") -/// .channel_id("clita") -/// .all_threads_related_to_channel_id("invidunt") +/// .video_id("ut") +/// .text_format("justo") +/// .search_terms("est") +/// .page_token("amet") +/// .order("accusam") +/// .moderation_status("clita") +/// .max_results(22) +/// .id("justo") +/// .channel_id("est") +/// .all_threads_related_to_channel_id("clita") /// .doit(); /// # } /// ``` @@ -14601,7 +14588,6 @@ impl<'a, C, A> CommentThreadUpdateCall<'a, C, A> where C: BorrowMut hub: &'a YouTube, _request: CommentThread, _part: String, - _share_on_google_plus: Option, _delegate: Option<&'a mut Delegate>, _additional_params: HashMap, _scopes: BTreeMap @@ -14633,15 +14618,12 @@ impl<'a, C, A> CommentThreadInsertCall<'a, C, A> where C: BorrowMut = Vec::with_capacity((5 + self._additional_params.len())); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); if self._part.len() == 0 { self._part = self._request.to_parts(); } params.push(("part", self._part.to_string())); - if let Some(value) = self._share_on_google_plus { - params.push(("shareOnGooglePlus", value.to_string())); - } - for &field in ["alt", "part", "shareOnGooglePlus"].iter() { + for &field in ["alt", "part"].iter() { if self._additional_params.contains_key(field) { dlg.finished(false); return Err(Error::FieldClash(field)); @@ -14773,13 +14755,6 @@ impl<'a, C, A> CommentThreadInsertCall<'a, C, A> where C: BorrowMut CommentThreadInsertCall<'a, C, A> { - self._share_on_google_plus = Some(new_value); - self - } /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong /// while executing the actual API request. /// @@ -14879,14 +14854,14 @@ impl<'a, C, A> CommentThreadInsertCall<'a, C, A> where C: BorrowMut LiveStreamUpdateCall<'a, C, A> where C: BorrowMut, /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.live_streams().delete("id") -/// .on_behalf_of_content_owner_channel("sed") -/// .on_behalf_of_content_owner("aliquyam") +/// .on_behalf_of_content_owner_channel("voluptua.") +/// .on_behalf_of_content_owner("duo") /// .doit(); /// # } /// ``` @@ -15430,12 +15405,12 @@ impl<'a, C, A> LiveStreamDeleteCall<'a, C, A> where C: BorrowMut, /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.live_streams().list("part") -/// .page_token("ea") -/// .on_behalf_of_content_owner_channel("et") -/// .on_behalf_of_content_owner("dolor") -/// .mine(true) -/// .max_results(39) -/// .id("invidunt") +/// .page_token("aliquyam") +/// .on_behalf_of_content_owner_channel("ea") +/// .on_behalf_of_content_owner("ea") +/// .mine(false) +/// .max_results(53) +/// .id("diam") /// .doit(); /// # } /// ``` @@ -15750,14 +15725,14 @@ impl<'a, C, A> LiveStreamListCall<'a, C, A> where C: BorrowMut, A /// req.status = Default::default(); // is LiveStreamStatus /// req.snippet = Default::default(); // is LiveStreamSnippet /// req.cdn = Default::default(); // is CdnSettings -/// req.id = Some("rebum.".to_string()); +/// req.id = Some("kasd".to_string()); /// /// // You can configure optional parameters by calling the respective setters at will, and /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.live_streams().insert(req) -/// .on_behalf_of_content_owner_channel("Lorem") -/// .on_behalf_of_content_owner("clita") +/// .on_behalf_of_content_owner_channel("invidunt") +/// .on_behalf_of_content_owner("rebum.") /// .doit(); /// # } /// ``` @@ -16300,7 +16275,7 @@ impl<'a, C, A> CommentInsertCall<'a, C, A> where C: BorrowMut, A: /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.comments().set_moderation_status("id", "moderationStatus") -/// .ban_author(false) +/// .ban_author(true) /// .doit(); /// # } /// ``` @@ -16734,11 +16709,11 @@ impl<'a, C, A> CommentDeleteCall<'a, C, A> where C: BorrowMut, A: /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.comments().list("part") -/// .text_format("sed") -/// .parent_id("sit") -/// .page_token("takimata") -/// .max_results(58) -/// .id("nonumy") +/// .text_format("consetetur") +/// .parent_id("et") +/// .page_token("sed") +/// .max_results(54) +/// .id("takimata") /// .doit(); /// # } /// ``` @@ -17477,7 +17452,7 @@ impl<'a, C, A> CommentMarkAsSpamCall<'a, C, A> where C: BorrowMut /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.channels().update(req) -/// .on_behalf_of_content_owner("Lorem") +/// .on_behalf_of_content_owner("nonumy") /// .doit(); /// # } /// ``` @@ -17739,16 +17714,16 @@ impl<'a, C, A> ChannelUpdateCall<'a, C, A> where C: BorrowMut, A: /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.channels().list("part") -/// .page_token("diam") -/// .on_behalf_of_content_owner("ut") +/// .page_token("Lorem") +/// .on_behalf_of_content_owner("Lorem") /// .my_subscribers(true) -/// .mine(false) -/// .max_results(1) +/// .mine(true) +/// .max_results(64) /// .managed_by_me(false) -/// .id("dolor") -/// .hl("sea") -/// .for_username("ut") -/// .category_id("eirmod") +/// .id("ipsum") +/// .hl("ut") +/// .for_username("dolor") +/// .category_id("sea") /// .doit(); /// # } /// ``` @@ -18095,7 +18070,7 @@ impl<'a, C, A> ChannelListCall<'a, C, A> where C: BorrowMut, A: o /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.video_abuse_report_reasons().list("part") -/// .hl("voluptua.") +/// .hl("eirmod") /// .doit(); /// # } /// ``` @@ -18333,7 +18308,7 @@ impl<'a, C, A> VideoAbuseReportReasonListCall<'a, C, A> where C: BorrowMut PlaylistItemDeleteCall<'a, C, A> where C: BorrowMut PlaylistItemUpdateCall<'a, C, A> where C: BorrowMut WatermarkSetCall<'a, C, A> where C: BorrowMut, A: self.doit(stream, mime_type, "simple") } /// Upload media in a resumable fashion. - /// Even if the upload fails or is interrupted, it can be resumed for a + /// Even if the upload fails or is interrupted, it can be resumed for a /// certain amount of time as the server maintains state temporarily. /// - /// The delegate will be asked for an `upload_url()`, and if not provided, will be asked to store an upload URL + /// The delegate will be asked for an `upload_url()`, and if not provided, will be asked to store an upload URL /// that was provided by the server, using `store_upload_url(...)`. The upload will be done in chunks, the delegate /// may specify the `chunk_size()` and may cancel the operation before each chunk is uploaded, using /// `cancel_chunk_upload(...)`. @@ -19705,7 +19680,7 @@ impl<'a, C, A> WatermarkSetCall<'a, C, A> where C: BorrowMut, A: /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.watermarks().unset("channelId") -/// .on_behalf_of_content_owner("takimata") +/// .on_behalf_of_content_owner("vero") /// .doit(); /// # } /// ``` @@ -19940,9 +19915,9 @@ impl<'a, C, A> WatermarkUnsetCall<'a, C, A> where C: BorrowMut, A /// // Values shown here are possibly random and not representative ! /// let result = hub.live_broadcasts().control("id", "part") /// .walltime("et") -/// .on_behalf_of_content_owner_channel("sed") -/// .on_behalf_of_content_owner("no") -/// .offset_time_ms("invidunt") +/// .on_behalf_of_content_owner_channel("nonumy") +/// .on_behalf_of_content_owner("et") +/// .offset_time_ms("sed") /// .display_slate(true) /// .doit(); /// # } @@ -20259,9 +20234,9 @@ impl<'a, C, A> LiveBroadcastControlCall<'a, C, A> where C: BorrowMut LiveBroadcastBindDirectCall<'a, C, A> where C: BorrowMut LiveBroadcastUpdateCall<'a, C, A> where C: BorrowMut LiveBroadcastInsertCall<'a, C, A> where C: BorrowMut LiveBroadcastListCall<'a, C, A> where C: BorrowMut /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.live_broadcasts().delete("id") -/// .on_behalf_of_content_owner_channel("dolor") -/// .on_behalf_of_content_owner("sanctus") +/// .on_behalf_of_content_owner_channel("Stet") +/// .on_behalf_of_content_owner("sed") /// .doit(); /// # } /// ``` @@ -21752,8 +21727,8 @@ impl<'a, C, A> LiveBroadcastDeleteCall<'a, C, A> where C: BorrowMut LiveBroadcastTransitionCall<'a, C, A> where C: BorrowMut LiveBroadcastBindCall<'a, C, A> where C: BorrowMut /// // Values shown here are possibly random and not representative ! /// let result = hub.captions().insert(req) /// .sync(true) -/// .on_behalf_of_content_owner("Lorem") -/// .on_behalf_of("rebum.") -/// .debug_project_id_override("et") +/// .on_behalf_of_content_owner("accusam") +/// .on_behalf_of("magna") /// .upload_resumable(fs::File::open("file.ext").unwrap(), "application/octet-stream".parse().unwrap()); /// # } /// ``` @@ -22343,7 +22317,6 @@ pub struct CaptionInsertCall<'a, C, A> _sync: Option, _on_behalf_of_content_owner: Option, _on_behalf_of: Option, - _debug_project_id_override: Option, _delegate: Option<&'a mut Delegate>, _additional_params: HashMap, _scopes: BTreeMap @@ -22366,7 +22339,7 @@ impl<'a, C, A> CaptionInsertCall<'a, C, A> where C: BorrowMut, A: }; dlg.begin(MethodInfo { id: "youtube.captions.insert", http_method: hyper::method::Method::Post }); - let mut params: Vec<(&str, String)> = Vec::with_capacity((8 + self._additional_params.len())); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); if self._part.len() == 0 { self._part = self._request.to_parts(); } @@ -22380,10 +22353,7 @@ impl<'a, C, A> CaptionInsertCall<'a, C, A> where C: BorrowMut, A: if let Some(value) = self._on_behalf_of { params.push(("onBehalfOf", value.to_string())); } - if let Some(value) = self._debug_project_id_override { - params.push(("debugProjectIdOverride", value.to_string())); - } - for &field in ["alt", "part", "sync", "onBehalfOfContentOwner", "onBehalfOf", "debugProjectIdOverride"].iter() { + for &field in ["alt", "part", "sync", "onBehalfOfContentOwner", "onBehalfOf"].iter() { if self._additional_params.contains_key(field) { dlg.finished(false); return Err(Error::FieldClash(field)); @@ -22589,10 +22559,10 @@ impl<'a, C, A> CaptionInsertCall<'a, C, A> where C: BorrowMut, A: self.doit(stream, mime_type, "simple") } /// Upload media in a resumable fashion. - /// Even if the upload fails or is interrupted, it can be resumed for a + /// Even if the upload fails or is interrupted, it can be resumed for a /// certain amount of time as the server maintains state temporarily. /// - /// The delegate will be asked for an `upload_url()`, and if not provided, will be asked to store an upload URL + /// The delegate will be asked for an `upload_url()`, and if not provided, will be asked to store an upload URL /// that was provided by the server, using `store_upload_url(...)`. The upload will be done in chunks, the delegate /// may specify the `chunk_size()` and may cancel the operation before each chunk is uploaded, using /// `cancel_chunk_upload(...)`. @@ -22652,13 +22622,6 @@ impl<'a, C, A> CaptionInsertCall<'a, C, A> where C: BorrowMut, A: self._on_behalf_of = Some(new_value.to_string()); self } - /// The debugProjectIdOverride parameter should be used for mimicking a request for a certain project ID. - /// - /// Sets the *debug project id override* query property to the given value. - pub fn debug_project_id_override(mut self, new_value: &str) -> CaptionInsertCall<'a, C, A> { - self._debug_project_id_override = Some(new_value.to_string()); - self - } /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong /// while executing the actual API request. /// @@ -22752,10 +22715,9 @@ impl<'a, C, A> CaptionInsertCall<'a, C, A> where C: BorrowMut, A: /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.captions().list("part", "videoId") -/// .on_behalf_of_content_owner("dolores") -/// .on_behalf_of("vero") -/// .id("consetetur") -/// .debug_project_id_override("vero") +/// .on_behalf_of_content_owner("et") +/// .on_behalf_of("clita") +/// .id("eos") /// .doit(); /// # } /// ``` @@ -22768,7 +22730,6 @@ pub struct CaptionListCall<'a, C, A> _on_behalf_of_content_owner: Option, _on_behalf_of: Option, _id: Option, - _debug_project_id_override: Option, _delegate: Option<&'a mut Delegate>, _additional_params: HashMap, _scopes: BTreeMap @@ -22790,7 +22751,7 @@ impl<'a, C, A> CaptionListCall<'a, C, A> where C: BorrowMut, A: o }; dlg.begin(MethodInfo { id: "youtube.captions.list", http_method: hyper::method::Method::Get }); - let mut params: Vec<(&str, String)> = Vec::with_capacity((8 + self._additional_params.len())); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); params.push(("part", self._part.to_string())); params.push(("videoId", self._video_id.to_string())); if let Some(value) = self._on_behalf_of_content_owner { @@ -22802,10 +22763,7 @@ impl<'a, C, A> CaptionListCall<'a, C, A> where C: BorrowMut, A: o if let Some(value) = self._id { params.push(("id", value.to_string())); } - if let Some(value) = self._debug_project_id_override { - params.push(("debugProjectIdOverride", value.to_string())); - } - for &field in ["alt", "part", "videoId", "onBehalfOfContentOwner", "onBehalfOf", "id", "debugProjectIdOverride"].iter() { + for &field in ["alt", "part", "videoId", "onBehalfOfContentOwner", "onBehalfOf", "id"].iter() { if self._additional_params.contains_key(field) { dlg.finished(false); return Err(Error::FieldClash(field)); @@ -22948,13 +22906,6 @@ impl<'a, C, A> CaptionListCall<'a, C, A> where C: BorrowMut, A: o self._id = Some(new_value.to_string()); self } - /// The debugProjectIdOverride parameter should be used for mimicking a request for a certain project ID. - /// - /// Sets the *debug project id override* query property to the given value. - pub fn debug_project_id_override(mut self, new_value: &str) -> CaptionListCall<'a, C, A> { - self._debug_project_id_override = Some(new_value.to_string()); - self - } /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong /// while executing the actual API request. /// @@ -23037,11 +22988,10 @@ impl<'a, C, A> CaptionListCall<'a, C, A> where C: BorrowMut, A: o /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.captions().download("id") -/// .tlang("eos") -/// .tfmt("justo") -/// .on_behalf_of_content_owner("tempor") -/// .on_behalf_of("gubergren") -/// .debug_project_id_override("dolore") +/// .tlang("vero") +/// .tfmt("consetetur") +/// .on_behalf_of_content_owner("vero") +/// .on_behalf_of("consetetur") /// .doit(); /// # } /// ``` @@ -23054,7 +23004,6 @@ pub struct CaptionDownloadCall<'a, C, A> _tfmt: Option, _on_behalf_of_content_owner: Option, _on_behalf_of: Option, - _debug_project_id_override: Option, _delegate: Option<&'a mut Delegate>, _additional_params: HashMap, _scopes: BTreeMap @@ -23076,7 +23025,7 @@ impl<'a, C, A> CaptionDownloadCall<'a, C, A> where C: BorrowMut, }; dlg.begin(MethodInfo { id: "youtube.captions.download", http_method: hyper::method::Method::Get }); - let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); params.push(("id", self._id.to_string())); if let Some(value) = self._tlang { params.push(("tlang", value.to_string())); @@ -23090,10 +23039,7 @@ impl<'a, C, A> CaptionDownloadCall<'a, C, A> where C: BorrowMut, if let Some(value) = self._on_behalf_of { params.push(("onBehalfOf", value.to_string())); } - if let Some(value) = self._debug_project_id_override { - params.push(("debugProjectIdOverride", value.to_string())); - } - for &field in ["id", "tlang", "tfmt", "onBehalfOfContentOwner", "onBehalfOf", "debugProjectIdOverride"].iter() { + for &field in ["id", "tlang", "tfmt", "onBehalfOfContentOwner", "onBehalfOf"].iter() { if self._additional_params.contains_key(field) { dlg.finished(false); return Err(Error::FieldClash(field)); @@ -23238,13 +23184,6 @@ impl<'a, C, A> CaptionDownloadCall<'a, C, A> where C: BorrowMut, self._on_behalf_of = Some(new_value.to_string()); self } - /// The debugProjectIdOverride parameter should be used for mimicking a request for a certain project ID - /// - /// Sets the *debug project id override* query property to the given value. - pub fn debug_project_id_override(mut self, new_value: &str) -> CaptionDownloadCall<'a, C, A> { - self._debug_project_id_override = Some(new_value.to_string()); - self - } /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong /// while executing the actual API request. /// @@ -23324,9 +23263,8 @@ impl<'a, C, A> CaptionDownloadCall<'a, C, A> where C: BorrowMut, /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.captions().delete("id") -/// .on_behalf_of_content_owner("dolore") -/// .on_behalf_of("magna") -/// .debug_project_id_override("elitr") +/// .on_behalf_of_content_owner("justo") +/// .on_behalf_of("tempor") /// .doit(); /// # } /// ``` @@ -23337,7 +23275,6 @@ pub struct CaptionDeleteCall<'a, C, A> _id: String, _on_behalf_of_content_owner: Option, _on_behalf_of: Option, - _debug_project_id_override: Option, _delegate: Option<&'a mut Delegate>, _additional_params: HashMap, _scopes: BTreeMap @@ -23359,7 +23296,7 @@ impl<'a, C, A> CaptionDeleteCall<'a, C, A> where C: BorrowMut, A: }; dlg.begin(MethodInfo { id: "youtube.captions.delete", http_method: hyper::method::Method::Delete }); - let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); params.push(("id", self._id.to_string())); if let Some(value) = self._on_behalf_of_content_owner { params.push(("onBehalfOfContentOwner", value.to_string())); @@ -23367,10 +23304,7 @@ impl<'a, C, A> CaptionDeleteCall<'a, C, A> where C: BorrowMut, A: if let Some(value) = self._on_behalf_of { params.push(("onBehalfOf", value.to_string())); } - if let Some(value) = self._debug_project_id_override { - params.push(("debugProjectIdOverride", value.to_string())); - } - for &field in ["id", "onBehalfOfContentOwner", "onBehalfOf", "debugProjectIdOverride"].iter() { + for &field in ["id", "onBehalfOfContentOwner", "onBehalfOf"].iter() { if self._additional_params.contains_key(field) { dlg.finished(false); return Err(Error::FieldClash(field)); @@ -23480,13 +23414,6 @@ impl<'a, C, A> CaptionDeleteCall<'a, C, A> where C: BorrowMut, A: self._on_behalf_of = Some(new_value.to_string()); self } - /// The debugProjectIdOverride parameter should be used for mimicking a request for a certain project ID - /// - /// Sets the *debug project id override* query property to the given value. - pub fn debug_project_id_override(mut self, new_value: &str) -> CaptionDeleteCall<'a, C, A> { - self._debug_project_id_override = Some(new_value.to_string()); - self - } /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong /// while executing the actual API request. /// @@ -23574,9 +23501,8 @@ impl<'a, C, A> CaptionDeleteCall<'a, C, A> where C: BorrowMut, A: /// // Values shown here are possibly random and not representative ! /// let result = hub.captions().update(req) /// .sync(false) -/// .on_behalf_of_content_owner("ipsum") -/// .on_behalf_of("invidunt") -/// .debug_project_id_override("accusam") +/// .on_behalf_of_content_owner("dolore") +/// .on_behalf_of("amet.") /// .upload_resumable(fs::File::open("file.ext").unwrap(), "application/octet-stream".parse().unwrap()); /// # } /// ``` @@ -23589,7 +23515,6 @@ pub struct CaptionUpdateCall<'a, C, A> _sync: Option, _on_behalf_of_content_owner: Option, _on_behalf_of: Option, - _debug_project_id_override: Option, _delegate: Option<&'a mut Delegate>, _additional_params: HashMap, _scopes: BTreeMap @@ -23612,7 +23537,7 @@ impl<'a, C, A> CaptionUpdateCall<'a, C, A> where C: BorrowMut, A: }; dlg.begin(MethodInfo { id: "youtube.captions.update", http_method: hyper::method::Method::Put }); - let mut params: Vec<(&str, String)> = Vec::with_capacity((8 + self._additional_params.len())); + let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len())); if self._part.len() == 0 { self._part = self._request.to_parts(); } @@ -23626,10 +23551,7 @@ impl<'a, C, A> CaptionUpdateCall<'a, C, A> where C: BorrowMut, A: if let Some(value) = self._on_behalf_of { params.push(("onBehalfOf", value.to_string())); } - if let Some(value) = self._debug_project_id_override { - params.push(("debugProjectIdOverride", value.to_string())); - } - for &field in ["alt", "part", "sync", "onBehalfOfContentOwner", "onBehalfOf", "debugProjectIdOverride"].iter() { + for &field in ["alt", "part", "sync", "onBehalfOfContentOwner", "onBehalfOf"].iter() { if self._additional_params.contains_key(field) { dlg.finished(false); return Err(Error::FieldClash(field)); @@ -23835,10 +23757,10 @@ impl<'a, C, A> CaptionUpdateCall<'a, C, A> where C: BorrowMut, A: self.doit(stream, mime_type, "simple") } /// Upload media in a resumable fashion. - /// Even if the upload fails or is interrupted, it can be resumed for a + /// Even if the upload fails or is interrupted, it can be resumed for a /// certain amount of time as the server maintains state temporarily. /// - /// The delegate will be asked for an `upload_url()`, and if not provided, will be asked to store an upload URL + /// The delegate will be asked for an `upload_url()`, and if not provided, will be asked to store an upload URL /// that was provided by the server, using `store_upload_url(...)`. The upload will be done in chunks, the delegate /// may specify the `chunk_size()` and may cancel the operation before each chunk is uploaded, using /// `cancel_chunk_upload(...)`. @@ -23898,13 +23820,6 @@ impl<'a, C, A> CaptionUpdateCall<'a, C, A> where C: BorrowMut, A: self._on_behalf_of = Some(new_value.to_string()); self } - /// The debugProjectIdOverride parameter should be used for mimicking a request for a certain project ID. - /// - /// Sets the *debug project id override* query property to the given value. - pub fn debug_project_id_override(mut self, new_value: &str) -> CaptionUpdateCall<'a, C, A> { - self._debug_project_id_override = Some(new_value.to_string()); - self - } /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong /// while executing the actual API request. /// @@ -23984,9 +23899,9 @@ impl<'a, C, A> CaptionUpdateCall<'a, C, A> where C: BorrowMut, A: /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.video_categories().list("part") -/// .region_code("diam") -/// .id("nonumy") -/// .hl("sed") +/// .region_code("magna") +/// .id("elitr") +/// .hl("magna") /// .doit(); /// # } /// ``` @@ -24235,14 +24150,14 @@ impl<'a, C, A> VideoCategoryListCall<'a, C, A> where C: BorrowMut /// // execute the final call using `doit()`. /// // Values shown here are possibly random and not representative ! /// let result = hub.activities().list("part") -/// .region_code("magna") -/// .published_before("dolor") -/// .published_after("Lorem") -/// .page_token("dolor") +/// .region_code("invidunt") +/// .published_before("accusam") +/// .published_after("labore") +/// .page_token("diam") /// .mine(true) -/// .max_results(10) -/// .home(true) -/// .channel_id("dolores") +/// .max_results(8) +/// .home(false) +/// .channel_id("magna") /// .doit(); /// # } /// ``` diff --git a/gen/youtubeanalytics1-cli/Cargo.toml b/gen/youtubeanalytics1-cli/Cargo.toml index 4d2c2fbe8d..0b7ef18ef3 100644 --- a/gen/youtubeanalytics1-cli/Cargo.toml +++ b/gen/youtubeanalytics1-cli/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-youtubeanalytics1-cli" -version = "0.3.2+20150304" +version = "0.3.2+20150921" authors = ["Sebastian Thiel "] description = "A complete library to interact with YouTube Analytics (protocol v1)" repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/youtubeanalytics1-cli" diff --git a/gen/youtubeanalytics1-cli/README.md b/gen/youtubeanalytics1-cli/README.md index 257539de1c..7a1536983e 100644 --- a/gen/youtubeanalytics1-cli/README.md +++ b/gen/youtubeanalytics1-cli/README.md @@ -24,7 +24,7 @@ Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/ma # Usage -This documentation was generated from the *YouTube Analytics* API at revision *20150304*. The CLI is at version *0.3.2*. +This documentation was generated from the *YouTube Analytics* API at revision *20150921*. The CLI is at version *0.3.2*. ```bash youtubeanalytics1 [options] diff --git a/gen/youtubeanalytics1-cli/mkdocs.yml b/gen/youtubeanalytics1-cli/mkdocs.yml index d79970b6f3..fa02971397 100644 --- a/gen/youtubeanalytics1-cli/mkdocs.yml +++ b/gen/youtubeanalytics1-cli/mkdocs.yml @@ -1,4 +1,4 @@ -site_name: YouTube Analytics v0.3.2+20150304 +site_name: YouTube Analytics v0.3.2+20150921 site_url: http://byron.github.io/google-apis-rs/google-youtubeanalytics1-cli site_description: Write integrating applications with bcore diff --git a/gen/youtubeanalytics1-cli/src/main.rs b/gen/youtubeanalytics1-cli/src/main.rs index 0472dc16ff..ae9e9bc4ef 100644 --- a/gen/youtubeanalytics1-cli/src/main.rs +++ b/gen/youtubeanalytics1-cli/src/main.rs @@ -1122,7 +1122,7 @@ fn main() { let mut app = App::new("youtubeanalytics1") .author("Sebastian Thiel ") - .version("0.3.2+20150304") + .version("0.3.2+20150921") .about("Retrieve your YouTube Analytics reports.") .after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_youtubeanalytics1_cli") .arg(Arg::with_name("url") diff --git a/gen/youtubeanalytics1/Cargo.toml b/gen/youtubeanalytics1/Cargo.toml index 2f79b99880..b643450fa3 100644 --- a/gen/youtubeanalytics1/Cargo.toml +++ b/gen/youtubeanalytics1/Cargo.toml @@ -4,7 +4,7 @@ [package] name = "google-youtubeanalytics1" -version = "0.1.9+20150304" +version = "0.1.9+20150921" authors = ["Sebastian Thiel "] description = "A complete library to interact with YouTube Analytics (protocol v1)" repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/youtubeanalytics1" diff --git a/gen/youtubeanalytics1/README.md b/gen/youtubeanalytics1/README.md index e719250f96..0e0a2a9318 100644 --- a/gen/youtubeanalytics1/README.md +++ b/gen/youtubeanalytics1/README.md @@ -5,7 +5,7 @@ DO NOT EDIT ! --> The `google-youtubeanalytics1` library allows access to all features of the *Google YouTube Analytics* service. -This documentation was generated from *YouTube Analytics* crate version *0.1.9+20150304*, where *20150304* is the exact revision of the *youtubeAnalytics:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +This documentation was generated from *YouTube Analytics* crate version *0.1.9+20150921*, where *20150921* is the exact revision of the *youtubeAnalytics:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. Everything else about the *YouTube Analytics* *v1* API can be found at the [official documentation site](http://developers.google.com/youtube/analytics/). diff --git a/gen/youtubeanalytics1/src/lib.rs b/gen/youtubeanalytics1/src/lib.rs index 2a3ccaa620..d5a8c5dc1e 100644 --- a/gen/youtubeanalytics1/src/lib.rs +++ b/gen/youtubeanalytics1/src/lib.rs @@ -2,7 +2,7 @@ // This file was generated automatically from 'src/mako/api/lib.rs.mako' // DO NOT EDIT ! -//! This documentation was generated from *YouTube Analytics* crate version *0.1.9+20150304*, where *20150304* is the exact revision of the *youtubeAnalytics:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +//! This documentation was generated from *YouTube Analytics* crate version *0.1.9+20150921*, where *20150921* is the exact revision of the *youtubeAnalytics:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. //! //! Everything else about the *YouTube Analytics* *v1* API can be found at the //! [official documentation site](http://developers.google.com/youtube/analytics/). diff --git a/gen/youtubereporting1-cli/Cargo.toml b/gen/youtubereporting1-cli/Cargo.toml new file mode 100644 index 0000000000..b13c984631 --- /dev/null +++ b/gen/youtubereporting1-cli/Cargo.toml @@ -0,0 +1,35 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-youtubereporting1-cli" +version = "0.3.2+20150923" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with YouTube Reporting (protocol v1)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/youtubereporting1-cli" +homepage = "https://developers.google.com/youtube/reporting/v1/reports/" +documentation = "http://byron.github.io/google-apis-rs/google_youtubereporting1_cli" +license = "MIT" +keywords = ["youtubereporting", "google", "cli"] + +[[bin]] +name = "youtubereporting1" + +[dependencies] +hyper = ">= 0.6.8" +mime = "0.1.0" +serde = ">= 0.6.0" +serde_json = ">= 0.6.0" +yup-oauth2 = "*" +strsim = "*" +yup-hyper-mock = ">=1.0.0" +clap = ">= 1.0.3" + +[build-dependencies] +syntex = { version = "*" } +serde_codegen = { version = "*" } + + +[dependencies.google-youtubereporting1] +path = "../youtubereporting1" diff --git a/gen/youtubereporting1-cli/LICENSE.md b/gen/youtubereporting1-cli/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/youtubereporting1-cli/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/youtubereporting1-cli/README.md b/gen/youtubereporting1-cli/README.md new file mode 100644 index 0000000000..51f45d22b9 --- /dev/null +++ b/gen/youtubereporting1-cli/README.md @@ -0,0 +1,122 @@ + +The `youtubereporting1` command-line interface *(CLI)* allows to use most features of the *Google YouTube Reporting* service from the comfort of your terminal. + +By default all output is printed to standard out, but flags can be set to direct it into a file independent of your shell's +capabilities. Errors will be printed to standard error, and cause the program's exit code to be non-zero. + +If data-structures are requested, these will be returned as pretty-printed JSON, to be useful as input to other tools. + +Everything else about the *YouTube Reporting* API can be found at the +[official documentation site](https://developers.google.com/youtube/reporting/v1/reports/). + +# Downloads + +You can download the pre-compiled 64bit binaries for the following platforms: + +* ![icon](http://megaicons.net/static/img/icons_sizes/6/140/16/ubuntu-icon.png) [ubuntu](http://dl.byronimo.de/google.rs/cli/0.3.2/ubuntu/youtubereporting1.tar.gz) +* ![icon](http://hydra-media.cursecdn.com/wow.gamepedia.com/a/a2/Apple-icon-16x16.png?version=25ddd67ac3dd3b634478e3978b76cb74) [osx](http://dl.byronimo.de/google.rs/cli/0.3.2/osx/youtubereporting1.tar.gz) + +Find the source code [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/youtubereporting1-cli). + +# Usage + +This documentation was generated from the *YouTube Reporting* API at revision *20150923*. The CLI is at version *0.3.2*. + +```bash +youtubereporting1 [options] + jobs + create (-r )... [-p ]... [-o ] + delete [-p ]... [-o ] + get [-p ]... [-o ] + list [-p ]... [-o ] + reports-get [-p ]... [-o ] + reports-list [-p ]... [-o ] + media + download [-p ]... [-o ] + report-types + list [-p ]... [-o ] + youtubereporting1 --help + +Configuration: + [--scope ]... + Specify the authentication a method should be executed in. Each scope + requires the user to grant this application permission to use it. + If unset, it defaults to the shortest scope url for a particular method. + --config-dir + A directory into which we will store our persistent data. Defaults to + a user-writable directory that we will create during the first invocation. + [default: ~/.google-service-cli] + --debug + Output all server communication to standard error. `tx` and `rx` are placed + into the same stream. + --debug-auth + Output all communication related to authentication to standard error. `tx` + and `rx` are placed into the same stream. + +``` + +# Configuration + +The program will store all persistent data in the `~/.google-service-cli` directory in *JSON* files prefixed with `youtubereporting1-`. You can change the directory used to store configuration with the `--config-dir` flag on a per-invocation basis. + +More information about the various kinds of persistent data are given in the following paragraphs. + +# Authentication + +Most APIs require a user to authenticate any request. If this is the case, the [scope][scopes] determines the +set of permissions granted. The granularity of these is usually no more than *read-only* or *full-access*. + +If not set, the system will automatically select the smallest feasible scope, e.g. when invoking a +method that is read-only, it will ask only for a read-only scope. +You may use the `--scope` flag to specify a scope directly. +All applicable scopes are documented in the respective method's CLI documentation. + +The first time a scope is used, the user is asked for permission. Follow the instructions given +by the CLI to grant permissions, or to decline. + +If a scope was authenticated by the user, the respective information will be stored as *JSON* in the configuration +directory, e.g. `~/.google-service-cli/youtubereporting1-token-.json`. No manual management of these tokens +is necessary. + +To revoke granted authentication, please refer to the [official documentation][revoke-access]. + +# Application Secrets + +In order to allow any application to use Google services, it will need to be registered using the +[Google Developer Console][google-dev-console]. APIs the application may use are then enabled for it +one by one. Most APIs can be used for free and have a daily quota. + +To allow more comfortable usage of the CLI without forcing anyone to register an own application, the CLI +comes with a default application secret that is configured accordingly. This also means that heavy usage +all around the world may deplete the daily quota. + +You can workaround this limitation by putting your own secrets file at this location: +`~/.google-service-cli/youtubereporting1-secret.json`, assuming that the required *youtubereporting* API +was enabled for it. Such a secret file can be downloaded in the *Google Developer Console* at +*APIs & auth -> Credentials -> Download JSON* and used as is. + +Learn more about how to setup Google projects and enable APIs using the [official documentation][google-project-new]. + + +# Debugging + +Even though the CLI does its best to provide usable error messages, sometimes it might be desirable to know +what exactly led to a particular issue. This is done by allowing all client-server communication to be +output to standard error *as-is*. + +The `--debug` flag will print all client-server communication to standard error, whereas the `--debug-auth` flag +will cause all communication related to authentication to standard error. +If the `--debug` flag is set, error-results will be debug-printed, possibly yielding more information about the +issue at hand. + +You may consider redirecting standard error into a file for ease of use, e.g. `youtubereporting1 --debug [options] 2>debug.txt`. + + +[scopes]: https://developers.google.com/+/api/oauth#scopes +[revoke-access]: http://webapps.stackexchange.com/a/30849 +[google-dev-console]: https://console.developers.google.com/ +[google-project-new]: https://developers.google.com/console/help/new/ \ No newline at end of file diff --git a/gen/youtubereporting1-cli/mkdocs.yml b/gen/youtubereporting1-cli/mkdocs.yml new file mode 100644 index 0000000000..1b9f62e00d --- /dev/null +++ b/gen/youtubereporting1-cli/mkdocs.yml @@ -0,0 +1,24 @@ +site_name: YouTube Reporting v0.3.2+20150923 +site_url: http://byron.github.io/google-apis-rs/google-youtubereporting1-cli +site_description: Write integrating applications with bcore + +repo_url: https://github.com/Byron/google-apis-rs/tree/master/gen/youtubereporting1-cli + +docs_dir: docs +site_dir: build_html + +pages: +- ['index.md', 'Home'] +- ['jobs_create.md', 'Jobs', 'Create'] +- ['jobs_delete.md', 'Jobs', 'Delete'] +- ['jobs_get.md', 'Jobs', 'Get'] +- ['jobs_list.md', 'Jobs', 'List'] +- ['jobs_reports-get.md', 'Jobs', 'Reports Get'] +- ['jobs_reports-list.md', 'Jobs', 'Reports List'] +- ['media_download.md', 'Media', 'Download'] +- ['report-types_list.md', 'Report Types', 'List'] + +theme: readthedocs + +copyright: Copyright © 2015, `Sebastian Thiel` + diff --git a/gen/youtubereporting1-cli/src/cmn.rs b/gen/youtubereporting1-cli/src/cmn.rs new file mode 100644 index 0000000000..8358f156fa --- /dev/null +++ b/gen/youtubereporting1-cli/src/cmn.rs @@ -0,0 +1,721 @@ +// COPY OF 'src/rust/cli/cmn.rs' +// DO NOT EDIT +use oauth2::{ApplicationSecret, ConsoleApplicationSecret, TokenStorage, Token}; +use serde_json as json; +use serde_json::value::Value; +use mime::Mime; +use clap::{App, SubCommand}; +use strsim; + +use std::fs; +use std::env; +use std::io; +use std::fmt; +use std::path::{Path, PathBuf}; +use std::str::FromStr; +use std::string::ToString; +use std::io::{Write, Read, stdout}; + +use std::default::Default; + +const FIELD_SEP: char = '.'; + + +pub enum ComplexType { + Pod, + Vec, + Map, +} + + // Null, + // Bool(bool), + // I64(i64), + // U64(u64), + // F64(f64), + // String(String), + +pub enum JsonType { + Boolean, + Int, + Uint, + Float, + String, +} + +pub struct JsonTypeInfo { + pub jtype: JsonType, + pub ctype: ComplexType, +} + +// Based on @erickt user comment. Thanks for the idea ! +// Remove all keys whose values are null from given value (changed in place) +pub fn remove_json_null_values(value: &mut Value) { + match *value { + Value::Object(ref mut map) => { + let mut for_removal = Vec::new(); + + for (key, mut value) in map.iter_mut() { + if value.is_null() { + for_removal.push(key.clone()); + } else { + remove_json_null_values(&mut value); + } + } + + for key in &for_removal { + map.remove(key); + } + } + _ => {} + } +} + +fn did_you_mean<'a>(v: &str, possible_values: &[&'a str]) -> Option<&'a str> { + + let mut candidate: Option<(f64, &str)> = None; + for pv in possible_values { + let confidence = strsim::jaro_winkler(v, pv); + if confidence > 0.8 && (candidate.is_none() || (candidate.as_ref().unwrap().0 < confidence)) { + candidate = Some((confidence, pv)); + } + } + match candidate { + None => None, + Some((_, candidate)) => Some(candidate), + } +} + +pub enum CallType { + Upload(UploadProtocol), + Standard, +} + +arg_enum!{ + pub enum UploadProtocol { + Simple, + Resumable + } +} + +impl AsRef for UploadProtocol { + fn as_ref(&self) -> &str { + match *self { + UploadProtocol::Simple => "simple", + UploadProtocol::Resumable => "resumable" + } + } +} + +impl AsRef for CallType { + fn as_ref(&self) -> &str { + match *self { + CallType::Upload(ref proto) => proto.as_ref(), + CallType::Standard => "standard-request" + } + } +} + +#[derive(Clone, Default)] +pub struct FieldCursor(Vec); + +impl ToString for FieldCursor { + fn to_string(&self) -> String { + self.0.join(".") + } +} + +impl From<&'static str> for FieldCursor { + fn from(value: &'static str) -> FieldCursor { + let mut res = FieldCursor::default(); + res.set(value).unwrap(); + res + } +} + +impl FieldCursor { + pub fn set(&mut self, value: &str) -> Result<(), CLIError> { + if value.len() == 0 { + return Err(CLIError::Field(FieldError::Empty)) + } + + let mut first_is_field_sep = false; + let mut char_count: usize = 0; + let mut last_c = FIELD_SEP; + let mut num_conscutive_field_seps = 0; + + let mut field = String::new(); + let mut fields = self.0.clone(); + + let push_field = |fs: &mut Vec, f: &mut String| { + if f.len() > 0 { + fs.push(f.clone()); + f.truncate(0); + } + }; + + for (cid, c) in value.chars().enumerate() { + char_count += 1; + + if c == FIELD_SEP { + if cid == 0 { + first_is_field_sep = true; + } + num_conscutive_field_seps += 1; + if cid > 0 && last_c == FIELD_SEP { + if fields.pop().is_none() { + return Err(CLIError::Field(FieldError::PopOnEmpty(value.to_string()))) + } + } else { + push_field(&mut fields, &mut field); + } + } else { + num_conscutive_field_seps = 0; + if cid == 1 { + if first_is_field_sep { + fields.truncate(0); + } + } + field.push(c); + } + + last_c = c; + } + + push_field(&mut fields, &mut field); + + if char_count == 1 && first_is_field_sep { + fields.truncate(0); + } + if char_count > 1 && num_conscutive_field_seps == 1 { + return Err(CLIError::Field(FieldError::TrailingFieldSep(value.to_string()))) + } + + self.0 = fields; + Ok(()) + } + + pub fn did_you_mean(value: &str, possible_values: &[&str]) -> Option { + if value.len() == 0 { + return None + } + + let mut last_c = FIELD_SEP; + + let mut field = String::new(); + let mut output = String::new(); + + let push_field = |fs: &mut String, f: &mut String| { + if f.len() > 0 { + fs.push_str( + match did_you_mean(&f, possible_values) { + Some(candidate) => candidate, + None => &f, + }); + f.truncate(0); + } + }; + + for (cid, c) in value.chars().enumerate() { + if c == FIELD_SEP { + if last_c != FIELD_SEP { + push_field(&mut output, &mut field); + } + output.push(c); + } else { + field.push(c); + } + + last_c = c; + } + + push_field(&mut output, &mut field); + + if &output == value { + None + } else { + Some(output) + } + } + + pub fn set_json_value(&self, mut object: &mut Value, + value: &str, type_info: JsonTypeInfo, + err: &mut InvalidOptionsError, + orig_cursor: &FieldCursor) { + assert!(self.0.len() > 0); + + for field in &self.0[..self.0.len()-1] { + let tmp = object; + object = + match *tmp { + Value::Object(ref mut mapping) => { + mapping.entry(field.to_owned()).or_insert( + Value::Object(Default::default()) + ) + }, + _ => panic!("We don't expect non-object Values here ...") + }; + } + + match *object { + Value::Object(ref mut mapping) => { + let field = &self.0[self.0.len()-1]; + let to_jval = + |value: &str, jtype: JsonType, err: &mut InvalidOptionsError| + -> Value { + match jtype { + JsonType::Boolean => + Value::Bool(arg_from_str(value, err, &field, "boolean")), + JsonType::Int => + Value::I64(arg_from_str(value, err, &field, "int")), + JsonType::Uint => + Value::U64(arg_from_str(value, err, &field, "uint")), + JsonType::Float => + Value::F64(arg_from_str(value, err, &field, "float")), + JsonType::String => + Value::String(value.to_owned()), + } + }; + + match type_info.ctype { + ComplexType::Pod => { + if mapping.insert(field.to_owned(), to_jval(value, type_info.jtype, err)).is_some() { + err.issues.push(CLIError::Field(FieldError::Duplicate(orig_cursor.to_string()))); + } + }, + ComplexType::Vec => { + match *mapping.entry(field.to_owned()) + .or_insert(Value::Array(Default::default())) { + Value::Array(ref mut values) => values.push(to_jval(value, type_info.jtype, err)), + _ => unreachable!() + } + }, + ComplexType::Map => { + let (key, value) = parse_kv_arg(value, err, true); + let jval = to_jval(value.unwrap_or(""), type_info.jtype, err); + + match *mapping.entry(field.to_owned()) + .or_insert(Value::Object(Default::default())) { + Value::Object(ref mut value_map) => { + if value_map.insert(key.to_owned(), jval).is_some() { + err.issues.push(CLIError::Field(FieldError::Duplicate(orig_cursor.to_string()))); + } + } + _ => unreachable!() + } + } + } + }, + _ => unreachable!() + } + } + + pub fn num_fields(&self) -> usize { + self.0.len() + } +} + +pub fn parse_kv_arg<'a>(kv: &'a str, err: &mut InvalidOptionsError, for_hashmap: bool) + -> (&'a str, Option<&'a str>) { + let mut add_err = || err.issues.push(CLIError::InvalidKeyValueSyntax(kv.to_string(),for_hashmap)); + match kv.find('=') { + None => { + add_err(); + return (kv, None) + }, + Some(pos) => { + let key = &kv[..pos]; + if kv.len() <= pos + 1 { + add_err(); + return (key, Some("")) + } + (key, Some(&kv[pos+1..])) + } + } +} + +pub fn calltype_from_str(name: &str, valid_protocols: Vec, err: &mut InvalidOptionsError) -> CallType { + CallType::Upload( + match UploadProtocol::from_str(name) { + Ok(up) => up, + Err(msg) => { + err.issues.push(CLIError::InvalidUploadProtocol(name.to_string(), valid_protocols)); + UploadProtocol::Simple + } + }) +} + +pub fn input_file_from_opts(file_path: &str, err: &mut InvalidOptionsError) -> Option { + match fs::File::open(file_path) { + Ok(f) => Some(f), + Err(io_err) => { + err.issues.push(CLIError::Input(InputError::IOError((file_path.to_string(), io_err)))); + None + } + } +} + +pub fn input_mime_from_opts(mime: &str, err: &mut InvalidOptionsError) -> Option { + match mime.parse() { + Ok(m) => Some(m), + Err(_) => { + err.issues.push(CLIError::Input(InputError::Mime(mime.to_string()))); + None + } + } +} + +pub fn writer_from_opts(arg: Option<&str>) -> Result, io::Error> { + let f = arg.unwrap_or("-"); + match f { + "-" => Ok(Box::new(stdout())), + _ => match fs::OpenOptions::new().create(true).write(true).open(f) { + Ok(f) => Ok(Box::new(f)), + Err(io_err) => Err(io_err), + } + } +} + + +pub fn arg_from_str<'a, T>(arg: &str, err: &mut InvalidOptionsError, + arg_name: &'a str, + arg_type: &'a str) -> T + where T: FromStr + Default, + ::Err: fmt::Display { + match FromStr::from_str(arg) { + Err(perr) => { + err.issues.push( + CLIError::ParseError(arg_name.to_owned(), arg_type.to_owned(), arg.to_string(), format!("{}", perr)) + ); + Default::default() + }, + Ok(v) => v, + } +} + +pub struct JsonTokenStorage { + pub program_name: &'static str, + pub db_dir: String, +} + +impl JsonTokenStorage { + fn path(&self, scope_hash: u64) -> PathBuf { + Path::new(&self.db_dir).join(&format!("{}-token-{}.json", self.program_name, scope_hash)) + } +} + +impl TokenStorage for JsonTokenStorage { + type Error = json::Error; + + // NOTE: logging might be interesting, currently we swallow all errors + fn set(&mut self, scope_hash: u64, _: &Vec<&str>, token: Option) -> Result<(), json::Error> { + match token { + None => { + match fs::remove_file(self.path(scope_hash)) { + Err(err) => + match err.kind() { + io::ErrorKind::NotFound => Ok(()), + _ => Err(json::Error::IoError(err)) + }, + Ok(_) => Ok(()), + } + } + Some(token) => { + match fs::OpenOptions::new().create(true).write(true).open(&self.path(scope_hash)) { + Ok(mut f) => { + match json::to_writer_pretty(&mut f, &token) { + Ok(_) => Ok(()), + Err(serde_err) => Err(serde_err), + } + }, + Err(io_err) => Err(json::Error::IoError(io_err)) + } + } + } + } + + fn get(&self, scope_hash: u64, _: &Vec<&str>) -> Result, json::Error> { + match fs::File::open(&self.path(scope_hash)) { + Ok(mut f) => { + match json::de::from_reader(f) { + Ok(token) => Ok(Some(token)), + Err(err) => Err(err), + } + }, + Err(io_err) => { + match io_err.kind() { + io::ErrorKind::NotFound => Ok(None), + _ => Err(json::Error::IoError(io_err)) + } + } + } + } +} + + +#[derive(Debug)] +pub enum ApplicationSecretError { + DecoderError((String, json::Error)), + FormatError(String), +} + +impl fmt::Display for ApplicationSecretError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + ApplicationSecretError::DecoderError((ref path, ref err)) + => writeln!(f, "Could not decode file at '{}' with error: {}.", + path, err), + ApplicationSecretError::FormatError(ref path) + => writeln!(f, "'installed' field is unset in secret file at '{}'.", + path), + } + } +} + +#[derive(Debug)] +pub enum ConfigurationError { + DirectoryCreationFailed((String, io::Error)), + DirectoryUnset, + HomeExpansionFailed(String), + Secret(ApplicationSecretError), + IOError((String, io::Error)), +} + +impl fmt::Display for ConfigurationError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + ConfigurationError::DirectoryCreationFailed((ref dir, ref err)) + => writeln!(f, "Directory '{}' could not be created with error: {}.", dir, err), + ConfigurationError::DirectoryUnset + => writeln!(f, "--config-dir was unset or empty."), + ConfigurationError::HomeExpansionFailed(ref dir) + => writeln!(f, "Couldn't find HOME directory of current user, failed to expand '{}'.", dir), + ConfigurationError::Secret(ref err) + => writeln!(f, "Secret -> {}", err), + ConfigurationError::IOError((ref path, ref err)) + => writeln!(f, "IO operation failed on path '{}' with error: {}.", path, err), + } + } +} + +#[derive(Debug)] +pub enum InputError { + IOError((String, io::Error)), + Mime(String), +} + +impl fmt::Display for InputError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + InputError::IOError((ref file_path, ref io_err)) + => writeln!(f, "Failed to open '{}' for reading with error: {}.", file_path, io_err), + InputError::Mime(ref mime) + => writeln!(f, "'{}' is not a known mime-type.", mime), + } + } +} + +#[derive(Debug)] +pub enum FieldError { + PopOnEmpty(String), + TrailingFieldSep(String), + Unknown(String, Option, Option), + Duplicate(String), + Empty, +} + + +impl fmt::Display for FieldError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + FieldError::PopOnEmpty(ref field) + => writeln!(f, "'{}': Cannot move up on empty field cursor.", field), + FieldError::TrailingFieldSep(ref field) + => writeln!(f, "'{}': Single field separator may not be last character.", field), + FieldError::Unknown(ref field, ref suggestion, ref value) => { + let suffix = + match *suggestion { + Some(ref s) => { + let kv = + match *value { + Some(ref v) => format!("{}={}", s, v), + None => s.clone(), + }; + format!(" Did you mean '{}' ?", kv) + }, + None => String::new(), + }; + writeln!(f, "Field '{}' does not exist.{}", field, suffix) + }, + FieldError::Duplicate(ref cursor) + => writeln!(f, "Value at '{}' was already set", cursor), + FieldError::Empty + => writeln!(f, "Field names must not be empty."), + } + } +} + + +#[derive(Debug)] +pub enum CLIError { + Configuration(ConfigurationError), + ParseError(String, String, String, String), + UnknownParameter(String, Vec<&'static str>), + InvalidUploadProtocol(String, Vec), + InvalidKeyValueSyntax(String, bool), + Input(InputError), + Field(FieldError), + MissingCommandError, + MissingMethodError(String), +} + +impl fmt::Display for CLIError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + CLIError::Configuration(ref err) => write!(f, "Configuration -> {}", err), + CLIError::Input(ref err) => write!(f, "Input -> {}", err), + CLIError::Field(ref err) => write!(f, "Field -> {}", err), + CLIError::InvalidUploadProtocol(ref proto_name, ref valid_names) + => writeln!(f, "'{}' is not a valid upload protocol. Choose from one of {}.", proto_name, valid_names.join(", ")), + CLIError::ParseError(ref arg_name, ref type_name, ref value, ref err_desc) + => writeln!(f, "Failed to parse argument '{}' with value '{}' as {} with error: {}.", + arg_name, value, type_name, err_desc), + CLIError::UnknownParameter(ref param_name, ref possible_values) => { + let mut suffix = + match did_you_mean(param_name, &possible_values) { + Some(v) => format!(" Did you mean '{}' ?", v), + None => String::new(), + }; + write!(f, "Parameter '{}' is unknown.{}\n", param_name, suffix) + }, + CLIError::InvalidKeyValueSyntax(ref kv, is_hashmap) => { + let hashmap_info = if is_hashmap { "hashmap " } else { "" }; + writeln!(f, "'{}' does not match {}pattern =.", kv, hashmap_info) + }, + CLIError::MissingCommandError => writeln!(f, "Please specify the main sub-command."), + CLIError::MissingMethodError(ref cmd) => writeln!(f, "Please specify the method to call on the '{}' command.", cmd), + } + } +} + +#[derive(Debug)] +pub struct InvalidOptionsError { + pub issues: Vec, + pub exit_code: i32, +} + +impl fmt::Display for InvalidOptionsError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + for issue in &self.issues { + try!(issue.fmt(f)); + } + Ok(()) + } +} + +impl InvalidOptionsError { + pub fn single(err: CLIError, exit_code: i32) -> InvalidOptionsError { + InvalidOptionsError { + issues: vec![err], + exit_code: exit_code, + } + } + + pub fn new() -> InvalidOptionsError { + InvalidOptionsError { + issues: Vec::new(), + exit_code: 1, + } + } +} + +pub fn assure_config_dir_exists(dir: &str) -> Result { + let trdir = dir.trim(); + if trdir.len() == 0 { + return Err(CLIError::Configuration(ConfigurationError::DirectoryUnset)) + } + + let expanded_config_dir = + if trdir.as_bytes()[0] == b'~' { + match env::var("HOME").ok().or(env::var("UserProfile").ok()) { + None => return Err(CLIError::Configuration(ConfigurationError::HomeExpansionFailed(trdir.to_string()))), + Some(mut user) => { + user.push_str(&trdir[1..]); + user + } + } + } else { + trdir.to_string() + }; + + if let Err(err) = fs::create_dir(&expanded_config_dir) { + if err.kind() != io::ErrorKind::AlreadyExists { + return Err(CLIError::Configuration( + ConfigurationError::DirectoryCreationFailed((expanded_config_dir, err)))) + } + } + + Ok(expanded_config_dir) +} + +pub fn application_secret_from_directory(dir: &str, + secret_basename: &str, + json_console_secret: &str) + -> Result { + let secret_path = Path::new(dir).join(secret_basename); + let secret_str = || secret_path.as_path().to_str().unwrap().to_string(); + let secret_io_error = |io_err: io::Error| { + Err(CLIError::Configuration(ConfigurationError::IOError( + (secret_str(), io_err) + ))) + }; + + for _ in 0..2 { + match fs::File::open(&secret_path) { + Err(mut err) => { + if err.kind() == io::ErrorKind::NotFound { + // Write our built-in one - user may adjust the written file at will + + err = match fs::OpenOptions::new().create(true).write(true).open(&secret_path) { + Err(cfe) => cfe, + Ok(mut f) => { + // Assure we convert 'ugly' json string into pretty one + let console_secret: ConsoleApplicationSecret + = json::from_str(json_console_secret).unwrap(); + match json::to_writer_pretty(&mut f, &console_secret) { + Err(serde_err) => match serde_err { + json::Error::IoError(err) => err, + _ => panic!("Unexpected serde error: {:#?}", serde_err) + }, + Ok(_) => continue, + } + } + }; + // fall through to IO error handling + } + return secret_io_error(err) + }, + Ok(mut f) => { + match json::de::from_reader::<_, ConsoleApplicationSecret>(f) { + Err(json::Error::IoError(err)) => + return secret_io_error(err), + Err(json_err) => + return Err(CLIError::Configuration( + ConfigurationError::Secret( + ApplicationSecretError::DecoderError( + (secret_str(), json_err) + )))), + Ok(console_secret) => + match console_secret.installed { + Some(secret) => return Ok(secret), + None => return Err( + CLIError::Configuration( + ConfigurationError::Secret( + ApplicationSecretError::FormatError(secret_str()) + ))) + }, + } + } + } + } + unreachable!(); +} diff --git a/gen/youtubereporting1-cli/src/main.rs b/gen/youtubereporting1-cli/src/main.rs new file mode 100644 index 0000000000..47387d9d2e --- /dev/null +++ b/gen/youtubereporting1-cli/src/main.rs @@ -0,0 +1,970 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/cli/main.rs.mako' +// DO NOT EDIT ! +#![allow(unused_variables, unused_imports, dead_code, unused_mut)] + +#[macro_use] +extern crate clap; +extern crate yup_oauth2 as oauth2; +extern crate yup_hyper_mock as mock; +extern crate serde; +extern crate serde_json; +extern crate hyper; +extern crate mime; +extern crate strsim; +extern crate google_youtubereporting1 as api; + +use std::env; +use std::io::{self, Write}; +use clap::{App, SubCommand, Arg}; + +mod cmn; + +use cmn::{InvalidOptionsError, CLIError, JsonTokenStorage, arg_from_str, writer_from_opts, parse_kv_arg, + input_file_from_opts, input_mime_from_opts, FieldCursor, FieldError, CallType, UploadProtocol, + calltype_from_str, remove_json_null_values, ComplexType, JsonType, JsonTypeInfo}; + +use std::default::Default; +use std::str::FromStr; + +use oauth2::{Authenticator, DefaultAuthenticatorDelegate}; +use serde_json as json; +use clap::ArgMatches; + +enum DoitError { + IoError(String, io::Error), + ApiError(api::Error), +} + +struct Engine<'n, 'a> { + opt: ArgMatches<'n, 'a>, + hub: api::YouTubeReporting>, + gp: Vec<&'static str>, + gpm: Vec<(&'static str, &'static str)>, +} + + +impl<'n, 'a> Engine<'n, 'a> { + fn _jobs_create(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + + let mut field_cursor = FieldCursor::default(); + let mut object = json::value::Value::Object(Default::default()); + + for kvarg in opt.values_of("kv").unwrap_or(Vec::new()).iter() { + let last_errc = err.issues.len(); + let (key, value) = parse_kv_arg(&*kvarg, err, false); + let mut temp_cursor = field_cursor.clone(); + if let Err(field_err) = temp_cursor.set(&*key) { + err.issues.push(field_err); + } + if value.is_none() { + field_cursor = temp_cursor.clone(); + if err.issues.len() > last_errc { + err.issues.remove(last_errc); + } + continue; + } + + let type_info: Option<(&'static str, JsonTypeInfo)> = + match &temp_cursor.to_string()[..] { + "report-type-id" => Some(("reportTypeId", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "id" => Some(("id", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "create-time" => Some(("createTime", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + "name" => Some(("name", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })), + _ => { + let suggestion = FieldCursor::did_you_mean(key, &vec!["create-time", "id", "name", "report-type-id"]); + err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string())))); + None + } + }; + if let Some((field_cursor_str, type_info)) = type_info { + FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor); + } + } + let mut request: api::Job = json::value::from_value(object).unwrap(); + let mut call = self.hub.jobs().create(request); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "on-behalf-of-content-owner" => { + call = call.on_behalf_of_content_owner(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["on-behalf-of-content-owner"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _jobs_delete(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.jobs().delete(opt.value_of("job-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "on-behalf-of-content-owner" => { + call = call.on_behalf_of_content_owner(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["on-behalf-of-content-owner"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _jobs_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.jobs().get(opt.value_of("job-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "on-behalf-of-content-owner" => { + call = call.on_behalf_of_content_owner(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["on-behalf-of-content-owner"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _jobs_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.jobs().list(); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "page-size" => { + call = call.page_size(arg_from_str(value.unwrap_or("-0"), err, "page-size", "integer")); + }, + "on-behalf-of-content-owner" => { + call = call.on_behalf_of_content_owner(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["page-token", "on-behalf-of-content-owner", "page-size"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _jobs_reports_get(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.jobs().reports_get(opt.value_of("job-id").unwrap_or(""), opt.value_of("report-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "on-behalf-of-content-owner" => { + call = call.on_behalf_of_content_owner(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["on-behalf-of-content-owner"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _jobs_reports_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.jobs().reports_list(opt.value_of("job-id").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "page-size" => { + call = call.page_size(arg_from_str(value.unwrap_or("-0"), err, "page-size", "integer")); + }, + "on-behalf-of-content-owner" => { + call = call.on_behalf_of_content_owner(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["page-token", "on-behalf-of-content-owner", "page-size"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _media_download(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut download_mode = false; + let mut call = self.hub.media().download(opt.value_of("resource-name").unwrap_or("")); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + if key == "alt" && value.unwrap_or("unset") == "media" { + download_mode = true; + } + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + if !download_mode { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + } else { + io::copy(&mut response, &mut ostream).unwrap(); + ostream.flush().unwrap(); + } + Ok(()) + } + } + } + } + + fn _report_types_list(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError) + -> Result<(), DoitError> { + let mut call = self.hub.report_types().list(); + for parg in opt.values_of("v").unwrap_or(Vec::new()).iter() { + let (key, value) = parse_kv_arg(&*parg, err, false); + match key { + "page-token" => { + call = call.page_token(value.unwrap_or("")); + }, + "page-size" => { + call = call.page_size(arg_from_str(value.unwrap_or("-0"), err, "page-size", "integer")); + }, + "on-behalf-of-content-owner" => { + call = call.on_behalf_of_content_owner(value.unwrap_or("")); + }, + _ => { + let mut found = false; + for param in &self.gp { + if key == *param { + found = true; + call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset")); + break; + } + } + if !found { + err.issues.push(CLIError::UnknownParameter(key.to_string(), + {let mut v = Vec::new(); + v.extend(self.gp.iter().map(|v|*v)); + v.extend(["page-token", "on-behalf-of-content-owner", "page-size"].iter().map(|v|*v)); + v } )); + } + } + } + } + let protocol = CallType::Standard; + if dry_run { + Ok(()) + } else { + assert!(err.issues.len() == 0); + for scope in self.opt.values_of("url").unwrap_or(Vec::new()).iter() { + call = call.add_scope(scope); + } + let mut ostream = match writer_from_opts(opt.value_of("out")) { + Ok(mut f) => f, + Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)), + }; + match match protocol { + CallType::Standard => call.doit(), + _ => unreachable!() + } { + Err(api_err) => Err(DoitError::ApiError(api_err)), + Ok((mut response, output_schema)) => { + let mut value = json::value::to_value(&output_schema); + remove_json_null_values(&mut value); + json::to_writer_pretty(&mut ostream, &value).unwrap(); + ostream.flush().unwrap(); + Ok(()) + } + } + } + } + + fn _doit(&self, dry_run: bool) -> Result, Option> { + let mut err = InvalidOptionsError::new(); + let mut call_result: Result<(), DoitError> = Ok(()); + let mut err_opt: Option = None; + match self.opt.subcommand() { + ("jobs", Some(opt)) => { + match opt.subcommand() { + ("create", Some(opt)) => { + call_result = self._jobs_create(opt, dry_run, &mut err); + }, + ("delete", Some(opt)) => { + call_result = self._jobs_delete(opt, dry_run, &mut err); + }, + ("get", Some(opt)) => { + call_result = self._jobs_get(opt, dry_run, &mut err); + }, + ("list", Some(opt)) => { + call_result = self._jobs_list(opt, dry_run, &mut err); + }, + ("reports-get", Some(opt)) => { + call_result = self._jobs_reports_get(opt, dry_run, &mut err); + }, + ("reports-list", Some(opt)) => { + call_result = self._jobs_reports_list(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("jobs".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("media", Some(opt)) => { + match opt.subcommand() { + ("download", Some(opt)) => { + call_result = self._media_download(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("media".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + ("report-types", Some(opt)) => { + match opt.subcommand() { + ("list", Some(opt)) => { + call_result = self._report_types_list(opt, dry_run, &mut err); + }, + _ => { + err.issues.push(CLIError::MissingMethodError("report-types".to_string())); + writeln!(io::stderr(), "{}\n", opt.usage()).ok(); + } + } + }, + _ => { + err.issues.push(CLIError::MissingCommandError); + writeln!(io::stderr(), "{}\n", self.opt.usage()).ok(); + } + } + + if dry_run { + if err.issues.len() > 0 { + err_opt = Some(err); + } + Err(err_opt) + } else { + Ok(call_result) + } + } + + // Please note that this call will fail if any part of the opt can't be handled + fn new(opt: ArgMatches<'a, 'n>) -> Result, InvalidOptionsError> { + let (config_dir, secret) = { + let config_dir = match cmn::assure_config_dir_exists(opt.value_of("folder").unwrap_or("~/.google-service-cli")) { + Err(e) => return Err(InvalidOptionsError::single(e, 3)), + Ok(p) => p, + }; + + match cmn::application_secret_from_directory(&config_dir, "youtubereporting1-secret.json", + "{\"installed\":{\"auth_uri\":\"https://accounts.google.com/o/oauth2/auth\",\"client_secret\":\"hCsslbCUyfehWMmbkG8vTYxG\",\"token_uri\":\"https://accounts.google.com/o/oauth2/token\",\"client_email\":\"\",\"redirect_uris\":[\"urn:ietf:wg:oauth:2.0:oob\",\"oob\"],\"client_x509_cert_url\":\"\",\"client_id\":\"620010449518-9ngf7o4dhs0dka470npqvor6dc5lqb9b.apps.googleusercontent.com\",\"auth_provider_x509_cert_url\":\"https://www.googleapis.com/oauth2/v1/certs\"}}") { + Ok(secret) => (config_dir, secret), + Err(e) => return Err(InvalidOptionsError::single(e, 4)) + } + }; + + let auth = Authenticator::new( &secret, DefaultAuthenticatorDelegate, + if opt.is_present("debug-auth") { + hyper::Client::with_connector(mock::TeeConnector { + connector: hyper::net::HttpsConnector::::default() + }) + } else { + hyper::Client::new() + }, + JsonTokenStorage { + program_name: "youtubereporting1", + db_dir: config_dir.clone(), + }, None); + + let client = + if opt.is_present("debug") { + hyper::Client::with_connector(mock::TeeConnector { + connector: hyper::net::HttpsConnector::::default() + }) + } else { + hyper::Client::new() + }; + let engine = Engine { + opt: opt, + hub: api::YouTubeReporting::new(client, auth), + gp: vec!["$-xgafv", "access-token", "alt", "bearer-token", "callback", "fields", "key", "oauth-token", "pp", "pretty-print", "quota-user", "upload-type", "upload-protocol"], + gpm: vec![ + ("$-xgafv", "$.xgafv"), + ("access-token", "access_token"), + ("bearer-token", "bearer_token"), + ("oauth-token", "oauth_token"), + ("pretty-print", "prettyPrint"), + ("quota-user", "quotaUser"), + ("upload-type", "uploadType"), + ("upload-protocol", "upload_protocol"), + ] + }; + + match engine._doit(true) { + Err(Some(err)) => Err(err), + Err(None) => Ok(engine), + Ok(_) => unreachable!(), + } + } + + fn doit(&self) -> Result<(), DoitError> { + match self._doit(false) { + Ok(res) => res, + Err(_) => unreachable!(), + } + } +} + +fn main() { + let mut exit_status = 0i32; + let arg_data = [ + ("jobs", "methods: 'create', 'delete', 'get', 'list', 'reports-get' and 'reports-list'", vec![ + ("create", + Some(r##"Creates a job and returns it."##), + "Details at http://byron.github.io/google-apis-rs/google_youtubereporting1_cli/jobs_create", + vec![ + (Some(r##"kv"##), + Some(r##"r"##), + Some(r##"Set various fields of the request structure, matching the key=value form"##), + Some(true), + Some(true)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("delete", + Some(r##"Deletes a job."##), + "Details at http://byron.github.io/google-apis-rs/google_youtubereporting1_cli/jobs_delete", + vec![ + (Some(r##"job-id"##), + None, + Some(r##"The ID of the job to delete."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("get", + Some(r##"Gets a job."##), + "Details at http://byron.github.io/google-apis-rs/google_youtubereporting1_cli/jobs_get", + vec![ + (Some(r##"job-id"##), + None, + Some(r##"The ID of the job to retrieve."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("list", + Some(r##"Lists jobs."##), + "Details at http://byron.github.io/google-apis-rs/google_youtubereporting1_cli/jobs_list", + vec![ + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("reports-get", + Some(r##"Gets the metadata of a specific report."##), + "Details at http://byron.github.io/google-apis-rs/google_youtubereporting1_cli/jobs_reports-get", + vec![ + (Some(r##"job-id"##), + None, + Some(r##"The ID of the job."##), + Some(true), + Some(false)), + + (Some(r##"report-id"##), + None, + Some(r##"The ID of the report to retrieve."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ("reports-list", + Some(r##"Lists reports created by a specific job. Returns NOT_FOUND if the job does not exist."##), + "Details at http://byron.github.io/google-apis-rs/google_youtubereporting1_cli/jobs_reports-list", + vec![ + (Some(r##"job-id"##), + None, + Some(r##"The ID of the job."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("media", "methods: 'download'", vec![ + ("download", + Some(r##"Method for media download. Download is supported on the URI `/v1/media/{+name}?alt=media`."##), + "Details at http://byron.github.io/google-apis-rs/google_youtubereporting1_cli/media_download", + vec![ + (Some(r##"resource-name"##), + None, + Some(r##"Name of the media that is being downloaded. See [][ByteStream.ReadRequest.resource_name]."##), + Some(true), + Some(false)), + + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ("report-types", "methods: 'list'", vec![ + ("list", + Some(r##"Lists report types."##), + "Details at http://byron.github.io/google-apis-rs/google_youtubereporting1_cli/report-types_list", + vec![ + (Some(r##"v"##), + Some(r##"p"##), + Some(r##"Set various optional parameters, matching the key=value form"##), + Some(false), + Some(true)), + + (Some(r##"out"##), + Some(r##"o"##), + Some(r##"Specify the file into which to write the program's output"##), + Some(false), + Some(false)), + ]), + ]), + + ]; + + let mut app = App::new("youtubereporting1") + .author("Sebastian Thiel ") + .version("0.3.2+20150923") + .about("An API to schedule reporting jobs and download the resulting bulk data reports about YouTube channels, videos etc. in the form of CSV files.") + .after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_youtubereporting1_cli") + .arg(Arg::with_name("url") + .long("scope") + .help("Specify the authentication a method should be executed in. Each scope requires the user to grant this application permission to use it.If unset, it defaults to the shortest scope url for a particular method.") + .multiple(true) + .takes_value(true)) + .arg(Arg::with_name("folder") + .long("config-dir") + .help("A directory into which we will store our persistent data. Defaults to a user-writable directory that we will create during the first invocation.[default: ~/.google-service-cli") + .multiple(false) + .takes_value(true)) + .arg(Arg::with_name("debug") + .long("debug") + .help("Output all server communication to standard error. `tx` and `rx` are placed into the same stream.") + .multiple(false) + .takes_value(false)) + .arg(Arg::with_name("debug-auth") + .long("debug-auth") + .help("Output all communication related to authentication to standard error. `tx` and `rx` are placed into the same stream.") + .multiple(false) + .takes_value(false)); + + for &(main_command_name, ref about, ref subcommands) in arg_data.iter() { + let mut mcmd = SubCommand::with_name(main_command_name).about(about); + + for &(sub_command_name, ref desc, url_info, ref args) in subcommands { + let mut scmd = SubCommand::with_name(sub_command_name); + if let &Some(desc) = desc { + scmd = scmd.about(desc); + } + scmd = scmd.after_help(url_info); + + for &(ref arg_name, ref flag, ref desc, ref required, ref multi) in args { + let arg_name_str = + match (arg_name, flag) { + (&Some(an), _ ) => an, + (_ , &Some(f)) => f, + _ => unreachable!(), + }; + let mut arg = Arg::with_name(arg_name_str) + .empty_values(false); + if let &Some(short_flag) = flag { + arg = arg.short(short_flag); + } + if let &Some(desc) = desc { + arg = arg.help(desc); + } + if arg_name.is_some() && flag.is_some() { + arg = arg.takes_value(true); + } + if let &Some(required) = required { + arg = arg.required(required); + } + if let &Some(multi) = multi { + arg = arg.multiple(multi); + } + scmd = scmd.arg(arg); + } + mcmd = mcmd.subcommand(scmd); + } + app = app.subcommand(mcmd); + } + + let matches = app.get_matches(); + + let debug = matches.is_present("debug"); + match Engine::new(matches) { + Err(err) => { + exit_status = err.exit_code; + writeln!(io::stderr(), "{}", err).ok(); + }, + Ok(engine) => { + if let Err(doit_err) = engine.doit() { + exit_status = 1; + match doit_err { + DoitError::IoError(path, err) => { + writeln!(io::stderr(), "Failed to open output file '{}': {}", path, err).ok(); + }, + DoitError::ApiError(err) => { + if debug { + writeln!(io::stderr(), "{:#?}", err).ok(); + } else { + writeln!(io::stderr(), "{}", err).ok(); + } + } + } + } + } + } + + std::process::exit(exit_status); +} \ No newline at end of file diff --git a/gen/youtubereporting1/Cargo.toml b/gen/youtubereporting1/Cargo.toml new file mode 100644 index 0000000000..f9f323b113 --- /dev/null +++ b/gen/youtubereporting1/Cargo.toml @@ -0,0 +1,29 @@ +# DO NOT EDIT ! +# This file was generated automatically from 'src/mako/Cargo.toml.mako' +# DO NOT EDIT ! +[package] + +name = "google-youtubereporting1" +version = "0.1.9+20150923" +authors = ["Sebastian Thiel "] +description = "A complete library to interact with YouTube Reporting (protocol v1)" +repository = "https://github.com/Byron/google-apis-rs/tree/master/gen/youtubereporting1" +homepage = "https://developers.google.com/youtube/reporting/v1/reports/" +documentation = "http://byron.github.io/google-apis-rs/google_youtubereporting1" +license = "MIT" +keywords = ["youtubereporting", "google", "protocol", "web", "api"] +build = "src/build.rs" + + +[dependencies] +hyper = ">= 0.6.8" +mime = "0.1.0" +serde = ">= 0.6.0" +serde_json = ">= 0.6.0" +yup-oauth2 = "*" +url = "*" + +[build-dependencies] +syntex = { version = "*" } +serde_codegen = { version = "*" } + diff --git a/gen/youtubereporting1/LICENSE.md b/gen/youtubereporting1/LICENSE.md new file mode 100644 index 0000000000..ae22e6ec52 --- /dev/null +++ b/gen/youtubereporting1/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/youtubereporting1/README.md b/gen/youtubereporting1/README.md new file mode 100644 index 0000000000..57b1685227 --- /dev/null +++ b/gen/youtubereporting1/README.md @@ -0,0 +1,189 @@ + +The `google-youtubereporting1` library allows access to all features of the *Google YouTube Reporting* service. + +This documentation was generated from *YouTube Reporting* crate version *0.1.9+20150923*, where *20150923* is the exact revision of the *youtubereporting:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. + +Everything else about the *YouTube Reporting* *v1* API can be found at the +[official documentation site](https://developers.google.com/youtube/reporting/v1/reports/). +# Features + +Handle the following *Resources* with ease from the central [hub](http://byron.github.io/google-apis-rs/google_youtubereporting1/struct.YouTubeReporting.html) ... + +* [jobs](http://byron.github.io/google-apis-rs/google_youtubereporting1/struct.Job.html) + * [*create*](http://byron.github.io/google-apis-rs/google_youtubereporting1/struct.JobCreateCall.html), [*delete*](http://byron.github.io/google-apis-rs/google_youtubereporting1/struct.JobDeleteCall.html), [*get*](http://byron.github.io/google-apis-rs/google_youtubereporting1/struct.JobGetCall.html), [*list*](http://byron.github.io/google-apis-rs/google_youtubereporting1/struct.JobListCall.html), [*reports get*](http://byron.github.io/google-apis-rs/google_youtubereporting1/struct.JobReportGetCall.html) and [*reports list*](http://byron.github.io/google-apis-rs/google_youtubereporting1/struct.JobReportListCall.html) +* [media](http://byron.github.io/google-apis-rs/google_youtubereporting1/struct.Media.html) + * [*download*](http://byron.github.io/google-apis-rs/google_youtubereporting1/struct.MediaDownloadCall.html) +* [report types](http://byron.github.io/google-apis-rs/google_youtubereporting1/struct.ReportType.html) + * [*list*](http://byron.github.io/google-apis-rs/google_youtubereporting1/struct.ReportTypeListCall.html) + + +Download supported by ... + +* [*download media*](http://byron.github.io/google-apis-rs/google_youtubereporting1/struct.MediaDownloadCall.html) + + + +# Structure of this Library + +The API is structured into the following primary items: + +* **[Hub](http://byron.github.io/google-apis-rs/google_youtubereporting1/struct.YouTubeReporting.html)** + * a central object to maintain state and allow accessing all *Activities* + * creates [*Method Builders*](http://byron.github.io/google-apis-rs/google_youtubereporting1/trait.MethodsBuilder.html) which in turn + allow access to individual [*Call Builders*](http://byron.github.io/google-apis-rs/google_youtubereporting1/trait.CallBuilder.html) +* **[Resources](http://byron.github.io/google-apis-rs/google_youtubereporting1/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_youtubereporting1/trait.Part.html)** + * a collection of properties + * never directly used in *Activities* +* **[Activities](http://byron.github.io/google-apis-rs/google_youtubereporting1/trait.CallBuilder.html)** + * operations to apply to *Resources* + +All *structures* are marked with applicable traits to further categorize them and ease browsing. + +Generally speaking, you can invoke *Activities* like this: + +```Rust,ignore +let r = hub.resource().activity(...).doit() +``` + +Or specifically ... + +```ignore +let r = hub.jobs().delete(...).doit() +let r = hub.jobs().reports_get(...).doit() +let r = hub.jobs().get(...).doit() +let r = hub.jobs().reports_list(...).doit() +let r = hub.jobs().list(...).doit() +let r = hub.jobs().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-youtubereporting1 = "*" +``` + +## A complete example + +```Rust +extern crate hyper; +extern crate yup_oauth2 as oauth2; +extern crate google_youtubereporting1 as youtubereporting1; +use youtubereporting1::{Result, Error}; +use std::default::Default; +use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +use youtubereporting1::YouTubeReporting; + +// 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 = YouTubeReporting::new(hyper::Client::new(), auth); +// You can configure optional parameters by calling 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().reports_list("jobId") + .page_token("sit") + .page_size(-65) + .on_behalf_of_content_owner("sed") + .doit(); + +match result { + Err(e) => match e { + // The Error enum provides details about what exactly happened. + // You can also just use its `Debug`, `Display` or `Error` traits + Error::HttpError(_) + |Error::MissingAPIKey + |Error::MissingToken(_) + |Error::Cancelled + |Error::UploadSizeLimitExceeded(_, _) + |Error::Failure(_) + |Error::BadRequest(_) + |Error::FieldClash(_) + |Error::JsonDecodeError(_, _) => println!("{}", e), + }, + Ok(res) => println!("Success: {:?}", res), +} + +``` +## Handling Errors + +All errors produced by the system are provided either as [Result](http://byron.github.io/google-apis-rs/google_youtubereporting1/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_youtubereporting1/trait.Delegate.html), or the [Authenticator Delegate](http://byron.github.io/google-apis-rs/google_youtubereporting1/../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 Downloads +If a method supports downloads, the response body, which is part of the [Result](http://byron.github.io/google-apis-rs/google_youtubereporting1/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_youtubereporting1/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_youtubereporting1/trait.Delegate.html) to the +[Method Builder](http://byron.github.io/google-apis-rs/google_youtubereporting1/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_youtubereporting1/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_youtubereporting1/trait.RequestValue.html) and +[decodable](http://byron.github.io/google-apis-rs/google_youtubereporting1/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_youtubereporting1/trait.Part.html) which are identifiable 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_youtubereporting1/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_youtubereporting1/trait.RequestValue.html) are moved + +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 **youtubereporting1** 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/youtubereporting1/src/build.rs b/gen/youtubereporting1/src/build.rs new file mode 100644 index 0000000000..4eb97c6a04 --- /dev/null +++ b/gen/youtubereporting1/src/build.rs @@ -0,0 +1,16 @@ +extern crate syntex; +extern crate serde_codegen; + +use std::env; +use std::path::Path; + +pub fn main() { + let out_dir = env::var_os("OUT_DIR").unwrap(); + + let src = Path::new("src/lib.rs.in"); + let dst = Path::new(&out_dir).join("lib.rs"); + + let mut registry = syntex::Registry::new(); + serde_codegen::register(&mut registry); + registry.expand("google-youtubereporting1", &src, &dst).unwrap(); +} diff --git a/gen/youtubereporting1/src/cmn.rs b/gen/youtubereporting1/src/cmn.rs new file mode 100644 index 0000000000..0e31353ba3 --- /dev/null +++ b/gen/youtubereporting1/src/cmn.rs @@ -0,0 +1,762 @@ +// COPY OF 'src/rust/api/cmn.rs' +// DO NOT EDIT +use std::io::{self, Read, Seek, Cursor, Write, SeekFrom}; +use std; +use std::fmt::{self, Display}; +use std::str::FromStr; +use std::error; +use std::thread::sleep_ms; + +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::h1::LINE_ENDING; +use hyper::method::Method; +use hyper::status::StatusCode; + +use serde_json as json; + +/// 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 {} + +/// Identifies types for building methods of a particular resource type +pub trait MethodsBuilder {} + +/// Identifies types which represent builders for a particular resource method +pub trait CallBuilder {} + +/// Identifies types which can be inserted and deleted. +/// Types with this trait are most commonly used by clients of this API. +pub trait Resource {} + +/// Identifies types which are used in API responses. +pub trait ResponseResult {} + +/// Identifies types which are used in API requests. +pub trait RequestValue {} + +/// Identifies types which are not actually used by the API +/// This might be a bug within the google API schema. +pub trait UnusedType {} + +/// Identifies types which are only used as part of other types, which +/// usually are carrying the `Resource` trait. +pub trait Part {} + +/// 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 {} + +/// 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 +} + +/// A utility to represent detailed errors we might see in case there are BadRequests. +/// The latter happen if the sent parameters or request structures are unsound +#[derive(Deserialize, Serialize, Debug)] +pub struct ErrorResponse { + error: ServerError, +} + +#[derive(Deserialize, Serialize, Debug)] +pub struct ServerError { + errors: Vec, + code: u16, + message: String, +} + +#[derive(Deserialize, Serialize, Debug)] +pub struct ServerMessage { + domain: String, + reason: String, + message: String, + #[serde(rename="locationType")] + location_type: Option, + location: 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 successful. That way, the delegate 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. + /// + /// If you choose to retry after a duration, the duration should be chosen using the + /// [exponential backoff algorithm](http://en.wikipedia.org/wiki/Exponential_backoff). + /// + /// Return retry information. + fn http_error(&mut self, &hyper::Error) -> 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 it as a general information about the + /// impending failure. + /// The given Error provides information about why the token couldn't be acquired in the + /// first place + fn token(&mut self, err: &error::Error) -> Option { + let _ = err; + 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/canceled, 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()`. + /// It will also be called with None after a successful upload, which allows the delegate + /// to forget the URL. That way, we will not attempt to resume an upload that has already + /// finished. + fn store_upload_url(&mut self, url: Option<&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: &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. + /// + /// If you choose to retry after a duration, the duration should be chosen using the + /// [exponential backoff algorithm](http://en.wikipedia.org/wiki/Exponential_backoff). + fn http_failure(&mut self, _: &hyper::client::Response, Option, _: 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 {} + + +#[derive(Debug)] +pub enum Error { + /// The http connection failed + HttpError(hyper::Error), + + /// 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), + + /// Represents information about a request that was not understood by the server. + /// Details are included. + BadRequest(ErrorResponse), + + /// 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(Box), + + /// 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(String, json::Error), + + /// Indicates an HTTP repsonse with a non-success status code + Failure(hyper::client::Response), +} + + +impl Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + Error::HttpError(ref err) => err.fmt(f), + Error::UploadSizeLimitExceeded(ref resource_size, ref max_size) => + writeln!(f, "The media size {} exceeds the maximum allowed upload size of {}" + , resource_size, max_size), + Error::MissingAPIKey => { + (writeln!(f, "The application's API key was not found in the configuration")).ok(); + writeln!(f, "It is used as there are no Scopes defined for this method.") + }, + Error::BadRequest(ref err) => { + try!(writeln!(f, "Bad Requst ({}): {}", err.error.code, err.error.message)); + for err in err.error.errors.iter() { + try!(writeln!(f, " {}: {}, {}{}", + err.domain, + err.message, + err.reason, + match &err.location { + &Some(ref loc) => format!("@{}", loc), + &None => String::new(), + })); + } + Ok(()) + }, + Error::MissingToken(ref err) => + writeln!(f, "Token retrieval failed with error: {}", err), + Error::Cancelled => + writeln!(f, "Operation cancelled by delegate"), + Error::FieldClash(field) => + writeln!(f, "The custom parameter '{}' is already provided natively by the CallBuilder.", field), + Error::JsonDecodeError(ref json_str, ref err) + => writeln!(f, "{}: {}", err, json_str), + Error::Failure(ref response) => + writeln!(f, "Http status indicates failure: {:?}", response), + } + } +} + +impl error::Error for Error { + fn description(&self) -> &str { + match *self { + Error::HttpError(ref err) => err.description(), + Error::JsonDecodeError(_, ref err) => err.description(), + _ => "NO DESCRIPTION POSSIBLE - use `Display.fmt()` instead" + } + } + + fn cause(&self) -> Option<&error::Error> { + match *self { + Error::HttpError(ref err) => err.cause(), + Error::JsonDecodeError(_, ref err) => err.cause(), + _ => None + } + } +} + +/// A universal result type used as return for all calls. +pub type Result = std::result::Result; + +/// 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 + 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 following macro invocation needs to be expanded, as `include!` +// doens't support external macros +// header!{ +// #[doc="The `X-Upload-Content-Type` header."] +// (XUploadContentType, "X-Upload-Content-Type") => [Mime] + +// xupload_content_type { +// test_header!( +// test1, +// vec![b"text/plain"], +// Some(HeaderField( +// vec![Mime(TopLevel::Text, SubLevel::Plain, Vec::new())] +// ))); + +// } +// } + +/// The `X-Upload-Content-Type` header. +/// +/// Generated via rustc --pretty expanded -Z unstable-options, and manually +/// processed to be more readable. +#[derive(PartialEq, Debug, Clone)] +pub struct XUploadContentType(pub Mime); + +impl ::std::ops::Deref for XUploadContentType { + type Target = Mime; + fn deref<'a>(&'a self) -> &'a Mime { &self.0 } +} +impl ::std::ops::DerefMut for XUploadContentType { + fn deref_mut<'a>(&'a mut self) -> &'a mut Mime { &mut self.0 } +} +impl Header for XUploadContentType { + fn header_name() -> &'static str { "X-Upload-Content-Type" } + fn parse_header(raw: &[Vec]) -> hyper::error::Result { + hyper::header::parsing::from_one_raw_str(raw).map(XUploadContentType) + } +} +impl HeaderFormat for XUploadContentType { + fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { + Display::fmt(&**self, f) + } +} +impl Display for XUploadContentType { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Display::fmt(&**self, f) + } +} + +#[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]) -> hyper::error::Result { + Err(hyper::error::Error::Method) + } +} + + +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]) -> hyper::error::Result { + if raw.len() > 0 { + let v = &raw[0]; + if let Ok(s) = std::str::from_utf8(v) { + const PREFIX: &'static str = "bytes "; + if s.starts_with(PREFIX) { + if let Ok(c) = ::from_str(&s[PREFIX.len()..]) { + return Ok(RangeResponseHeader(c)) + } + } + } + } + Err(hyper::error::Error::Method) + } +} + +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, 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, A> ResumableUploadHelper<'a, A> + where A: oauth2::GetToken { + + fn query_transfer_status(&mut self) -> std::result::Result> { + 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, None) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + return Err(Ok(r)) + } + }; + return Ok(h.0.last) + } + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + return Err(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() { + Ok(s) => s, + Err(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 + }; + + self.reader.seek(SeekFrom::Start(start)).unwrap(); + loop { + let request_size = match self.content_length - start { + rs if rs > chunk_size => chunk_size, + rs => rs + }; + + 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 + } + // workaround https://github.com/rust-lang/rust/issues/22252 + let res = 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(); + match res { + 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, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + } + return Some(Ok(res)) + }, + Err(err) => { + if let Retry::After(d) = self.delegate.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + return Some(Err(err)) + } + } + } + } +} + +// Copy of src/rust/cli/cmn.rs +// TODO(ST): Allow sharing common code between program types +pub fn remove_json_null_values(value: &mut json::value::Value) { + match *value { + json::value::Value::Object(ref mut map) => { + let mut for_removal = Vec::new(); + + for (key, mut value) in map.iter_mut() { + if value.is_null() { + for_removal.push(key.clone()); + } else { + remove_json_null_values(&mut value); + } + } + + for key in &for_removal { + map.remove(key); + } + } + _ => {} + } +} diff --git a/gen/youtubereporting1/src/lib.rs b/gen/youtubereporting1/src/lib.rs new file mode 100644 index 0000000000..e32c856ed7 --- /dev/null +++ b/gen/youtubereporting1/src/lib.rs @@ -0,0 +1,193 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/api/lib.rs.mako' +// DO NOT EDIT ! + +//! This documentation was generated from *YouTube Reporting* crate version *0.1.9+20150923*, where *20150923* is the exact revision of the *youtubereporting:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v0.1.9*. +//! +//! Everything else about the *YouTube Reporting* *v1* API can be found at the +//! [official documentation site](https://developers.google.com/youtube/reporting/v1/reports/). +//! The original source code is [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/youtubereporting1). +//! # Features +//! +//! Handle the following *Resources* with ease from the central [hub](struct.YouTubeReporting.html) ... +//! +//! * [jobs](struct.Job.html) +//! * [*create*](struct.JobCreateCall.html), [*delete*](struct.JobDeleteCall.html), [*get*](struct.JobGetCall.html), [*list*](struct.JobListCall.html), [*reports get*](struct.JobReportGetCall.html) and [*reports list*](struct.JobReportListCall.html) +//! * [media](struct.Media.html) +//! * [*download*](struct.MediaDownloadCall.html) +//! * [report types](struct.ReportType.html) +//! * [*list*](struct.ReportTypeListCall.html) +//! +//! +//! Download supported by ... +//! +//! * [*download media*](struct.MediaDownloadCall.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.YouTubeReporting.html)** +//! * a central object to maintain state and allow accessing all *Activities* +//! * creates [*Method Builders*](trait.MethodsBuilder.html) which in turn +//! allow access to individual [*Call Builders*](trait.CallBuilder.html) +//! * **[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* +//! +//! All *structures* are marked with applicable traits to further categorize them and ease browsing. +//! +//! Generally speaking, you can invoke *Activities* like this: +//! +//! ```Rust,ignore +//! let r = hub.resource().activity(...).doit() +//! ``` +//! +//! Or specifically ... +//! +//! ```ignore +//! let r = hub.jobs().delete(...).doit() +//! let r = hub.jobs().reports_get(...).doit() +//! let r = hub.jobs().get(...).doit() +//! let r = hub.jobs().reports_list(...).doit() +//! let r = hub.jobs().list(...).doit() +//! let r = hub.jobs().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-youtubereporting1 = "*" +//! ``` +//! +//! ## A complete example +//! +//! ```test_harness,no_run +//! extern crate hyper; +//! extern crate yup_oauth2 as oauth2; +//! extern crate google_youtubereporting1 as youtubereporting1; +//! use youtubereporting1::{Result, Error}; +//! # #[test] fn egal() { +//! use std::default::Default; +//! use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +//! use youtubereporting1::YouTubeReporting; +//! +//! // 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 = YouTubeReporting::new(hyper::Client::new(), auth); +//! // You can configure optional parameters by calling 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().reports_list("jobId") +//! .page_token("et") +//! .page_size(-70) +//! .on_behalf_of_content_owner("aliquyam") +//! .doit(); +//! +//! match result { +//! Err(e) => match e { +//! // The Error enum provides details about what exactly happened. +//! // You can also just use its `Debug`, `Display` or `Error` traits +//! Error::HttpError(_) +//! |Error::MissingAPIKey +//! |Error::MissingToken(_) +//! |Error::Cancelled +//! |Error::UploadSizeLimitExceeded(_, _) +//! |Error::Failure(_) +//! |Error::BadRequest(_) +//! |Error::FieldClash(_) +//! |Error::JsonDecodeError(_, _) => println!("{}", e), +//! }, +//! Ok(res) => println!("Success: {:?}", res), +//! } +//! # } +//! ``` +//! ## 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 Downloads +//! 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 identifiable 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 moved +//! +//! 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 +//! +//! + +// 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)] + +include!(concat!(env!("OUT_DIR"), "/lib.rs")); \ No newline at end of file diff --git a/gen/youtubereporting1/src/lib.rs.in b/gen/youtubereporting1/src/lib.rs.in new file mode 100644 index 0000000000..69c2651322 --- /dev/null +++ b/gen/youtubereporting1/src/lib.rs.in @@ -0,0 +1,2684 @@ +// DO NOT EDIT ! +// This file was generated automatically from 'src/mako/api/lib.rs.in.mako' +// DO NOT EDIT ! + +extern crate hyper; +extern crate serde; +extern crate serde_json; +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 serde_json as json; +use std::io; +use std::fs; +use std::thread::sleep_ms; + +pub use cmn::{MultiPartReader, ToParts, MethodInfo, Result, Error, CallBuilder, Hub, ReadSeek, Part, + ResponseResult, RequestValue, NestedType, Delegate, DefaultDelegate, MethodsBuilder, + Resource, ErrorResponse, remove_json_null_values}; + + +// ############## +// 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 YouTube Analytics reports for your YouTube content + YtAnalyticReadonly, + + /// View monetary and non-monetary YouTube Analytics reports for your YouTube content + YtAnalyticMonetaryReadonly, +} + +impl AsRef for Scope { + fn as_ref(&self) -> &str { + match *self { + Scope::YtAnalyticReadonly => "https://www.googleapis.com/auth/yt-analytics.readonly", + Scope::YtAnalyticMonetaryReadonly => "https://www.googleapis.com/auth/yt-analytics-monetary.readonly", + } + } +} + +impl Default for Scope { + fn default() -> Scope { + Scope::YtAnalyticReadonly + } +} + + + +// ######## +// HUB ### +// ###### + +/// Central instance to access all YouTubeReporting related resource activities +/// +/// # Examples +/// +/// Instantiate a new hub +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate yup_oauth2 as oauth2; +/// extern crate google_youtubereporting1 as youtubereporting1; +/// use youtubereporting1::{Result, Error}; +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use youtubereporting1::YouTubeReporting; +/// +/// // 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 = YouTubeReporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling 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().reports_list("jobId") +/// .page_token("dolores") +/// .page_size(-63) +/// .on_behalf_of_content_owner("accusam") +/// .doit(); +/// +/// match result { +/// Err(e) => match e { +/// // The Error enum provides details about what exactly happened. +/// // You can also just use its `Debug`, `Display` or `Error` traits +/// Error::HttpError(_) +/// |Error::MissingAPIKey +/// |Error::MissingToken(_) +/// |Error::Cancelled +/// |Error::UploadSizeLimitExceeded(_, _) +/// |Error::Failure(_) +/// |Error::BadRequest(_) +/// |Error::FieldClash(_) +/// |Error::JsonDecodeError(_, _) => println!("{}", e), +/// }, +/// Ok(res) => println!("Success: {:?}", res), +/// } +/// # } +/// ``` +pub struct YouTubeReporting { + client: RefCell, + auth: RefCell, + _user_agent: String, +} + +impl<'a, C, A> Hub for YouTubeReporting {} + +impl<'a, C, A> YouTubeReporting + where C: BorrowMut, A: oauth2::GetToken { + + pub fn new(client: C, authenticator: A) -> YouTubeReporting { + YouTubeReporting { + client: RefCell::new(client), + auth: RefCell::new(authenticator), + _user_agent: "google-api-rust-client/0.1.9".to_string(), + } + } + + pub fn jobs(&'a self) -> JobMethods<'a, C, A> { + JobMethods { hub: &self } + } + pub fn media(&'a self) -> MediaMethods<'a, C, A> { + MediaMethods { hub: &self } + } + pub fn report_types(&'a self) -> ReportTypeMethods<'a, C, A> { + ReportTypeMethods { 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.9`. + /// + /// 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 message for ReportingService.ListReportTypes. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where 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 report types](struct.ReportTypeListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ListReportTypesResponse { + /// A token to retrieve next page of results. Pass this value in the ListReportTypesRequest.page_token field in the subsequent call to `ListReportTypes` method to retrieve the next page of results. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// The list of report types. + #[serde(rename="reportTypes")] + pub report_types: Option>, +} + +impl ResponseResult for ListReportTypesResponse {} + + +/// Media 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*). +/// +/// * [download media](struct.MediaDownloadCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Media { + /// Name of the media resource. + #[serde(rename="resourceName")] + pub resource_name: Option, +} + +impl ResponseResult for Media {} + + +/// Response message for ReportingService.ListJobs. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where 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, Serialize, Deserialize)] +pub struct ListJobsResponse { + /// A token to retrieve next page of results. Pass this value in the ListJobsRequest.page_token field in the subsequent call to `ListJobs` method to retrieve the next page of results. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// The list of jobs. + pub jobs: Option>, +} + +impl ResponseResult for ListJobsResponse {} + + +/// A job creating reports of a specific 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*). +/// +/// * [delete jobs](struct.JobDeleteCall.html) (none) +/// * [reports get jobs](struct.JobReportGetCall.html) (none) +/// * [get jobs](struct.JobGetCall.html) (response) +/// * [reports list jobs](struct.JobReportListCall.html) (none) +/// * [list jobs](struct.JobListCall.html) (none) +/// * [create jobs](struct.JobCreateCall.html) (request|response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Job { + /// The type of reports this job creates. Corresponds to the ID of a ReportType. + #[serde(rename="reportTypeId")] + pub report_type_id: Option, + /// The server-generated ID of the job (max. 40 characters). + pub id: Option, + /// The name of the job (max. 100 characters). TODO(lanthaler) Clarify what this will actually be used for + pub name: Option, + /// The creation date/time of the job. + #[serde(rename="createTime")] + pub create_time: Option, +} + +impl RequestValue for Job {} +impl Resource for Job {} +impl ResponseResult for Job {} + + +/// Response message for ReportingService.ListReports. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where 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 list jobs](struct.JobReportListCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ListReportsResponse { + /// A token to retrieve next page of results. Pass this value in the ListReportsRequest.page_token field in the subsequent call to `ListReports` method to retrieve the next page of results. + #[serde(rename="nextPageToken")] + pub next_page_token: Option, + /// The list of report types. + pub reports: Option>, +} + +impl ResponseResult for ListReportsResponse {} + + +/// A 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*). +/// +/// * [list report types](struct.ReportTypeListCall.html) (none) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct ReportType { + /// The ID of the report type (max. 100 characters). + pub id: Option, + /// The name of the report type (max. 100 characters). + pub name: Option, +} + +impl Resource for ReportType {} + + +/// A report's metadata including the URL from which the report itself can be 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*). +/// +/// * [reports get jobs](struct.JobReportGetCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Report { + /// The URL from which the report can be downloaded (max. 1000 characters). + #[serde(rename="downloadUrl")] + pub download_url: Option, + /// The start of the time period that the report instance covers. The value is inclusive. + #[serde(rename="startTime")] + pub start_time: Option, + /// The server-generated ID of the report. + pub id: Option, + /// The end of the time period that the report instance covers. The value is exclusive. + #[serde(rename="endTime")] + pub end_time: Option, + /// The date/time when this report was created. + #[serde(rename="createTime")] + pub create_time: Option, + /// The ID of the job that created this report. + #[serde(rename="jobId")] + pub job_id: Option, +} + +impl ResponseResult for Report {} + + +/// A generic empty message that you can re-use to avoid defining duplicated empty messages in your APIs. A typical example is to use it as the request or the response type of an API method. For instance: service Foo { rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); } The JSON representation for `Empty` is empty JSON object `{}`. +/// +/// # Activities +/// +/// This type is used in activities, which are methods you may call on this type or where 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 jobs](struct.JobDeleteCall.html) (response) +/// +#[derive(Default, Clone, Debug, Serialize, Deserialize)] +pub struct Empty; + +impl ResponseResult for Empty {} + + + +// ################### +// MethodBuilders ### +// ################# + +/// A builder providing access to all methods supported on *media* resources. +/// It is not used directly, but through the `YouTubeReporting` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate yup_oauth2 as oauth2; +/// extern crate google_youtubereporting1 as youtubereporting1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use youtubereporting1::YouTubeReporting; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = YouTubeReporting::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `download(...)` +/// // to build up your call. +/// let rb = hub.media(); +/// # } +/// ``` +pub struct MediaMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a YouTubeReporting, +} + +impl<'a, C, A> MethodsBuilder for MediaMethods<'a, C, A> {} + +impl<'a, C, A> MediaMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Method for media download. Download is supported on the URI `/v1/media/{+name}?alt=media`. + /// + /// # Arguments + /// + /// * `resourceName` - Name of the media that is being downloaded. See [][ByteStream.ReadRequest.resource_name]. + pub fn download(&self, resource_name: &str) -> MediaDownloadCall<'a, C, A> { + MediaDownloadCall { + hub: self.hub, + _resource_name: resource_name.to_string(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + +/// A builder providing access to all methods supported on *reportType* resources. +/// It is not used directly, but through the `YouTubeReporting` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate yup_oauth2 as oauth2; +/// extern crate google_youtubereporting1 as youtubereporting1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use youtubereporting1::YouTubeReporting; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = YouTubeReporting::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.report_types(); +/// # } +/// ``` +pub struct ReportTypeMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a YouTubeReporting, +} + +impl<'a, C, A> MethodsBuilder for ReportTypeMethods<'a, C, A> {} + +impl<'a, C, A> ReportTypeMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Lists report types. + pub fn list(&self) -> ReportTypeListCall<'a, C, A> { + ReportTypeListCall { + hub: self.hub, + _page_token: Default::default(), + _page_size: Default::default(), + _on_behalf_of_content_owner: Default::default(), + _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 `YouTubeReporting` hub. +/// +/// # Example +/// +/// Instantiate a resource builder +/// +/// ```test_harness,no_run +/// extern crate hyper; +/// extern crate yup_oauth2 as oauth2; +/// extern crate google_youtubereporting1 as youtubereporting1; +/// +/// # #[test] fn egal() { +/// use std::default::Default; +/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// use youtubereporting1::YouTubeReporting; +/// +/// let secret: ApplicationSecret = Default::default(); +/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// hyper::Client::new(), +/// ::default(), None); +/// let mut hub = YouTubeReporting::new(hyper::Client::new(), auth); +/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders* +/// // like `create(...)`, `delete(...)`, `get(...)`, `list(...)`, `reports_get(...)` and `reports_list(...)` +/// // to build up your call. +/// let rb = hub.jobs(); +/// # } +/// ``` +pub struct JobMethods<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a YouTubeReporting, +} + +impl<'a, C, A> MethodsBuilder for JobMethods<'a, C, A> {} + +impl<'a, C, A> JobMethods<'a, C, A> { + + /// Create a builder to help you perform the following task: + /// + /// Deletes a job. + /// + /// # Arguments + /// + /// * `jobId` - The ID of the job to delete. + pub fn delete(&self, job_id: &str) -> JobDeleteCall<'a, C, A> { + JobDeleteCall { + hub: self.hub, + _job_id: job_id.to_string(), + _on_behalf_of_content_owner: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets the metadata of a specific report. + /// + /// # Arguments + /// + /// * `jobId` - The ID of the job. + /// * `reportId` - The ID of the report to retrieve. + pub fn reports_get(&self, job_id: &str, report_id: &str) -> JobReportGetCall<'a, C, A> { + JobReportGetCall { + hub: self.hub, + _job_id: job_id.to_string(), + _report_id: report_id.to_string(), + _on_behalf_of_content_owner: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Gets a job. + /// + /// # Arguments + /// + /// * `jobId` - The ID of the job to retrieve. + pub fn get(&self, job_id: &str) -> JobGetCall<'a, C, A> { + JobGetCall { + hub: self.hub, + _job_id: job_id.to_string(), + _on_behalf_of_content_owner: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Lists reports created by a specific job. Returns NOT_FOUND if the job does not exist. + /// + /// # Arguments + /// + /// * `jobId` - The ID of the job. + pub fn reports_list(&self, job_id: &str) -> JobReportListCall<'a, C, A> { + JobReportListCall { + hub: self.hub, + _job_id: job_id.to_string(), + _page_token: Default::default(), + _page_size: Default::default(), + _on_behalf_of_content_owner: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Lists jobs. + pub fn list(&self) -> JobListCall<'a, C, A> { + JobListCall { + hub: self.hub, + _page_token: Default::default(), + _page_size: Default::default(), + _on_behalf_of_content_owner: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } + + /// Create a builder to help you perform the following task: + /// + /// Creates a job and returns it. + /// + /// # Arguments + /// + /// * `request` - No description provided. + pub fn create(&self, request: Job) -> JobCreateCall<'a, C, A> { + JobCreateCall { + hub: self.hub, + _request: request, + _on_behalf_of_content_owner: Default::default(), + _delegate: Default::default(), + _scopes: Default::default(), + _additional_params: Default::default(), + } + } +} + + + + + +// ################### +// CallBuilders ### +// ################# + +/// Method for media download. Download is supported on the URI `/v1/media/{+name}?alt=media`. +/// +/// 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 `Media` structure that you would usually get. The latter will be a default value. +/// +/// A builder for the *download* method supported by a *media* resource. +/// It is not used directly, but through a `MediaMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_youtubereporting1 as youtubereporting1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use youtubereporting1::YouTubeReporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = YouTubeReporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.media().download("resourceName") +/// .doit(); +/// # } +/// ``` +pub struct MediaDownloadCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a YouTubeReporting, + _resource_name: String, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for MediaDownloadCall<'a, C, A> {} + +impl<'a, C, A> MediaDownloadCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Media)> { + use url::percent_encoding::{percent_encode, FORM_URLENCODED_ENCODE_SET}; + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "youtubereporting.media.download", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((2 + self._additional_params.len())); + params.push(("resourceName", self._resource_name.to_string())); + for &field in ["resourceName"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::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 >::as_ref(&value) != "json" { + enable = false; + } + break; + } + } + (field_present, enable) + }; + if json_field_missing { + params.push(("alt", "json".to_string())); + } + + let mut url = "https://youtubereporting.googleapis.com/v1/media/{+resourceName}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::YtAnalyticMonetaryReadonly.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{+resourceName}", "resourceName")].iter() { + let mut replace_with = String::new(); + for &(name, ref value) in params.iter() { + if name == param_name { + replace_with = value.to_string(); + break; + } + } + if find_this.as_bytes()[1] == '+' as u8 { + replace_with = percent_encode(replace_with.as_bytes(), FORM_URLENCODED_ENCODE_SET); + } + url = url.replace(find_this, &replace_with); + } + { + let mut indices_for_removal: Vec = Vec::with_capacity(1); + for param_name in ["resourceName"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + 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 Err(Error::JsonDecodeError(json_response, err)); + } + } + } else { (res, Default::default()) }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// Name of the media that is being downloaded. See [][ByteStream.ReadRequest.resource_name]. + /// + /// Sets the *resource 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 resource_name(mut self, new_value: &str) -> MediaDownloadCall<'a, C, A> { + self._resource_name = new_value.to_string(); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> MediaDownloadCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> MediaDownloadCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::YtAnalyticMonetaryReadonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> MediaDownloadCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Lists report types. +/// +/// A builder for the *list* method supported by a *reportType* resource. +/// It is not used directly, but through a `ReportTypeMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_youtubereporting1 as youtubereporting1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use youtubereporting1::YouTubeReporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = YouTubeReporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling the respective setters at will, and +/// // execute the final call using `doit()`. +/// // Values shown here are possibly random and not representative ! +/// let result = hub.report_types().list() +/// .page_token("justo") +/// .page_size(-1) +/// .on_behalf_of_content_owner("erat") +/// .doit(); +/// # } +/// ``` +pub struct ReportTypeListCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a YouTubeReporting, + _page_token: Option, + _page_size: Option, + _on_behalf_of_content_owner: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for ReportTypeListCall<'a, C, A> {} + +impl<'a, C, A> ReportTypeListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ListReportTypesResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "youtubereporting.reportTypes.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._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._on_behalf_of_content_owner { + params.push(("onBehalfOfContentOwner", value.to_string())); + } + for &field in ["alt", "pageToken", "pageSize", "onBehalfOfContentOwner"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://youtubereporting.googleapis.com/v1/reportTypes".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::YtAnalyticMonetaryReadonly.as_ref().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// A token identifying a page of results the server should return. Typically, this is the value of ListReportTypesResponse.next_page_token returned in response to the previous call to the `ListReportTypes` method. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> ReportTypeListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Requested page size. Server may return fewer report types than requested. If unspecified, server will pick an appropriate default. + /// + /// Sets the *page size* query property to the given value. + pub fn page_size(mut self, new_value: i32) -> ReportTypeListCall<'a, C, A> { + self._page_size = Some(new_value); + self + } + /// The content owner's external ID on which behalf the user is acting on. If not set, the user is acting for himself (his own channel). + /// + /// Sets the *on behalf of content owner* query property to the given value. + pub fn on_behalf_of_content_owner(mut self, new_value: &str) -> ReportTypeListCall<'a, C, A> { + self._on_behalf_of_content_owner = Some(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> ReportTypeListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> ReportTypeListCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::YtAnalyticMonetaryReadonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> ReportTypeListCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Deletes a job. +/// +/// A builder for the *delete* method supported by a *job* resource. +/// It is not used directly, but through a `JobMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_youtubereporting1 as youtubereporting1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use youtubereporting1::YouTubeReporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = YouTubeReporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling 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().delete("jobId") +/// .on_behalf_of_content_owner("sea") +/// .doit(); +/// # } +/// ``` +pub struct JobDeleteCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a YouTubeReporting, + _job_id: String, + _on_behalf_of_content_owner: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for JobDeleteCall<'a, C, A> {} + +impl<'a, C, A> JobDeleteCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, Empty)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "youtubereporting.jobs.delete", + http_method: hyper::method::Method::Delete }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("jobId", self._job_id.to_string())); + if let Some(value) = self._on_behalf_of_content_owner { + params.push(("onBehalfOfContentOwner", value.to_string())); + } + for &field in ["alt", "jobId", "onBehalfOfContentOwner"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://youtubereporting.googleapis.com/v1/jobs/{jobId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::YtAnalyticMonetaryReadonly.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{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(1); + for param_name in ["jobId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The ID of the job to delete. + /// + /// 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. + pub fn job_id(mut self, new_value: &str) -> JobDeleteCall<'a, C, A> { + self._job_id = new_value.to_string(); + self + } + /// The content owner's external ID on which behalf the user is acting on. If not set, the user is acting for himself (his own channel). + /// + /// Sets the *on behalf of content owner* query property to the given value. + pub fn on_behalf_of_content_owner(mut self, new_value: &str) -> JobDeleteCall<'a, C, A> { + self._on_behalf_of_content_owner = Some(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> JobDeleteCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> JobDeleteCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::YtAnalyticMonetaryReadonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> JobDeleteCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Gets the metadata of a specific report. +/// +/// A builder for the *reports.get* method supported by a *job* resource. +/// It is not used directly, but through a `JobMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_youtubereporting1 as youtubereporting1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use youtubereporting1::YouTubeReporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = YouTubeReporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling 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().reports_get("jobId", "reportId") +/// .on_behalf_of_content_owner("gubergren") +/// .doit(); +/// # } +/// ``` +pub struct JobReportGetCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a YouTubeReporting, + _job_id: String, + _report_id: String, + _on_behalf_of_content_owner: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for JobReportGetCall<'a, C, A> {} + +impl<'a, C, A> JobReportGetCall<'a, C, A> where 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: "youtubereporting.jobs.reports.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len())); + params.push(("jobId", self._job_id.to_string())); + params.push(("reportId", self._report_id.to_string())); + if let Some(value) = self._on_behalf_of_content_owner { + params.push(("onBehalfOfContentOwner", value.to_string())); + } + for &field in ["alt", "jobId", "reportId", "onBehalfOfContentOwner"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://youtubereporting.googleapis.com/v1/jobs/{jobId}/reports/{reportId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::YtAnalyticMonetaryReadonly.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{jobId}", "jobId"), ("{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 ["reportId", "jobId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The ID of the job. + /// + /// 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. + pub fn job_id(mut self, new_value: &str) -> JobReportGetCall<'a, C, A> { + self._job_id = new_value.to_string(); + self + } + /// The ID of the report to retrieve. + /// + /// 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. + pub fn report_id(mut self, new_value: &str) -> JobReportGetCall<'a, C, A> { + self._report_id = new_value.to_string(); + self + } + /// The content owner's external ID on which behalf the user is acting on. If not set, the user is acting for himself (his own channel). + /// + /// Sets the *on behalf of content owner* query property to the given value. + pub fn on_behalf_of_content_owner(mut self, new_value: &str) -> JobReportGetCall<'a, C, A> { + self._on_behalf_of_content_owner = Some(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> JobReportGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> JobReportGetCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::YtAnalyticMonetaryReadonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> JobReportGetCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Gets a job. +/// +/// A builder for the *get* method supported by a *job* resource. +/// It is not used directly, but through a `JobMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_youtubereporting1 as youtubereporting1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use youtubereporting1::YouTubeReporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = YouTubeReporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling 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("jobId") +/// .on_behalf_of_content_owner("aliquyam") +/// .doit(); +/// # } +/// ``` +pub struct JobGetCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a YouTubeReporting, + _job_id: String, + _on_behalf_of_content_owner: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for JobGetCall<'a, C, A> {} + +impl<'a, C, A> JobGetCall<'a, C, A> where 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: "youtubereporting.jobs.get", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len())); + params.push(("jobId", self._job_id.to_string())); + if let Some(value) = self._on_behalf_of_content_owner { + params.push(("onBehalfOfContentOwner", value.to_string())); + } + for &field in ["alt", "jobId", "onBehalfOfContentOwner"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://youtubereporting.googleapis.com/v1/jobs/{jobId}".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::YtAnalyticMonetaryReadonly.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{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(1); + for param_name in ["jobId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The ID of the job to retrieve. + /// + /// 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. + pub fn job_id(mut self, new_value: &str) -> JobGetCall<'a, C, A> { + self._job_id = new_value.to_string(); + self + } + /// The content owner's external ID on which behalf the user is acting on. If not set, the user is acting for himself (his own channel). + /// + /// Sets the *on behalf of content owner* query property to the given value. + pub fn on_behalf_of_content_owner(mut self, new_value: &str) -> JobGetCall<'a, C, A> { + self._on_behalf_of_content_owner = Some(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> JobGetCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> JobGetCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::YtAnalyticMonetaryReadonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Lists reports created by a specific job. Returns NOT_FOUND if the job does not exist. +/// +/// A builder for the *reports.list* method supported by a *job* resource. +/// It is not used directly, but through a `JobMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_youtubereporting1 as youtubereporting1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use youtubereporting1::YouTubeReporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = YouTubeReporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling 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().reports_list("jobId") +/// .page_token("no") +/// .page_size(-21) +/// .on_behalf_of_content_owner("justo") +/// .doit(); +/// # } +/// ``` +pub struct JobReportListCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a YouTubeReporting, + _job_id: String, + _page_token: Option, + _page_size: Option, + _on_behalf_of_content_owner: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for JobReportListCall<'a, C, A> {} + +impl<'a, C, A> JobReportListCall<'a, C, A> where 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: "youtubereporting.jobs.reports.list", + http_method: hyper::method::Method::Get }); + let mut params: Vec<(&str, String)> = Vec::with_capacity((6 + self._additional_params.len())); + params.push(("jobId", self._job_id.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._on_behalf_of_content_owner { + params.push(("onBehalfOfContentOwner", value.to_string())); + } + for &field in ["alt", "jobId", "pageToken", "pageSize", "onBehalfOfContentOwner"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://youtubereporting.googleapis.com/v1/jobs/{jobId}/reports".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::YtAnalyticMonetaryReadonly.as_ref().to_string(), ()); + } + + for &(find_this, param_name) in [("{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(1); + for param_name in ["jobId"].iter() { + if let Some(index) = params.iter().position(|t| &t.0 == param_name) { + indices_for_removal.push(index); + } + } + for &index in indices_for_removal.iter() { + params.remove(index); + } + } + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// The ID of the job. + /// + /// 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. + pub fn job_id(mut self, new_value: &str) -> JobReportListCall<'a, C, A> { + self._job_id = new_value.to_string(); + self + } + /// A token identifying a page of results the server should return. Typically, this is the value of ListReportsResponse.next_page_token returned in response to the previous call to the `ListReports` method. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> JobReportListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Requested page size. Server may return fewer report types than requested. If unspecified, server will pick an appropriate default. + /// + /// Sets the *page size* query property to the given value. + pub fn page_size(mut self, new_value: i32) -> JobReportListCall<'a, C, A> { + self._page_size = Some(new_value); + self + } + /// The content owner's external ID on which behalf the user is acting on. If not set, the user is acting for himself (his own channel). + /// + /// Sets the *on behalf of content owner* query property to the given value. + pub fn on_behalf_of_content_owner(mut self, new_value: &str) -> JobReportListCall<'a, C, A> { + self._on_behalf_of_content_owner = Some(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> JobReportListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> JobReportListCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::YtAnalyticMonetaryReadonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> JobReportListCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Lists jobs. +/// +/// A builder for the *list* method supported by a *job* resource. +/// It is not used directly, but through a `JobMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_youtubereporting1 as youtubereporting1; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use youtubereporting1::YouTubeReporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = YouTubeReporting::new(hyper::Client::new(), auth); +/// // You can configure optional parameters by calling 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() +/// .page_token("et") +/// .page_size(-17) +/// .on_behalf_of_content_owner("diam") +/// .doit(); +/// # } +/// ``` +pub struct JobListCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a YouTubeReporting, + _page_token: Option, + _page_size: Option, + _on_behalf_of_content_owner: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for JobListCall<'a, C, A> {} + +impl<'a, C, A> JobListCall<'a, C, A> where C: BorrowMut, A: oauth2::GetToken { + + + /// Perform the operation you have build so far. + pub fn doit(mut self) -> Result<(hyper::client::Response, ListJobsResponse)> { + use std::io::{Read, Seek}; + use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location}; + let mut dd = DefaultDelegate; + let mut dlg: &mut Delegate = match self._delegate { + Some(d) => d, + None => &mut dd + }; + dlg.begin(MethodInfo { id: "youtubereporting.jobs.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._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._on_behalf_of_content_owner { + params.push(("onBehalfOfContentOwner", value.to_string())); + } + for &field in ["alt", "pageToken", "pageSize", "onBehalfOfContentOwner"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://youtubereporting.googleapis.com/v1/jobs".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::YtAnalyticMonetaryReadonly.as_ref().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + let mut req_result = { + let mut client = &mut *self.hub.client.borrow_mut(); + let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// A token identifying a page of results the server should return. Typically, this is the value of ListReportTypesResponse.next_page_token returned in response to the previous call to the `ListJobs` method. + /// + /// Sets the *page token* query property to the given value. + pub fn page_token(mut self, new_value: &str) -> JobListCall<'a, C, A> { + self._page_token = Some(new_value.to_string()); + self + } + /// Requested page size. Server may return fewer jobs than requested. If unspecified, server will pick an appropriate default. + /// + /// Sets the *page size* query property to the given value. + pub fn page_size(mut self, new_value: i32) -> JobListCall<'a, C, A> { + self._page_size = Some(new_value); + self + } + /// The content owner's external ID on which behalf the user is acting on. If not set, the user is acting for himself (his own channel). + /// + /// Sets the *on behalf of content owner* query property to the given value. + pub fn on_behalf_of_content_owner(mut self, new_value: &str) -> JobListCall<'a, C, A> { + self._on_behalf_of_content_owner = Some(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> JobListCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> JobListCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::YtAnalyticMonetaryReadonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing 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, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + + +/// Creates a job and returns it. +/// +/// A builder for the *create* method supported by a *job* resource. +/// It is not used directly, but through a `JobMethods` instance. +/// +/// # Example +/// +/// Instantiate a resource method builder +/// +/// ```test_harness,no_run +/// # extern crate hyper; +/// # extern crate yup_oauth2 as oauth2; +/// # extern crate google_youtubereporting1 as youtubereporting1; +/// use youtubereporting1::Job; +/// # #[test] fn egal() { +/// # use std::default::Default; +/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; +/// # use youtubereporting1::YouTubeReporting; +/// +/// # let secret: ApplicationSecret = Default::default(); +/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, +/// # hyper::Client::new(), +/// # ::default(), None); +/// # let mut hub = YouTubeReporting::new(hyper::Client::new(), auth); +/// // As the method needs a request, you would usually fill it with the desired information +/// // into the 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(); +/// +/// // You can configure optional parameters by calling 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().create(req) +/// .on_behalf_of_content_owner("ipsum") +/// .doit(); +/// # } +/// ``` +pub struct JobCreateCall<'a, C, A> + where C: 'a, A: 'a { + + hub: &'a YouTubeReporting, + _request: Job, + _on_behalf_of_content_owner: Option, + _delegate: Option<&'a mut Delegate>, + _additional_params: HashMap, + _scopes: BTreeMap +} + +impl<'a, C, A> CallBuilder for JobCreateCall<'a, C, A> {} + +impl<'a, C, A> JobCreateCall<'a, C, A> where 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: "youtubereporting.jobs.create", + 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._on_behalf_of_content_owner { + params.push(("onBehalfOfContentOwner", value.to_string())); + } + for &field in ["alt", "onBehalfOfContentOwner"].iter() { + if self._additional_params.contains_key(field) { + dlg.finished(false); + return Err(Error::FieldClash(field)); + } + } + for (name, value) in self._additional_params.iter() { + params.push((&name, value.clone())); + } + + params.push(("alt", "json".to_string())); + + let mut url = "https://youtubereporting.googleapis.com/v1/jobs".to_string(); + if self._scopes.len() == 0 { + self._scopes.insert(Scope::YtAnalyticMonetaryReadonly.as_ref().to_string(), ()); + } + + + if params.len() > 0 { + url.push('?'); + url.push_str(&url::form_urlencoded::serialize(params)); + } + + let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default()); + let mut request_value_reader = + { + let mut value = json::value::to_value(&self._request); + remove_json_null_values(&mut value); + let mut dst = io::Cursor::new(Vec::with_capacity(128)); + json::to_writer(&mut dst, &value).unwrap(); + dst + }; + let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap(); + request_value_reader.seek(io::SeekFrom::Start(0)).unwrap(); + + + loop { + let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) { + Ok(token) => token, + Err(err) => { + match dlg.token(&*err) { + Some(token) => token, + None => { + dlg.finished(false); + return Err(Error::MissingToken(err)) + } + } + } + }; + let auth_header = Authorization(oauth2::Scheme { token_type: oauth2::TokenType::Bearer, + access_token: token.access_token }); + request_value_reader.seek(io::SeekFrom::Start(0)).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) + .header(UserAgent(self.hub._user_agent.clone())) + .header(auth_header.clone()) + .header(ContentType(json_mime_type.clone())) + .header(ContentLength(request_size as u64)) + .body(&mut request_value_reader); + + dlg.pre_request(); + req.send() + }; + + match req_result { + Err(err) => { + if let oauth2::Retry::After(d) = dlg.http_error(&err) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return Err(Error::HttpError(err)) + } + Ok(mut res) => { + if !res.status.is_success() { + let mut json_err = String::new(); + res.read_to_string(&mut json_err).unwrap(); + if let oauth2::Retry::After(d) = dlg.http_failure(&res, + json::from_str(&json_err).ok(), + json::from_str(&json_err).ok()) { + sleep_ms(d.num_milliseconds() as u32); + continue; + } + dlg.finished(false); + return match json::from_str::(&json_err){ + Err(_) => Err(Error::Failure(res)), + Ok(serr) => Err(Error::BadRequest(serr)) + } + } + let result_value = { + let mut json_response = String::new(); + res.read_to_string(&mut json_response).unwrap(); + match json::from_str(&json_response) { + Ok(decoded) => (res, decoded), + Err(err) => { + dlg.response_json_decode_error(&json_response, &err); + return Err(Error::JsonDecodeError(json_response, err)); + } + } + }; + + dlg.finished(true); + return Ok(result_value) + } + } + } + } + + + /// + /// Sets the *request* property to the given value. + /// + /// Even though 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) -> JobCreateCall<'a, C, A> { + self._request = new_value; + self + } + /// The content owner's external ID on which behalf the user is acting on. If not set, the user is acting for himself (his own channel). + /// + /// Sets the *on behalf of content owner* query property to the given value. + pub fn on_behalf_of_content_owner(mut self, new_value: &str) -> JobCreateCall<'a, C, A> { + self._on_behalf_of_content_owner = Some(new_value.to_string()); + self + } + /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong + /// while executing the actual API request. + /// + /// It should be used to handle progress information, and to implement a certain level of resilience. + /// + /// Sets the *delegate* property to the given value. + pub fn delegate(mut self, new_value: &'a mut Delegate) -> JobCreateCall<'a, C, A> { + self._delegate = Some(new_value); + self + } + + /// Set any additional parameter of the query string used in the request. + /// It should be used to set parameters which are not yet available through their own + /// setters. + /// + /// Please note that this method must not be used to set any of the known paramters + /// which have their own setter method. If done anyway, the request will fail. + /// + /// # Additional Parameters + /// + /// * *bearer_token* (query-string) - OAuth bearer token. + /// * *pp* (query-boolean) - Pretty-print response. + /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks. + /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart"). + /// * *access_token* (query-string) - OAuth access token. + /// * *fields* (query-string) - Selector specifying which fields to include in a partial response. + /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. + /// * *callback* (query-string) - JSONP + /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user. + /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. + /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart"). + /// * *alt* (query-string) - Data format for response. + /// * *$.xgafv* (query-string) - V1 error format. + pub fn param(mut self, name: T, value: T) -> JobCreateCall<'a, C, A> + where T: AsRef { + self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string()); + self + } + + /// Identifies the authorization scope for the method you are building. + /// + /// Use this method to actively specify which scope should be used, instead the default `Scope` variant + /// `Scope::YtAnalyticMonetaryReadonly`. + /// + /// The `scope` will be added to a set of scopes. This is important as one can maintain access + /// tokens for more than one scope. + /// + /// Usually there is more than one suitable scope to authorize an operation, some of which may + /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be + /// sufficient, a read-write scope will do as well. + pub fn add_scope(mut self, scope: T) -> JobCreateCall<'a, C, A> + where T: AsRef { + self._scopes.insert(scope.as_ref().to_string(), ()); + self + } +} + +